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?
3 Answers 3
This plugin is deprecated!
The plugin is outdated as of QGIS 3.14 due to the introduction of the new functions for geometry overlay expressions
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.jpinilla– jpinilla2021年02月26日 11:57:47 +00:00Commented Feb 26, 2021 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 functionjpinilla– jpinilla2021年02月26日 11:55:04 +00:00Commented Feb 26, 2021 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– Babel2021年02月26日 12:59:27 +00:00Commented Feb 26, 2021 at 12:59
Currently a bit "old-fashioned" approach using the aggregate()
function:
aggregate(
layer:='polygon_layer',
aggregate:='concatenate',
concatenator:=',',
expression:=to_string("id"),
filter:=contains($geometry, geometry(@parent))
)
Explore related questions
See similar questions with these tags.