1

enter image description hereI 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.

enter image description here

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
  • Let us continue this discussion in chat. – LuWi Aug 3 '17 at 13:27
  • Does anyone get an idea please? thanks – hounto Aug 8 '17 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.