How to Make a Web Map with Python’s Flask and Leaflet

Stephen McNeal
Geek Culture
Published in
3 min readJan 12, 2022

This tutorial shows you how to build a web map with Python’s Flask and Leaflet, an open-source JavaScript library for mobile-friendly interactive maps.

Image by author.

Experience: Beginner

Requirements:

Basic knowledge of python, html, and javascript.

A python interpreter such as VSCode or Spyder.
These interpreters make it easy for you to edit your code.

This tutorial builds on the basic Google App Engine Example (available on github).

From the previous tutorial, we built a basic flask application and deployed it to Google App Engine using just 4 file: an HTML page, a Python file as the “controller”, a requirements file, and a file that tells App Engine what to do, called a .yaml file.

Building on these files, we just need two additional files to create a web map:

A CSS file and a JavaScript file. Flask knows to look for these files in a sub-directory called ‘static’. Create the directory in the same location as main.py. For organization, create two additional directories inside this one, one for javascript files and the other for css files. Finally, create these two empty files in their respective folders. The structure should look like this:

static/css/universal.css
static/css/universal.js

We are going for a full-screen map, so we want to remove all padding and margin from the body and set the height and width of the map to 100%.

Paste the following code into the universal.css file:

body {padding: 0;margin: 0;}html, body, #map {height: 100%;width: 100vw;}

Next we’ll add a standard leaflet map with an openstreet tile layer.

Paste the following into universal.js:

var map = L.map('map').fitWorld();L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);

The interesting part of this tutorial is utilizing “jinja” templates to feed variables from python to javascript. To do this, we need to give the page some variables. In main.py, we will add a parameter to feed “markers” into the page as a list of jsons.

from flask import Flask, render_templateapp=Flask(__name__)@app.route('/')def root():   markers=[   {   'lat':0,   'lon':0,   'popup':'This is the middle of the map.'    }   ]
return render_template('index.html',markers=markers )
if __name__ == '__main__': app.run(host="localhost", port=8080, debug=True)

And finally in the index.html page we add the standard javascript and css to render a leaflet map, as well as our css and javascript files in the static directory. By iterating through the list of marker jsons using a jinja “for loop” and adding the marker variables into an in-page script, we can pass variables from python to javascript. This allows us to take advantage of all of leaflets features using code and logic from python.

<!doctype html><html lang="en"><head><title>Flask Leaflet Website</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="{{ url_for('static', filename='css/universal.css') }}" /><link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="crossorigin=""/><script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="crossorigin=""></script></head><body><div id="map"></div><script src="{{ url_for('static', filename='js/universal.js') }}" /></script><script>{% for marker in markers %}L.marker([{{ marker['lat'] }}, {{ marker['lon'] }}]).addTo(map).bindPopup("{{ marker['popup'] }}").openPopup();{% endfor %}</script></body></html>

Voila! A free web map with only 6 files. View the repository on github.

--

--