Interactive maps#

In this tutorial we will learn how to publish data from Python on interactive leaflet.js maps.

JavaScript (JS) is a programming language for adding interactive content (such a zoomamble maps!) on webpages. Leaflet is a popular JavaScript library for creating interactive maps for webpages (OpenLayers is another JavaScript library for the same purpose).

Here, will mainly focus on Folium - a Python library that makes it easy to convert data from (Geo)DataFrames into interactive Leaflet maps.

Explore also…

Other interesting libraries for creating interactive visualizations from spatial data:

Folium#

Folium is a Python library that makes it possible visualize data on an interactive Leaflet map.

Resources:

Creating a simple interactive web-map#

Import folium and other useful packages:

import folium
from pyproj import crs
import geopandas as gpd
import matplotlib.pyplot as plt

We will start by creating a simple interactive web-map without any data on it. We just visualize OpenStreetMap on a specific location of the world.

First thing that we need to do is to create a Map instance and define a location for zooming in the data:

# Create a Map instance
m = folium.Map(location=[60.25, 24.8], zoom_start=10, control_scale=True)

The first parameter location takes a pair of lat, lon values as list as an input which will determine where the map will be positioned when user opens up the map. zoom_start -parameter adjusts the default zoom-level for the map (the higher the number the closer the zoom is). control_scale defines if map should have a scalebar or not.

Let’s see what our map looks like:

m
Make this Notebook Trusted to load map: File -> Trust Notebook

We can also save the map as a html file:

outfp = "base_map.html"
m.save(outfp)

You should now see a html file in your working directory. You can open the file in a web-browser in order to see the map, or in a text editor in order to see the source definition.

Let’s create another map with different settings (location, bacground map, zoom levels etc). See documentation of the Map() object for all avaiable options.

tiles -parameter is used for changing the background map provider and map style (see the documentation for all in-built options).

# Let's change the basemap style to 'Stamen Toner'
m = folium.Map(
    location=[40.730610, -73.935242],
    tiles="Stamen Toner",
    zoom_start=12,
    control_scale=True,
    prefer_canvas=True,
)

m
Make this Notebook Trusted to load map: File -> Trust Notebook

Adding layers to the map#

Let’s first have a look how we can add a simple marker on the webmap:

# Create a Map instance
m = folium.Map(location=[60.20, 24.96], zoom_start=12, control_scale=True)

# Add marker
# Run: help(folium.Icon) for more info about icons
folium.Marker(
    location=[60.20426, 24.96179],
    popup="Kumpula Campus",
    icon=folium.Icon(color="green", icon="ok-sign"),
).add_to(m)

# Show map
m
Make this Notebook Trusted to load map: File -> Trust Notebook

As mentioned, Folium combines the strenghts of data manipulation in Python with the mapping capabilities of Leaflet.js. Eventually, we would like to include the plotting of interactive maps as the last part of our data analysis workflow.

Let’s see how we can plot data from a geodataframe using folium.

# File path
points_fp = "data/addresses.shp"

# Read the data
points = gpd.read_file(points_fp)

# Check input data
points.head()
---------------------------------------------------------------------------
CPLE_OpenFailedError                      Traceback (most recent call last)
fiona/_shim.pyx in fiona._shim.gdal_open_vector()

fiona/_err.pyx in fiona._err.exc_wrap_pointer()

CPLE_OpenFailedError: data/addresses.shp: No such file or directory

During handling of the above exception, another exception occurred:

DriverError                               Traceback (most recent call last)
/tmp/ipykernel_221028/1565157085.py in <module>
      3 
      4 # Read the data
----> 5 points = gpd.read_file(points_fp)
      6 
      7 # Check input data

~/.conda/envs/mamba/envs/python-gis-book/lib/python3.9/site-packages/geopandas/io/file.py in _read_file(filename, bbox, mask, rows, **kwargs)
    199 
    200     with fiona_env():
--> 201         with reader(path_or_bytes, **kwargs) as features:
    202 
    203             # In a future Fiona release the crs attribute of features will

