Introduction to Folium

Technocrat
CoderHack.com
Published in
3 min readSep 14, 2023

--

Folium is a powerful Python library that helps you create several types of Leaflet maps. It enables both Python and Leaflet to manipulate and visualize geospatial data. Some of the things you can do with Folium are:

  • Create map tiles, markers, popups, and layers
  • Add features like polygons, circles, and polylines
  • Add tile layers, WMS/TMS tile layers, XYZ tile layers
  • Control the zoom level, center of the map, tooltip content and popup content
  • Create choropleth maps that color areas based on some metric
  • Create marker clusters for large datasets
  • Create heatmaps
  • GeoJSON Overlays

Installing Folium

You can install Folium either using pip:

pip install folium

or conda:

conda install -c conda-forge folium

You will also need the Leaflet.js library which Folium builds upon.

Getting Started

Let’s create a basic map centered at latitude 48.8, longitude 2.33 with a zoom level of 10:

import folium

location = [48.8, 2.33]
folium_map = folium.Map(location=location, zoom_start=10)

folium_map # Display the map

We can also add features to the map like markers, popups, polylines, etc.:

folium_map = folium.Map(location=[48.8, 2.33], zoom_start=10)

folium.Marker([48.8, 2.33], popup='Paris!').add_to(folium_map)

folium.PolyLine(locations, color="blue").add_to(m)
folium.Circle(radius=200, location=[48.8, 2.33]).add_to(folium_map)

folium_map

This will add a marker with a popup at the center of the map, a blue polyline connecting multiple locations, and a circle with a radius of 200 meters centered at [48.8, 2.33].

Adding Tiles

Folium supports adding various tile layers to your map:

Add OpenStreetMap tiles:

folium.TileLayer('openstreetmap').add_to(folium_map)

Add Stamen Terrain tiles:

folium.TileLayer('Stamen Terrain').add_to(folium_map)

Add a WMS/TMS tile layer:

folium.TileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', 
attr='Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
name='World Imagery').add_to(folium_map)

Add an XYZ tile layer:

folium.TileLayer('https://api.mapbox.com/styles/v1/mapbox/bright-v9/tiles/256/{z}/{x}/{y}?access_token=YOUR_ACCESS_TOKEN_HERE', 
attr='Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
name='Mapbox Bright').add_to(folium_map)

Visualizing Data

Folium can be used to visualize many types of data on maps:

Choropleth Maps: Color areas based on some metric. For example, we can color counties based on unemployment rate:

import folium
import geopandas as gpd

# Load data
df = gpd.read_file('counties.geojson')

# Get unemployment rate
df['unemployment_rate'] = df['unemployment_rate'] * 100

# Map color scale
color_scale = branca.colormap.LinearColormap(
colors=["#ffffb2", "#fee08b", "#fc8d59", "#d73027"],
index=[0, 5, 10, 15],
vmin=0, vmax=df.unemployment_rate.max())

# Create map
m = folium.Map(location=[48, -102], zoom_start=5)

# Add choropleth
folium.Choropleth(
geo_data=df,
name='Unemployment Rate (%)',
data=df['unemployment_rate'],
columns=['unemployment_rate'],
key_on='feature.id',
threshold_scale=color_scale,
fill_color='YlGnBu',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Unemployment Rate (%)').add_to(m)

m

Heatmaps: Show the density of data points on a map. For example, here is a heatmap of San Francisco bike rentals:

import folium
from folium import plugins

data = pd.read_csv('bikerentals.csv')

m = folium.Map(location=[37.76, -122.4], tiles='Mapbox Bright', zoom_start=13)

heatmap = plugins.HeatMap(data[['lat', 'lng']])
heatmap.add_to(m)

m # Display map

Markers and Marker Clusters: Add markers to plot location data, and use marker clusters to handle many markers:

locations = [[48.8566, 2.3522], [41.3851, 2.1734], [43.2964, 5.3790]]

m = folium.Map(location=[48.8566, 2.3522], zoom_start=6)

# Add markers
for loc in locations:
folium.Marker(loc).add_to(m)

# Marker cluster
folium.MarkerCluster().add_to(m)

m

GeoJSON Overlays: Add GeoJSON files containing location data to your map:

geo_path = 'countries.geo.json'  
with open(geo_path) as f:
geo_str = f.read()
geo_data = folium.GeoJson(geo_str, name='Countries')

m = folium.Map(location=[48, -102], zoom_start=2)
geo_data.add_to(m)
m

This will add a GeoJSON overlay to the map with country borders.

Conclusion

Folium is a useful library for visualizing geospatial data with Python. It enables creating several types of interactive maps, colorful and customizable tiles, as well as multiple overlays representing various types of data on maps. The possibilities are endless, so I highly recommend checking out the Folium documentation and gallery for more examples and use cases.

--

--