Martin Tumusiime
3 min readJul 10, 2020

How to visualize the shortest route for more than two addresses using gmaps python

In this article, I am going to plot more than two addresses on a map using google maps API and use the google maps directions API to find the shortest path using python gmaps library.

For this demonstration, I used Jupyter notebook as my IDE to help me break down each step and demonstrate how this works.

To use gmaps library in jupyter notebooks, the first step is to install the library with pip install gmaps or conda then enable the library.

Install jupyter gmaps with conda

This is perhaps the fastest and easiest way to install jupyter gmaps

conda install -c conda-forge gmaps

Alternatively

If using conda didn’t work for you, you can use pip

First, enable the following extension

jupyter nbextension enable — py — sys-prefix widgetsnbextension

Then install gmaps with pip as show below

pip install gmaps

Then load extension in jupyter with

jupyter nbextension enable — py — sys-prefix gmaps

After installing gmaps, restart your kernel in jupyter to allow it to fetch the new changes.

So assuming you have created an API key, place the api key in the . txt file and we shall access it from our code. Read here on how to create a Google API key.

In the screenshot below, open your jupyter notebook cell and write code to read the API key that you generated from the step above in the .txt file.

In the second screenshot, we import our gmaps library and configure our APIs, then create a map and add layers as indicated in the screenshot.

Brief explanation.

The directions API shown above maps the shortest route from start address (coordinates) and then moves through the waypoints optimizing for the shortest routes as much as it can up to the destination point (address).

The outcome is this

To indicate traffic jam in google maps, add the layer below

fig.add_layer(gmaps.traffic_layer())

And our map will show the current traffic jam between different roads.

Conclusion

There’s a lot of map visualizations you can do with google maps using the gmaps library and finding the shortest route with directions API. The limitation with the directions API is, it can’t take in more than 23 points according to their documentation, so if you want to do this for more complex route optimization (locations) you’ll need to read through more complex algorithms or look at problems such as TSP or VRP depending on the route optimization you are working one.

Get source code of this article on github

References

https://jupyter-gmaps.readthedocs.io/en/latest/install.html

Martin Tumusiime

Currently on the mission to change the narrative in the waste management industry across Africa through technological innovations.