Sometimes, you may want to find the best driving route between two addresses. Street routing has now become so commonplace that we take it for granted. However, if you explore the recipes on geocoding and network analysis in this book, you will begin to see what a complex challenge street routing truly is. To perform routing operations in QGIS, we'll use the QGIS GeoSearch plugin, which is written in Python, so that we can access it from the console.
You will need to install the QGIS Python GeoSearch plugin for this exercise in order to do the routing, as well as the QGIS OpenLayers Plugin to overlay the result on a Google map, as follows:
GeoSearch
.OpenLayers
.We will invoke the GeoSearch plugin's routing function, which uses Google's routing engine, and display the result over a Google map from the OpenLayers plugin. To do this, we need to perform the following steps:
import qgis.utils from GeoSearch import geosearchdialog, GoogleMapsApi
openLyrs = qgis.utils.plugins['openlayers_plugin']
g = geosearchdialog.GeoSearchDialog(iface) g.SearchRoute([])
d = GoogleMapsApi.directions.Directions()
origin = "Boston, MA" dest = "2517 Main Rd, Dedham, ME 04429"
route = d.GetDirections(origin, dest, mode = "driving", waypoints=None, avoid=None, units="imperial")
layerType = openLyrs._olLayerTypeRegistry.getById(4) openLyrs.addLayer(layerType)
g.CreateVectorLayerGeoSearch_Route(route)
Even though they are built in Python, neither the GeoSearch nor OpenLayers plugins are designed to be used with Python by a programmer. However, we are still able to use the tools in a script without much trouble. To take advantage of some of the routing options available with the GeoSearch plugin, you can use its GUI to see what is available and then add those options to your script. Beware that most plugins don't have a true API, so a slight change to the plugin in a future version can break your script.