5

In QGIS 3.22.7 I want to count the number of points on point 'layer B' within 60m of each point on point 'layer A' and add a column to the data on point 'layer A'. What is wrong with the following equation?

I couldn't get it to work by rewriting A into B. All the elements are zero. Or can I do it with the processing tool's functionality?

aggregate(
    'A', 
    'count',
    $id,
    filter:=distance(
        $geometry,
        geometry('B' )
        ) <= 60
    ) 

I am referring to this post: Counting points within certain distance of each other in QGIS

2 Answers 2

4

You must perform the calculation on layer A.
There are some problems with your expression:

  1. The aggregate function allows to do some kind of a loop in the features of a layer, so you need to loop throw the objects of layer B filtering by distance. Some times this can looks confusing, because the field calculator is performing a loop and if you are using aggregates this will perform loops for every calculated feature.
  2. When you use the filter in the aggregate function you can use the @parent variable to refer to the current object that's being calculated.

The correct expression is:

aggregate(
    layer:='B', -- here you loop throw the features of layer B
    aggregate:='count',
    expression:=$id,
    filter:=distance( -- this filter will be used to filter features of layer B
        $geometry, -- here $geometry refers to the geometry of layer B
        geometry(@parent) -- @parent is a variable containing the current feature that's being calculated of layer A
        ) <= 60
    ) 
2
  • Thank you so much!!When I want to apply a filter to layer B, can I calculate it using only the field calculator? Do I need to output the filtered data once? Commented Oct 13, 2022 at 11:34
  • @osakanatengoku, With "apply a filter to layer B", you mean filter features of layer B that are between a fixed distance from a feature of layer A?
    – Mayo
    Commented Oct 14, 2022 at 19:21
3

Use this expression on layer A:

array_length(
    overlay_nearest (
        'B',
        $id,
        limit:=-1,
        max_distance:=60
    )
)

Blue points: layer B; red point: Layer A, labeled with the number of blue points within 60 meters, calculated with the expression above:

enter image description here

4
  • Thank you very much. It worked well. Commented Sep 26, 2022 at 12:58
  • When I want to apply a filter to layer B, can I calculate it using only the field calculator? Do I need to output the filtered data once? Commented Oct 13, 2022 at 11:33
  • According to the policy of this site, you should add another post as this is a new question
    – Babel
    Commented Oct 13, 2022 at 13:37
  • I see. Thank you. Commented Oct 13, 2022 at 22:38

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.