7

I'm working with QGIS 3.16 Hannover under MacOS 10.13 environment. I've got a point and a polygon shapefile layers. I want to add a new field to my point layer with the id of the polygon that contains it. Is it possible to do so with the field calculator, instead of creating a new layer?

9

You can use refFunctions Plugin. It adds custom user functions to QGIS Field Calculator. Then, you can add a new field to the point layer with the id of the polygon that contains it using the following expression in Field Calculator for the point layer:

geomwithin('polygon_layer_name', 'id_field_of_polygon_layer')

enter image description here

1
  • Fortunately, you mentioned the arguments required in the "geomwithin" function, as its help isn't available. – Jesús Pinilla Feb 26 at 11:57
10

There is also a possibility without need to install a plugin, simply using this expression. overlay_within() is available since QGIS 3.16, in fact implementing the functions of the refFunctions plugin in QGIS natively: https://qgis.org/en/site/forusers/visualchangelog316/#port-reffunctions-to-core

array_to_string (overlay_within('polygon', id))

The first argument of the overlay_within() function is the layer it refers to, the second one an expression executed on this layer (here: simply a field name). Add the function to_int() to get an integer instead of a string as output type.

enter image description here

2
  • Although needing to install a complement, I find easier to implement the solution proposed by @Kadir Şahbaz. Not clear for me the arguments required by the overlay_within function – Jesús Pinilla Feb 26 at 11:55
  • 1
    Full syntax of the function is: overlay_within(layer[,expression][,filter][,limit][,cache=false]) - parts in brackets [] are optional. So the first argument is the layer you want to refer to (here: polygon), the second one the expression, here: id (as you want to get the id of the layer polygon). The expression enginge has a very good help that explains syntax/arguments in detail. – Babel Feb 26 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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