Django Web App for Plotting the Route between Two Points in a Map

Rajavel M
Python in Plain English
5 min readOct 7, 2021

--

Photo by Tamas Tuzes-Katai on Unsplash

Hi, everyone.

Building small functional applications is a fun and good way to learn and try new things. In this post, we will see how to build a web app in Django that integrates mapping and routing functionalities.

We are going to build a website which shows the shortest route on a map after selecting two locations using a mouse click. In order to do that, we need to use JavaScript. Django is a server-side technology, we need to run a client-side program to get coordinates from the mouse click and then send the coordinates to the backend.

The flow

First, we show a map on a webpage.

Whenever the user selects two locations using a mouse click, it sends the coordinates to the backend.

Then we pass the coordinates into OSRM API for getting routes. The response is encoded.

We decode the response and show it on a webpage using folium.

Prerequisites:

Django, Folium, requests, Polyline

Leaflet (the JavaScript library): We can use it through CDN, no need to install it.

Folium

We use Folium for drawing maps in Python. Folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet library. It works on the concept of manipulating your data in Python, then visualizing it on a Leaflet map via Folium.

Folium makes it easy to visualize data that’s been manipulated in Python on an interactive Leaflet map. It has a number of built-in tilesets from OpenStreetMap, Mapbox, and Stamen, and supports custom tilesets with Mapbox or Cloudmade API keys.

We can also use various parameters such as zoom, layer, Marker, etc.

Example snippet to show map

Below is the documentation for Folium.

Leaflet

Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 39 KB of JS, it has all the mapping features most developers ever need.

Leaflet is designed with simplicity, performance, and usability in mind. It works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy-to-use, and well-documented API and simple, readable source code.

OSRM

For getting routes, we can use the OSRM API. We can also do routing locally in our machine itself without using external API, but it needs very high computational power and memory, so we use API for getting the routes.

The Open Source Routing Machine or OSRM is a C++ implementation of a high-performance routing engine for the shortest path in road networks. It combines sophisticated routing algorithms with the open and free road network data of the OpenStreetMap (OSM) project. The shortest path computation on a continental-sized network can take up to several seconds if it is done without a so-called speedup technique. OSRM uses an implementation of contraction hierarchies and is able to compute and output the shortest path between any origin and destination within a few milliseconds, whereby the pure route computation takes much less time. Most effort is spent in annotating the route and transmitting the geometry over the network.

We can query OSRM routing API via a URL like this. Pass the source and destination coordinates with optional parameters.

'http://router.project-osrm.org/route/v1/driving/79.81039,12.00679;80.28150,13.08195?alternatives=true&geometries=polyline'

In Python, we can use the requests library for this.

The response we get from the API is like

It has distance, geometry, location, and some other information. What can we do with this?

Let’s look at geometry, it has something like this:

 ‘}ihhAoxbfNmUb|Bdv@dTewCftBm~Hb~AkjBneBc{BgLiaSpsN_hCq`@ktE{wDodI{~N{lI_{A}sD}fEceHseCs_LiiIqdYcvGkQa{BcgDzDccHauC{wa@o_VscDnIigB_wB{lJsw@koB_}Bk~B_Oe}CarHib@e_O’

It is in polyline encoded format. For getting coordinates in latitude and longitude format, we need to decode it.

Use the polyline.decode() method for this.

routes=polyline.decode(res[‘routes’][0][‘geometry’])

It gives a list of coordinates. Now we have a list of lat, lng coordinates. With this, we can draw routes on the map using folium.polyline() method.

Let's build this as a web app.

Create a new Django project and app.

django-admin startproject show_route
python manage.py startapp route

Edit settings.py file to add the app and templates directory. The link for the complete code is at the end.

getroute.py

It is a function that takes lat, lng parameters and calls the API, decodes the response, and returns it as a list.

views.py

In showmap view, we directly render the showmap.html file

In showroute view, we instantiate a Folium map and call the getroute function to get the routes from the OSRM API and draw the routes on the map and send them to the showroute.html file for rendering.

showmap.html

Include scripts to add Leaflet via CDN.

We need two locations, so the count variable is used to get two mouseclick events. If you have any alternative suggestions or methods to do this, feel free to mention them in the comments.

showroute.html

Just render the context given by our backend.

urls.py

Finally, map the view functions with the URL. <str:val> is for passing the string values in URL.

Output

Run the command below to start the server.

python manage.py runserver

For complete code, clone the repository

https://github.com/RAJAVEL-M/show-route-webapp

That’s all for now. It is only a part of the project, so it has a single feature only for now. We can use it in any Django web app that needs routing functionality. In the future, we will build many applications on top of this. If you have any suggestions, improvements, or queries, feel free to mention them in the comments.

Thank you for spending your time reading this.

More content at plainenglish.io

--

--