# Measure distance between vertices of polylines in QGIS for Desktop

I have this dataset of coordinates of electric lines in the form of vector polylines as shown in the image below, and I need to measure the distance between the first and last vertex of each line and all the other line vertices on the layer using PyQGIS. For example, take the first vertex of the first line and measure the distance between this one and all the others on the layer; then take the last vertex of the first line and measure all the distances, and repeat the same for the second line and so on.

I think that a good solution is to get the coordinates of the first and last vertices for each feature, save them as a point and then apply the method explained in this post: Measure distances between specific features in QGIS for Desktop to get the distances between points. If you want to take advantage of the former code you can do that:

``````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
``````

This code calculates each segment length (corroborated with "Measure Line Tool") in all lines; as you can see for the line vector layer of below image: Result at the Python Console was:

``````line0, 4 points
segment = 0, length = 21735.11
segment = 1, length = 20208.88
segment = 2, length = 38158.48
sum =  80102.4682351
line1, 7 points
segment = 0, length = 18831.03
segment = 1, length = 50481.12
segment = 2, length = 30119.61
segment = 3, length = 26176.50
segment = 4, length = 47111.79
segment = 5, length = 21697.58
sum =  194417.62525
line2, 5 points
segment = 0, length = 23266.31
segment = 1, length = 21186.16
segment = 2, length = 23595.18
segment = 3, length = 25817.39
sum =  93865.0436374
``````

The total length of each line, as sum of all its individual segments, it is also calculated.

• Thank you very much again xunilk! Very useful and clear. Oct 1, 2015 at 14:44