7

I have a layer with a single polygon and a layer with multiple points. Some of the points are inside the polygon. How can I create/update a field with a value of 1 (true) or 0 (false) depending if a point is inside the polygon.

Example from a similar question here.

I need to use this as part of a field calculator step in a graphical model. I've got scraps of code but I can't get the syntax for intersect expression right:

intersects(geometry('points'), geometry('polygon'))

I imagine using that along with some form of:

CASE
    WHEN
END

See below image for the problem:

Point in polygon

2 Answers 2

8

Use this expression: overlay_within('polygon') (see below for alternatives):

enter image description here

Just for your curiosity: the syntax for the intersects function is like this (returning 0/1):

intersects(
    $geometry,
    aggregate(
        'polygon',
        'collect',
        $geometry
   )
)

or:

intersects(
    $geometry,
    geometry (
        get_feature_by_id(
        'polygon',
        1)))
6
  • Thank you for the syntax clarification, that's great. Also thanks for Overlay_within, it works perfectly as a standalone process. Unfortunately it does not seem to work with the Field calculator in the graphical modeler. Instead, all the results of my "Within" field are 0 at the end of my modeler process. Any ideas? Commented Dec 14, 2021 at 21:56
  • 1
    Which QGIS version do you use? the overlay functions work formQGIS 3.16 on
    – Babel
    Commented Dec 14, 2021 at 22:11
  • I use 3.16. The overlay function works outside the graphical modeler, but it doesn't seem to work inside the modeler. Commented Dec 14, 2021 at 22:25
  • 1
    Does the intersects expression work in the modeler? Maybe you should ask another question here for this problem.
    – Babel
    Commented Dec 14, 2021 at 22:27
  • 2
    Does and will not work in modeler because you cannot reference a layer in expressions using the modeler. See github.com/qgis/QGIS/issues/30397#issuecomment-505699624
    – MrXsquared
    Commented Dec 14, 2021 at 23:41
6

Here is a solution that uses the CASE statement

CASE
    WHEN overlay_intersects('test2') THEN 1
    ELSE 0
END

result

p.s. 'test2' is the name of the polygon layer


I think that the CASE statement is useful when there are many conditions that have to be applied, if there are just two i.e. true/false, use the if condition instead, like:

if(overlay_intersects('test2'), 1, 0)

I will most likely use the solution provided by @Babel, however, when 1/0 is required instead of true/false, adjust the expression accordingly:

to_int(overlay_within('test2'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.