I am now trying to get the length of a shortest path using dijkstra(). I need it to find all the points in my sample, which are located more than 25 km away along roads from district centres. I will loop it, but before I do this I need to get the path's length.

When I enter the following code, it only shows me the shortest path highlighted in red, but not its length. How can I modify it in order to get length in km? (In case it is important, my crs is North_Pole_Lambert_Azimuthal_Equal_Area)

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

vl = qgis.utils.iface.mapCanvas().currentLayer()
director = QgsLineVectorLayerDirector(vl, -1, '', '', '', 3)
properter = QgsDistanceArcProperter()
crs = qgis.utils.iface.mapCanvas().mapRenderer().destinationCrs()
builder = QgsGraphBuilder(crs)

pStart = QgsPoint(2327292.145, -2732901.348)
pStop = QgsPoint(2328327.741, -2732822.68)

tiedPoints = director.makeGraph(builder, [pStart, pStop])
graph = builder.graph()

tStart = tiedPoints[0]
tStop = tiedPoints[1]

idStart = graph.findVertex(tStart)
idStop = graph.findVertex(tStop)
(tree, cost) = QgsGraphAnalyzer.dijkstra(graph, idStart, 0)
if tree[idStop] == -1:
  print ("Path not found")
  p = []
  curPos = idStop
  while curPos != idStart:
    curPos = graph.arc(tree[curPos]).outVertex();
  rb = QgsRubberBand(qgis.utils.iface.mapCanvas())
  for pnt in p:
  • 1
    Welcome to GIS SE! As a new user please take the Tour that introduces you to this site and its protocols. In your question you talked about a path highlighted in red, but there's no reference to it: maybe you may add a screenshot of what do you see for better explaining your issue.
    – mgri
    Feb 15, 2017 at 10:37

1 Answer 1


Basically your question is how long is the path represented as points in p. Since you are using a projection that is in meters it is simply a case of iterating through p and calculating the distance to the last/next point.

So something like:

lastPoint = None
d = 0
for point in p:
    if lastPoint is not None:
         dx = point.x - lastPoint.x
         dy = point.y - lastPoint.y  
         d += sqrt(dx*dx+dy*dy)
     lastPoint = point
print "distance is "+str(d/1000.0)+"km"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.