6

I'd like to snap the blue points to the nearest yellow point based on an attribute they share on QGIS, this attribute is their suburb, I've tried by using the tool "geometry by expression" running the following expression:

closest_point(
 geometry(
   get_feature(
     'yellowpoints',
     'suburb',
     attribute(
       $currentfeature,
       'suburb'
     )
   )
 ),
 $geometry
)

However, It snaps the blue points only to one per each suburb.

enter image description here

Does anyone know any way to do this?

geozelot
  • 30,050
  • 4
  • 32
  • 56
Juan
  • 131
  • 2
  • Welcome, maybe here you find the solution: https://gis.stackexchange.com/questions/391120/qgis-expression-with-overlay-fuction-filter-condition-based-on-comparison-of-at – pigreco Mar 25 '22 at 08:24

2 Answers2

3

QGIS documentation for get_feature() function says:

Returns the first feature of a layer matching a given attribute value.

That's why you get always the same point. Try with an aggregate, something like this:

aggregate(
    layer:='yellowpoints',
    aggregate:='array_agg',
    expression:=$geometry,
    filter:="suburb" = attribute(
        @parent,
        'suburb'
    ),
    order_by:=distance(
        geometry(@parent),
        $geometry
    )
)[-1]

Other option is.

closest_point(
    aggregate(
        layer:='yellowpoints',
        aggregate:='collect',
        expression:=$geometry,
        filter:="suburb" = attribute(
            @parent,
            'suburb'
        )
    ),
    $geometry
)
MrXsquared
  • 34,292
  • 21
  • 67
  • 117
Mayo
  • 3,902
  • 3
  • 22
3

You can also use the processing tool "Snap Vertices To Nearest Points By Condition" from ProcessX Plug-In.

Choose your blue points as Source Layer, your yellow points layer as Points Layer, select all options in Snap Vertices and your two suburb indicator fields as condition with = as comparison operator:

enter image description here

Disclaimer: I am the author of this Plug-In.

MrXsquared
  • 34,292
  • 21
  • 67
  • 117