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
df=pandas.read_csv("Volcanoes_USA.txt")
map=folium.Map(location=[df['LAT'].mean(),df['LON'].mean()],zoom_start=6,tiles='Mapbox bright')
def color(elev):
minimum=int(min(df['ELEV']))
step=int((max(df['ELEV'])-min(df['ELEV']))/3)
if elev in range(minimum,minimum+step):
col='green'
elif elev in range(minimum+step,minimum+step*2):
col='orange'
else:
col='red'
return col
fg=folium.FeatureGroup(name="Volcano Locations")
for lat,lon,name,elev in zip(df['LAT'],df['LON'],df['NAME'],df['ELEV']):
fg.add_child(folium.Marker(location=[lat,lon],popup=(folium.Popup(name)),icon=folium.Icon(color=color(elev),icon_color='green')))
map.add_child(fg)
map.add_child(folium.GeoJson(data=open('world_geojson_from_ogr.json'),
name="Population",
style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))
map.add_child(folium.LayerControl())
map.save(outfile='map.html')

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.