# Calculate the distance between multiple points within a buffer in QGIS

I am very new to QGIS so please bear with me.

Attached is an image of my QGIS project so far. In this, you have the pinkish points of the "Point_centers" layer and green points labeled "Point_trees" which are tree species that I am interested in. What I want to do is calculate the distance of the Point_centers to all the Point_trees within the 15 meter buffer layer I created. I want it to calculate the distances regardless whether or not the Trees overlap in different buffers.

To get the distance from the center point to each tree inside the buffer, use this expression:

``````array_foreach (
overlay_nearest(
'Point_trees',
\$geometry,
max_distance:=15,
limit:=-1
),
length (
make_line (
\$geometry,
@element
)
)
)
``````

This generates an array of distances from the center to each tree inside the buffer. The get the sum of all distances, enclose the expression in an `array_sum()` function.

The expression calculates the lengths of the black lines. These lines here are created based on the same expression for visualization purpose:

To calculate the distances in a table:

1. First ensure that your buffers layer and trees layer have a field with a unique identifier. I used `tree_id` and `buffer_id`.

2. Perform a spatial join between the trees and the buffers using a one-to-many join type. This will give you a new points layer where points are duplicated when they are within more than one buffer.

Tree `T23` now appears 3 times, in buffers `2`, `3`, and `4`.

1. Then use this expression in the Field Calculator on the joined layer:
``````length(
make_line(
\$geometry,
centroid(geometry(get_feature(                  -- get the centroid of the buffer that matches the buffer_id of the joined point.
layer:='buffers',
attribute:='buffer_id',   -- 'buffer_id' in single quotes is the field name
value:="buffer_id")))     -- "buffer_id" in double quotes is the field value of the current joined point

)
)
``````

Now each tree point has a distance to its corresonding buffer centroid:

Example:

(The lines are for visualisation purposes only)

You can use a virtual layer to compute the distance and optionally draw a line to the center point.

Go the the menu `layer / add layer / add-edit virtual layer` and enter the following query. You can add any field from the point or polygon layer.

``````select make_line(pt.geometry, st_centroid(poly.geometry)) as geometry,
st_distance(pt.geometry, st_centroid(poly.geometry)) as dist
from myPolygonLayer poly
join myPointLayer pt
on st_intersects(pt.geometry,poly.geometry)
``````

PS: See how accurate is my buffer polygon?! That's why it is usually better NOT to select point within a buffer, but rather to select points within a distance of another point.