qgis – Selecting Points Inside a Polygon Layer Using Aggregate Function in QGIS

qgisqgis-expression

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) 
)

enter image description here

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.

enter image description here

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:

select *, pt.geometry 
from "area_and_points(1) — points" as pt, 
"area_and_points(1) — polygons" as poly
where st_within ( pt.geometry, poly.geometry)

enter image description here

Using QGIS expressions

  1. Create a new attribute name on the point layer with this expression, using Field calculator:

    overlay_within(
        'polygons_e2b7c2ad_6eec_4a0a_b6cc_2b580b12acef',
        name
    )[0]
    
  2. Extract the points that are within polygons to a new layer with Geometry by expression and the following expression:

    case 
    when 
        overlay_within(
            'polygons_e2b7c2ad_6eec_4a0a_b6cc_2b580b12acef'
        )
    then $geometry
    end
    

    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

Related Question