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:
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:
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.