Calculating the distance between the furthest vertex of a Voronoi polygon and the point from which it was generated
You can use the following script. Paste the script into QGIS Python Editor. Change layers' name in the first two lines and common field name and run.
# get layers
Voronoi = QgsProject.instance().mapLayersByName("Voronoi")[0]
Points = QgsProject.instance().mapLayersByName("Points")[0]
def to_geom(vertex): # for creating QgsGeometry from vertex
return QgsGeometry.fromPointXY(QgsPointXY(vertex))
Voronoi.startEditing()
# add "max_dist" field if it doesn't exist
if Voronoi.fields().indexFromName('max_dist') == -1:
Voronoi.addAttribute(QgsField('max_dist', 6, len=10, prec=3)) # 6 means Double
for vor in Voronoi.getFeatures():
# get Voronoi cell point geometry. there is only one point
request = "POINT_ID = '{0}'".format(vor["POINT_ID"]) # POINT_ID is a string here
point = list(Points.getFeatures(request))[0].geometry()
# vertices of Voronoi polygon
vx = vor.geometry().vertices()
# distances to all vertices from point
distances = [point.distance(to_geom(v)) for v in vx]
vor['max_dist'] = max(distances)
Voronoi.updateFeature(vor)
Voronoi.commitChanges()
Result:
To add a second possible solution at your request, using only the Field Calculator, you can calculate the maximum distance between the furthest vertex of a Voronoi polygon and the point that generated it using the following expression on the Voronoi polygon layer:
array_max(
array_foreach(
array_foreach(
generate_series(1,num_geometries( nodes_to_points($geometry))),
make_line(
geometry_n(nodes_to_points($geometry),@element),
aggregate('point','array_agg',$geometry,"id" = attribute(@parent,'id'))
)
), length(@element)
)
)
The expression will create a label (or a new field) with the maximum requested value.
NB. array_sum
is not yet part of the QGIS core. To use it, you need to install the plugin arrayPlus that integrate some more arrays into your Field calculator.
In your case, the expression to use will be
array_max(
array_foreach(
array_foreach(
generate_series(1,num_geometries( nodes_to_points($geometry))),
make_line(
geometry_n(nodes_to_points($geometry),@element),
aggregate('NODI TOPOIETI','array_agg',$geometry,"ID_NODO" =
attribute(@parent,'ID_NODO'))
)
), length(@element)
)
)
An example in the figure below, where are also shown the lines used to do the calculation, created by Geometry Generator using the expression
collect_geometries(
array_foreach(
generate_series(1,num_geometries( nodes_to_points( $geometry))),
make_line(
geometry_n(nodes_to_points($geometry),@element),
aggregate('point','array_agg',$geometry, "id" = attribute (@parent,'id'))
)
)
)