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? Thanks in advanceenter image description here

Mat Thias
  • 89
  • 3

2 Answers2

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.

Mayo
  • 3,902
  • 3
  • 22
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 this post, which was answered by @Babel.

Mauro_F
  • 33
  • 7