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?
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')
-
Fortunately, you mentioned the arguments required in the "geomwithin" function, as its help isn't available. – Jesús Pinilla Feb 26 at 11:57
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.
-
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
-
1Full 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 theid
of the layerpolygon
). The expression enginge has a very good help that explains syntax/arguments in detail. – Babel Feb 26 at 12:59