# Counting number of points in one layer within fixed distance to points in another layer in QGIS

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

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
)
``````
• 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? 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
Oct 14, 2022 at 19:21

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:

• Thank you very much. It worked well. 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? Oct 13, 2022 at 11:33
• According to the policy of this site, you should add another post as this is a new question Oct 13, 2022 at 13:37
• I see. Thank you. Oct 13, 2022 at 22:38