I have two layers (polygons and points) in a geopackage (area_and_points.gpkg, LINK). I need to extract all point that lie within the polygons and also inherit one attribute (Name
in this case) from that polygons. I want to use aggregate expression to solve this. I used the following "Geometry Generator" code on the points layer. I get an empty layer.
aggregate(
layer:='polygons',
aggregate:='collect',
expression:=intersection(geometry(@parent),$geometry),
filter:=intersects(geometry(@parent), $geometry)
)
It even shows "Preview: <geometry: MultiPoint>". But the result is that there is no actual filtering and the generator geometry (Modified geometry) has all the points (15 in this case) as shown in the image below. I would be happy to get any solution using expression
.
I am not even getting the points filtered what to speak of adding the attribute (Name
).
Best Answer
There are different options: 1) select points inside polygons and copy/paste them to a new layer (fastest and easiest); 2) Virtual layer (most elegant) 3) using QGIS expressions (a bit cumbersome with with some shortcomings). In detail:
Remark: changing you layer names to something easier than
area_and_points(1) — points
could be a good idea.Solution 1: copy/paste selected features
Use Select by expression to select the points inside the polygons using
overlay_within ('polygons')
(use the name of your polygon layer).Then copy/paste the selected features to a new layer. Add the name of the polygon layer they are within using the expression in step 1 of solution 3 below.
Solution 2: virtual layer
Create a virtual layer with this query:
Using QGIS expressions
Create a new attribute
name
on the point layer with this expression, using Field calculator:Extract the points that are within polygons to a new layer with Geometry by expression and the following expression:
However, you will get a layer with all features from the initial layer, but the points outside polygons will come without features (only attributes) - so you probably want to delete these using Remove null geometries