1

I am currently using the Dijkstra's algorithm to find the shortest path between multiple latitudes and longitudes on QGIS.

Most of my code is from the Dijkstra's documentation here: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/network_analysis.html#finding-shortest-paths and I have also referred to a similar issue here: QGIS crash when looping through features in network analysis (dijkstra)

At first, I thought it was Dijkstra's algorithm function that was crashing QGIS. This is still happening, however, I have also found another error. When ran, the console shows "AttributeError: 'NoneType' object has no attribute 'findVertex'", implying that the graph returned from graph = builder.graph() is null. Has anyone run into this issue as well, or any suggestions of how I can move forward?

from qgis.utils import iface
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.networkanalysis import *

layers = qgis.utils.iface.legendInterface().layers()
for layer in layers:
    if layer.name() == 'tl_2016_44_tract':
        tractLayer = layer

# building a graph
# all roads are treated as two-way
director = QgsLineVectorLayerDirector(tractLayer, -1, '', '', '', 3)
properter = QgsDistanceArcProperter()
director.addProperter(properter)
crs = qgis.utils.iface.mapCanvas().mapRenderer().destinationCrs()
builder = QgsGraphBuilder(crs)

# extracting coordinates 
tractLayer.startEditing()
points = {f.id():f for f in tractLayer.getFeatures()}

for key1 in points:    
    lat1 = float(points[key1]["INTPTLAT"])
    lon1 = float(points[key1]["INTPTLON"])
    startPoint = QgsPoint(lat1, lon1)
    for key2 in points:
        lat2 = float(points[key2]["INTPTLAT"])
        lon2 = float(points[key2]["INTPTLON"])
        endPoint =  QgsPoint(lat2, lon2)

        tiedPoints = director.makeGraph(builder, [startPoint, endPoint])
        graph = builder.graph()

        tStart = tiedPoints[0]
        tStop = tiedPoints[1]
        idStart = graph.findVertex(tStart)
        idStop = graph.findVertex(tStop)

        (tree, cost) = QgsGraphAnalyzer.dijkstra(graph, idStart, 0)
        print "Travel time is %s hours" % (dcost[endId])
  • Does your graph definitely a have a path through it? – BradHards Jun 27 '17 at 4:48
  • @BradHards I wasn't sure how I could check for that. One thing is that I didn't overlay a street map over my Census Tract layer, but I figured that the builder.graph() would make a graph using existing edges for the boundaries of the tract. I'll try overlaying a street map and let you know how that goes. – emilyk Jun 27 '17 at 12:22

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.