~/.conda/envs/mamba/envs/python-gis-book/lib/python3.9/site-packages/fiona/env.py in wrapper(*args, **kwargs)
    406     def wrapper(*args, **kwargs):
    407         if local._env:
--> 408             return f(*args, **kwargs)
    409         else:
    410             if isinstance(args[0], str):

~/.conda/envs/mamba/envs/python-gis-book/lib/python3.9/site-packages/fiona/__init__.py in open(fp, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt, **kwargs)
    254 
    255         if mode in ('a', 'r'):
--> 256             c = Collection(path, mode, driver=driver, encoding=encoding,
    257                            layer=layer, enabled_drivers=enabled_drivers, **kwargs)
    258         elif mode == 'w':

~/.conda/envs/mamba/envs/python-gis-book/lib/python3.9/site-packages/fiona/collection.py in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, ignore_fields, ignore_geometry, **kwargs)
    160             if self.mode == 'r':
    161                 self.session = Session()
--> 162                 self.session.start(self, **kwargs)
    163             elif self.mode in ('a', 'w'):
    164                 self.session = WritingSession()

fiona/ogrext.pyx in fiona.ogrext.Session.start()

fiona/_shim.pyx in fiona._shim.gdal_open_vector()

DriverError: data/addresses.shp: No such file or directory
points.head()
  • conver the points to GeoJSON features using folium:

# Convert points to GeoJSON
points_gjson = folium.features.GeoJson(points, name="Public transport stations")
# Check the GeoJSON features
# points_gjson.data.get('features')

Now we have our population data stored as GeoJSON format which basically contains the data as text in a similar way that it would be written in the .geojson -file.

Add the points onto the Helsinki basemap:

# Create a Map instance
m = folium.Map(
    location=[60.25, 24.8], tiles="cartodbpositron", zoom_start=11, control_scale=True
)

# Add points to the map instance
points_gjson.add_to(m)

# Alternative syntax for adding points to the map instance
# m.add_child(points_gjson)

# Show map
m

Layer control#

We can also add a LayerControl object on our map, which allows the user to control which map layers are visible. See the documentation for available parameters (you can e.g. change the position of the layer control icon).

# Create a layer control object and add it to our map instance
folium.LayerControl().add_to(m)

# Show map
m

Heatmap#

Folium plugins allow us to use popular tools available in leaflet. One of these plugins is HeatMap, which creates a heatmap layer from input points.

Let’s visualize a heatmap of the public transport stations in Helsinki using the addresses input data. folium.plugins.HeatMap requires a list of points, or a numpy array as input, so we need to first manipulate the data a bit:

# Get x and y coordinates for each point
points["x"] = points["geometry"].apply(lambda geom: geom.x)
points["y"] = points["geometry"].apply(lambda geom: geom.y)

# Create a list of coordinate pairs
locations = list(zip(points["y"], points["x"]))

Check the data:

locations
from folium.plugins import HeatMap

# Create a Map instance
m = folium.Map(
    location=[60.25, 24.8], tiles="stamentoner", zoom_start=10, control_scale=True
)

# Add heatmap to map instance
# Available parameters: HeatMap(data, name=None, min_opacity=0.5, max_zoom=18, max_val=1.0, radius=25, blur=15, gradient=None, overlay=True, control=True, show=True)
HeatMap(locations).add_to(m)

# Alternative syntax:
# m.add_child(HeatMap(points_array, radius=15))

# Show map
m

Clustered point map#

Let’s visualize the address points (locations of transport stations in Helsinki) on top of the choropleth map using clustered markers using folium’s MarkerCluster class.

from folium.plugins import MarkerCluster
# Create a Map instance
m = folium.Map(
    location=[60.25, 24.8], tiles="cartodbpositron", zoom_start=11, control_scale=True
)
# Following this example: https://github.com/python-visualization/folium/blob/master/examples/MarkerCluster.ipynb

# Get x and y coordinates for each point
points["x"] = points["geometry"].apply(lambda geom: geom.x)
points["y"] = points["geometry"].apply(lambda geom: geom.y)

