How to measure driving distance, time, and plot routes between geographical locations using Python.
Ever tried to find open source tools for your data science project or solve any real-world routing problems? And ended without and clear idea? If so, this quick reading will navigate you to the right path.
Tools that we are using,
- Folium -If you are a data viz enthusiast, you may already heard about Folium. Folium is the python wrapper for the popular leaflet.js library. It's an easy-to-use and smooth library for interactive geo data visualization.
- openrouteservice -Route service for cars, pedestrians, and bicycles based on Open Standards and Open Geodata.
Install required libraries,
As we are continuing with the Python language, we can just run,
pip install openrouteservice folium
for install required libraries.
Import and the test run,
If you closely look at your response, you will see the following structure.
In our case, we are only using the routes attribute for afterward. Let’s look at the routes attribute.
As our purpose is to draw the route between the given points, we could use the routes’s geometry attribute. By default, the directions API returns encoded polylines.
No worries, we have a built-in method to decode it to a Python dict.
geometry = client.directions(coords)['routes'][0]['geometry']
decoded = convert.decode_polyline(geometry)
print(decoded)
This will print the GeoJSON geometry object that we can use in the visualization part.
Plot the path,
Here is the output.
With the few lines of code, we just drew the route between two points. The current view is really incomplete without source and destination points. Let's add them too.
Now we created the basic map with two geo-locations. Then, try to add more features, such as show duration and driving distance between two points.
To access the travel time and duration we can use the summary attribute.
It returns the distance and duration between given points in meters and Minutes.
First, we need to prepare the text for the popup when we click the route.
distance_txt = "<h4> <b>Distance : " + "<strong>"+str(round(res['routes'][0]['summary']['distance']/1000,1))+" Km </strong>" +"</h4></b>"duration_txt = "<h4> <b>Duration : " + "<strong>"+str(round(res['routes'][0]['summary']['duration']/60,1))+" Mins. </strong>" +"</h4></b>"
Next, we can add it to our map using the following way,
folium.GeoJson(decoded).add_child(folium.Popup(distance_txt+duration_txt,max_width=300)).add_to(m)
Finally, we got this output.
Feel free to play around with API and other response attributes, such as
routes[0]['segments']
Full code,
Also, you can use some alternatives according to your use case S.A,
- Open Source Routing Machine (OSRM) -Modern C++ routing engine for shortest paths in road networks.
Eager to know your feedback regarding this reading. Thanks!
References