I have a line and a point layer. The points are manually set next to the line at specific places. Now I would like to get the distance between the end/start of the line and the points.
Distance from the black point along red line to start and to end of line:
- Distance from Blackpoint #1 along the red Line to Start (i.e. 5km)
- Distance from Blackpoint #1 along the red Line to End (i.e. 50km)
- Distance from Blackpoint #2 along the red Line to Start (i.e. 10km)
- Distance from Blackpoint #2 along the red Line to End (i.e. 45km)
As you can see in the image, the black points are not exactly ON the line. The closest line-node should give the result. I need to know the distances for every black point (I have hundreds of them!).
I'm looking for a QGIS, Python or PostGIS solution. Because the black points and the line are changeing some times, it would be great to have a "dynamic" approach without changeing the geometry of the line.
Best Answer
NOTE I edited the code because the questioner preferred to choose the track and the points he wanted to measure. The update in the code is the possibility to create a number of point output layers equal to the number of the line features but, if selected in the main dialog, this number could be lower.
I propose a solution using PyQGIS. My idea was creating a certain number of temporary points along the line and then using the nearest neighbor of them from each point of the input points (i.e. your Blackpoints) for measuring the distance from the start/end of the line.
Before posting the code, I need to do some remarks:
step
, which is simply the spatial interval for the creation of the temporary points (remember that the accuracy of the result heavily depend from this parameter!);The code will return a point memory layer which stores the same geometries and attributes of the input layer, plus two additional fields:
"DIST_START"
, which stores the distance from the start of the line;"DIST_END"
, which stores the distance from the end of the line.This is the code:
Now let's give an example. Starting from these sample layers (14 points, the line has a length of about 16 km) and using a
step
of 1 m:I obtain this point layer:
with this Attribute Table (the values are expressed in meters):