1

I look for an expression in QGIS field calculator, that calculates the distance between the centroid (red dot) of polygones (red polygones) of layer 1 and the nearest (point-) feature of layer 2 (green dot). (I don't want the centroid as a seperate layer, it should be calculated "on the flight". The calculated distance should be a new field in layer 1 attribute table)

I guess the necessary functions are "distance" and "closest_point" and "get_feature". I tried this expression:

distance(centroid($geometry), closest_point($geometry, get_feature( 'layer 2'))

but receive the notification that the function "get_feature" needs 2-3 arguments, but there are 3.

What would be the right expression?

enter image description here

2 Answers 2

4

Try this:

aggregate(
    'Point layer name/id',
    'min',
    distance(centroid(geometry(@parent)), $geometry)
)

use the aggregate function in min mode to calculate the distance from the centroid to each point.

1

You need to operate on layer where you will want to have the results. In your case layer 1.

You will use the functions distance, closest_point, get_feature_by_id, array_to_string, overlay_nearest.

Open field calculator and create a new field.

Try this

distance(
 centroid(@geometry), 
  closest_point(
    geometry(
     get_feature_by_id('green point layer id',
       array_to_string(
        overlay_nearest('green point layer id', "fid of green point layer")
                       )
                      )
                     )
                    , @geometry
                   )
                  )

This code was adapted by me from Find nearest line feature from point in QGIS, which was answered by @Babel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.