# Create a list of coordinate pairs
locations = list(zip(points["y"], points["x"]))
# Create a folium marker cluster
marker_cluster = MarkerCluster(locations)

# Add marker cluster to map
marker_cluster.add_to(m)

# Show map
m

Choropleth map#

Next, let’s check how we can overlay a population map on top of a basemap using folium’s choropleth method. This method is able to read the geometries and attributes directly from a geodataframe. This example is modified from the Folium quicksart.

  • First read in the population grid from HSY wfs like we did in lesson 3:

import geopandas as gpd
from pyproj import CRS
import requests
import geojson

# Specify the url for web feature service
url = "https://kartta.hsy.fi/geoserver/wfs"

# Specify parameters (read data in json format).
# Available feature types in this particular data source: http://geo.stat.fi/geoserver/vaestoruutu/wfs?service=wfs&version=2.0.0&request=describeFeatureType
params = dict(
    service="WFS",
    version="2.0.0",
    request="GetFeature",
    typeName="asuminen_ja_maankaytto:Vaestotietoruudukko_2018",
    outputFormat="json",
)

# Fetch data from WFS using requests
r = requests.get(url, params=params)

# Create GeoDataFrame from geojson
data = gpd.GeoDataFrame.from_features(geojson.loads(r.content))

# Check the data
data.head()
from pyproj import CRS

# Define crs
data.crs = CRS.from_epsg(3879)

Re-project layer into WGS 84 (epsg: 4326)

# Re-project to WGS84
data = data.to_crs(epsg=4326)

# Check layer crs definition
print(data.crs)

Rename columns

# Change the name of a column
data = data.rename(columns={"asukkaita": "pop18"})
# Create a Geo-id which is needed by the Folium (it needs to have a unique identifier for each row)
data["geoid"] = data.index.astype(str)
# Select only needed columns
data = data[["geoid", "pop18", "geometry"]]

# Convert to geojson (not needed for the simple coropleth map!)
# pop_json = data.to_json()

# check data
data.head()

Create an interactive choropleth map from the population grid:

# Create a Map instance
m = folium.Map(
    location=[60.25, 24.8], tiles="cartodbpositron", zoom_start=10, control_scale=True
)

# Plot a choropleth map
# Notice: 'geoid' column that we created earlier needs to be assigned always as the first column
folium.Choropleth(
    geo_data=data,
    name="Population in 2018",
    data=data,
    columns=["geoid", "pop18"],
    key_on="feature.id",
    fill_color="YlOrRd",
    fill_opacity=0.7,
    line_opacity=0.2,
    line_color="white",
    line_weight=0,
    highlight=False,
    smooth_factor=1.0,
    # threshold_scale=[100, 250, 500, 1000, 2000],
    legend_name="Population in Helsinki",
).add_to(m)

# Show map
m

Tooltips#

It is possible to add different kinds of pop-up messages and tooltips to the map. Here, it would be nice to see the population of each grid cell when you hover the mouse over the map. Unfortunately this functionality is not apparently implemented implemented in the Choropleth method we used before.

Add tooltips, we can add tooltips to our map when plotting the polygons as GeoJson objects using the GeoJsonTooltip feature. (following examples from here and here)

For a quick workaround, we plot the polygons on top of the coropleth map as a transparent layer, and add the tooltip to these objects. Note: this is not an optimal solution as now the polygon geometry get’s stored twice in the output!

# Convert points to GeoJson
folium.features.GeoJson(
    data,
    name="Labels",
    style_function=lambda x: {
        "color": "transparent",
        "fillColor": "transparent",
        "weight": 0,
    },
    tooltip=folium.features.GeoJsonTooltip(
        fields=["pop18"], aliases=["Population"], labels=True, sticky=False
    ),
).add_to(m)

m

Rember that you can also save the output as an html file:

outfp = "choropleth_map.html"
m.save(outfp)

Extra: check out plotly express for an alternative way of plotting an interactive Choropleth map in here.