As mentioned in the recipe, Calculating the shortest paths using the Road graph plugin, QGIS comes with a network analysis library, which can be used from the Python console, inside plugins, to process scripts, and basically anything else that you can think of. In this recipe, we will introduce the usage of the network analysis to compute the shortest paths in the Python console.
Instead of typing or copying the following script directly in the Python console, we recommend opening the Python console editor using the Show editor button on the left-hand side of the Python console:
import processing
from processing.tools.vector import VectorWriter
from PyQt4.QtCore import *
from qgis.core import *
from qgis.networkanalysis import *
# create the graph
layer = processing.getObject('network_pgr')
director = QgsLineVectorLayerDirector(layer,-1,'','','',3)
director.addProperter(QgsDistanceArcProperter())
builder = QgsGraphBuilder(layer.crs())
from_point = QgsPoint(2.73343,3.00581)
to_point = QgsPoint(0.483584,2.01487)
tied_points = director.makeGraph(builder,[from_point,to_point])
graph = builder.graph()
# compute the route from from_id to to_id
from_id = graph.findVertex(tied_points[0])
to_id = graph.findVertex(tied_points[1])
(tree,cost) = QgsGraphAnalyzer.dijkstra(graph,from_id,0)
# assemble the route
route_points = []
curPos = to_id
while (curPos != from_id):
in_vertex = graph.arc(tree[curPos]).inVertex()
route_points.append(graph.vertex(in_vertex).point())
curPos = graph.arc(tree[curPos]).outVertex()
route_points.append(from_point)
# write the results to a Shapefile
result = 'C:\\temp\\route.shp'
writer = VectorWriter(result,None,[],2,layer.crs())
fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromPolyline(route_points))
writer.addFeature(fet)
del writer
processing.load(result)network_pgr.shp, which is provided with this book, adjust the coordinates of from_point and to_point for the route's starting and ending points.On line 8, we created a QgsLineVectorLayerDirector object (http://qgis.org/api/classQgsLineVectorLayerDirector.html), which contains the network configuration. The constructor (QgsLineVectorLayerDirector(layer,-1,'','','',3)) parameters are as follows:
-1 because this script does not consider one-ways1 for the in link direction, 2 for the reverse direction, and 3 for the two-wayLine 10 creates the QgsGraphBuilder (http://qgis.org/api/classQgsGraphBuilder.html) instance, which will be used to create the routing graph on line 14.
On lines 11 and 12, we defined the starting and ending points of our route. To be able to route between these two points, they have to be matched to the nearest network link. This happens on line 13 in the makeGraph() function, which returns the so-called tied_points.
The actual route computation takes place on line 18 in the QgsGraphAnalyzer.dijkstra() (http://qgis.org/api/classQgsGraphAnalyzer.html) function.
The while loop, starting on line 22, is where the script moves through the tree created by Dijkstra's algorithm to collect all the vertices on the way and add them to the route_points list, which becomes the resulting route geometry on line 31.
The writer for output route line layer is created on line 29, where we pass the file path, None for default encoding, the [] for empty fields list, and the 2 for geometry type, which equals to lines as well as the resulting layer CRS. The following lines, 30 to 32, create the route feature and add it to the writer.
Finally, the last line loads the resulting shapefile, and this is displayed on the map, as illustrated by the following screenshot:

You can read more about QGIS's network analysis library online in the PyQGIS Developer Cookbook at http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/network_analysis.html.