QGIS – Finding Maximum Possible Distance from Point to Polygon Boundary Using Expression

maximumpoint-in-polygonproximityqgisqgsexpression

Points layer is structured as below

Attributes Table of points layer

Polygons layer also has code as a field

For each point, I want to get maximum possible distance to the edge of the polygons listed with code in the overlap column. Line must not leave the polygon at any point e.g. in the case of complex polygon shapes.

The red arrow is the max distance to the edge

enter image description here

I tried this from the Field Calculator on the points layer: seems to work but gives more distances than overlaps! If there are two overlaps I need two maximum distances.

array_to_string(
    array_foreach(
        array_distinct(string_to_array("overlaps", ',')),
        format_number(
            maximum(
                distance(
                    $geometry,
                    boundary(
                        geometry(
                            get_feature('polygons___majorlang_6318baec_9d66_4f7c_ae25_a2b3a2e2ec27', 'code', trim(@element))
                        )
                    )
                )
            ),
            2
        )
    ),
    ', '
)

enter image description here

Best Answer

Use the following expression to find the vertex most distant (farthes) from a point inside a polygon - replace polygon on line 3 with the name of your polygon layer:

with_variable(
    'vertices',
    geometries_to_array (nodes_to_points( overlay_within ('polygon', $geometry)[0])),
with_variable(
    'max',
    array_max(
        array_foreach (@vertices, length (make_line($geometry,@element)))
    ),
    array_filter (
        array_foreach (
            @vertices,
            if (length (make_line($geometry,@element)) = @max, @element, NULL)
        ),
        @element is not NULL
    )
))[0]

The expression checks for each vertex of the blue polygon the distance to the orange point (black dotted line; just for visualization) and returns just the vertex with the largest distance; the yellow circle (buffer) shows that indeed, the red point is the farthes away from the orange one: enter image description here

Related Question