Web Mapping Tutorial with Python and Folium

This Folium tutorial shows how to create a Leaflet web map from scratch with Python and the Folium library. For more explanations on how the code works, please watch the video further below.

Here is how the map will look like (may need a few seconds to load):

If you don’t want to watch the video, here is the tutorial in a nutshell:

To make the map you need to have Python and the Python pandas and folium libraries installed:

pip install pandas
pip install folium

You also need the following two files. We will use them as data sources for the tutorial. You can download the files below:

The Volcano CSV File

The World Popuation JSON File

If the above files open in your browser, try right-clicking over them and then go to Save As to save them as local files.

Once you have Python, pandas, folium, and the data, place the data in a folder, create an empty Python script in that same folder and put the code below in that script.

import folium
import pandas
map=folium.Map(location=[df['LAT'].mean(),df['LON'].mean()],zoom_start=6,tiles='Mapbox bright')
def color(elev):
if elev in range(minimum,minimum+step):
elif elev in range(minimum+step,minimum+step*2):
return col
fg=folium.FeatureGroup(name="Volcano Locations")
for lat,lon,name,elev in zip(df['LAT'],df['LON'],df['NAME'],df['ELEV']):
style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))

Executing the Python script should generate a map.html file in your folder. Later, you can simply put that HTML file on a live server and have the map online.

If you look inside the map.html source code you will see that Folium has been able to generate HTML, Javascript and CSS and these three render the map on the browser. You can serve this HTML as a static file in a basic webserver, but you can also go more advanced and create a Python application and have Folium dynamically generate such Leaflet maps on demand.

If you want to learn how to build more cool programs like the one below, don’t miss The Python Mega Course: Build 10 Real World Applications

Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.

Subscribe to be the first to know when a new Python course is released.