Plotting API Results on a Map using Flask and LeafletJS

It is a frequent use-case to include a map in dashboards, websites or web applications. But how do we go from a list of coordinates, or a Python code that retrieves these coordinates from an API, to an interactive JavaScript-based map on our website? I will explain this in an example of a simple web app, which displays all the shops around the entered location.

Input page

Let’s start by talking about the input page. I made it very simple, without any unnecessary elements and without even a gram of styling with CSS. Just a good, old HTML, obviously in the Flask edition. And because we’re using Flask here, to be able to fetch the data using Python eventually, we actually need two files, one in HTML and another one in Python.

API Call

Before we can show any data on the map, we first need to acquire them using an API. In other words, we’re going to program our backend now. There are many APIs providing the locations of all sorts of things and places. In real life, I made Flask dashboards that showed parking locations or the company’s competitors. In this case, to keep it simple, I decided that we’ll display all shops in a 500 meters radius from the input location and we’ll use the OpenStreetMap data for it.

The Map

We have the results from the API: the list of coordinates of all the shops around the entered coordinates. How to present them in form of a map? For this, I’m using a JavaScript library called LeafletJS. To use it, we need to add several elements to the HTML file, so let’s create the results.html file.

Data Scientist @ Q-Park