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:

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

To make the map you need these:

  1.  Python installed
  2. Python Folium installed
  3. Basic understanding of Python
  4. The input datasets which you can download from these links:
    The volcanoes point locations
    The GeoJson world polygon layer with population dataRight click and Save As if files open in the browser.

Once you have Python, Folium and the data, you can go ahead and execute the following Python script. That should generate a map.html file. Later, you can simply put that HTML file on a live server and have the map online.

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')

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 real world web applications, don’t miss the Python Mega Course. You can take the course for $19 instead of its $195 list price through this link.