# How to loop and calculate length of each segment on a line having 2 distinct layers of points and lines?

I have a layer of polyline and a layer of points. My objective is to calculate the length of each segment along my polyline.

I tried a code but it returns the length between points that are not even contained in points layer.The picture below shows exactly what i need.

``````from math import sqrt
import itertools

layer = iface.activeLayer()
features = layer.getFeatures()
lines = [feature.geometry().asPolyline() for feature in features]
k = 0

for points in lines:
n = len(points)
list = range(n)
print "line" + str(k) + ", " + str(n) + " points"
length_segments = [sqrt(points[i].sqrDist(points[j]))
for i,j in itertools.combinations(list, 2)
if (j - i) == 1]
sum = 0

for length in length_segments:
i = length_segments.index(length)
print "segment = %d, length = %.2f" % (i, length)
sum += length

print "sum = ", sum
k += 1
``````
• So the points on the point layer are exactly the nodes of the lines? In your code, you do not access the point layer, and they seem to be completely separate datasets. Is it possible that your lines have nodes in between the points? You can check this by toggling the edit mode of the line layer (the yellow pencil) and then selecting a line with the node tool (the point with the hammer and the screwdriver). – LuWi Aug 3 '17 at 12:28
• Okay, thanks. And, just to clarify: You want distances between the points along the lines, not the distances between the nodes? – LuWi Aug 3 '17 at 12:42
• This sounds to me like you need some sort of routing algorithm. You might wanna look at docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/… – LuWi Aug 3 '17 at 12:46
• – LuWi Aug 3 '17 at 13:27
• Does anyone get an idea please? thanks – hounto Aug 8 '17 at 10:15