QGIS – Retrieving Attribute Field from Polygon Feature Containing Point Feature

expressionfield-calculatorfields-attributespoint-in-polygonqgis

I am trying to populate a point layer's field attribute with values from polygon features' attributes that contain point features.

The inverse is very simple:

aggregate(
    layer:='point layer's name',
    aggregate:='max',
    expression:="point layer's field name",
    filter:=intersects($geometry, geometry(@parent))
    )

I need to do the exact opposite, get the attribute from the polygon feature and populate the points contained in said polygon.

I have tried contains/intersects/overlaps/crosses/touches/within to no avail.

I'm limited to doing this with the Field calculator expression or potentially PyQGIS, no SQL or DB Manager.

Best Answer

Firstly make sure that your layers spatially overlap i.e. the same location and the same CRS.

Secondly as it says in the documentation for aggregate() function:

The source feature can be accessed with the variable @parent.

So, you can try either this:

aggregate(
    layer:='polygon layer's name',
    aggregate:='max',
    expression:="polygon layer's field name", 
    filter:=contains($geometry, geometry(@parent))
    )

or this:

aggregate(
    layer:='polygon layer's name',
    aggregate:='max',
    expression:="polygon layer's field name", 
    filter:=within(geometry(@parent), $geometry)
    )

Alternatively you can achieve the desired output with the overlay_within() and array_max()functions:

array_max(
    overlay_within(
        layer:='polygon layer's name',
        expression:="polygon layer's field name"
        )
    )
Related Question