This question arose from a comment on this answer to Calculating distance between multiple points within buffer using QGIS.
I have followed the steps there, which use a one-to-many spatial join to generate separate features for each point that is within a buffer polygon in another layer (called buffers
). Points that fall within multiple buffers are duplicated. The result is a layer called joined
. The points layer has a field called buffer_id
containing the id of the joined buffer polygon.
The lines connecting the points with their associated buffer centroid can be visualised using a Geometry Generator symbol layer like so:
collect_geometries(
array_foreach(
overlay_within(
'buffers',
@geometry
),
make_line(@geometry, centroid(@element))
)
)
How can I create the labels for the lines as shown in the screenshot?
Best Answer
Prerequisite
For this solution to work, the point layer must have a field (in this example called
buffer_id
) that contains the id of the joined buffer polygon. The solution was implemented in QGIS 3.30.3.Label values
The values for the labels are generated with this expression:
The expression finds the feature in the
buffers
layer where the buffer_id matches the joined field in the points layer, makes a line from the buffer centroid to the current point and gets the length of that line.The expression is entered by clicking the button next to the Value text edit. The mode is changed to
Offset from point
and the lower center quadrant is selected.Label placement
The labels are placed at the midpoint of the connecting lines using this expression:
The expression is entered by checking Geometry Generator and clicking on the ... button next to the text edit area.
Point / MultiPoint
is chosen as the geometry type.Label rotation
The labels are rotated parallel to the line using this expression:
The expression is entered as a Data defined override by clicking the button next to Rotation in the
Data defined
section