This page was generated from source/notebooks/L5/interactive-map-folium.ipynb.
Binder badge
Binder badge CSC badge

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 focus on two Python libraries -mplleaflet and Folium - that are able to convert our data in (geo)pandas into interactive Leaflet maps.

Explore also…

Other interesting libraries for creating interactive visualizations from spatial data:

From matplotlib to leaflet using mplleaflet

We can also convert maptlotlib plots directly to interactive web maps using mllpleaflet.

All you need to do is to:

  1. visualize your data using matplotlib (or geopandas plot())
  2. convert the plot into a webmap using mplleaflet

Let’s demonstrate this using a simple static map

[1]:
import geopandas as gpd
import matplotlib.pyplot as plt
import mplleaflet
  • read in sample data (the locations of transport stations in Helsinki):
[2]:
import geopandas as gpd

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

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

#Check input data
points.head()
[2]:
address id geometry
0 Kampinkuja 1, 00100 Helsinki, Finland 1001 POINT (24.93017 60.16837)
1 Kaivokatu 8, 00101 Helsinki, Finland 1002 POINT (24.94189 60.16987)
2 Hermanstads strandsväg 1, 00580 Helsingfors, F... 1003 POINT (24.97740 60.18736)
3 Itäväylä, 00900 Helsinki, Finland 1004 POINT (25.09196 60.21448)
4 Tyynenmerenkatu 9, 00220 Helsinki, Finland 1005 POINT (24.92148 60.15658)
  • plot the data and create an interactive map using mplleaflet:
[3]:
# 1.Plot data:
points.plot()

# 2. Convert plot to a web map:
mplleaflet.show()

the code above opens up a new tab with the visualized map

We can also render the map insite the notebook (following this example):

[4]:
# 1. Plot data:
ax = points.plot(markersize = 50, color = "red")

# 2. Convert plot to a web map:
mplleaflet.display(fig=ax.figure, crs=points.crs)
C:\Hyapp\Anaconda3\envs\grading\lib\site-packages\IPython\core\display.py:694: UserWarning: Consider using IPython.display.IFrame instead
  warnings.warn("Consider using IPython.display.IFrame instead")
[4]:

Folium

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

Resources:

Creating a simple interactive web-map

Let’s first see how we can do a simple interactive web-map without any data on it. We just visualize OpenStreetMap on a specific location of the a world.

First thing that we need to do is to create a Map instance

  • Create a map object and set the location to Helsinki:
[5]:
import folium

# 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:
[6]:
m
[6]:
  • We can also save the map already now
  • Let’s save the map as a html file base_map.html:
[7]:
outfp = "base_map.html"
m.save(outfp)

Task

Navigate to the location where you saved the html file and open it in a web browser (preferably Google Chrome). Open the file also in a text editor to see the source script.

Task

Create another map with different settings (location, bacground map, zoom levels etc). See documentation of class folium.folium.Map() 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).

[8]:
# 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
[8]:

Adding layers to the map

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

[9]:
# 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
[9]:

As mentioned, Folium combines the strenghts of data manipulation in Python with the mapping capabilities of Leaflet.js. Eventually, we would like to first manipulate data using Pandas/Geopandas before creating a fancy map.

Let’s first practice by adding the address points onto the Helsinki basemap.

  • Check what data we have in the points layer:
[10]:
points.head()
[10]:
address id geometry
0 Kampinkuja 1, 00100 Helsinki, Finland 1001 POINT (24.93017 60.16837)
1 Kaivokatu 8, 00101 Helsinki, Finland 1002 POINT (24.94189 60.16987)
2 Hermanstads strandsväg 1, 00580 Helsingfors, F... 1003 POINT (24.97740 60.18736)
3 Itäväylä, 00900 Helsinki, Finland 1004 POINT (25.09196 60.21448)
4 Tyynenmerenkatu 9, 00220 Helsinki, Finland 1005 POINT (24.92148 60.15658)
  • conver the points to GeoJSON features using folium:
[11]:
# Convert points to GeoJSON
points_gjson = folium.features.GeoJson(points, name="Public transport stations")
[12]:
# 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
[13]:
# 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
[13]:

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

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

#Show map
m
[14]:

Heatmap

Folium plugins allow us to use popular plugins 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:

[15]:
# 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 output:

[16]:
locations
[16]:
[(60.1683731, 24.9301701),
 (60.1698665, 24.9418933),
 (60.18735880000001, 24.9774004),
 (60.21448089999999, 25.0919641),
 (60.1565781, 24.9214846),
 (60.23489060000001, 25.0816923),
 (60.2033879, 25.042239),
 (60.2753891, 25.035855),
 (60.2633799, 25.0291078),
 (60.22243630000001, 24.8718598),
 (60.1711874, 24.94251),
 (60.2306474, 24.8840504),
 (60.240163, 24.877383),
 (60.22163339999999, 24.9483202),
 (60.25149829999999, 25.0125655),
 (60.2177823, 24.893153),
 (60.2485471, 24.86186),
 (60.2291135, 24.9670533),
 (60.1986856, 24.9334051),
 (60.22401389999999, 24.8609335),
 (60.2436961, 24.9934979),
 (60.24444239999999, 25.040583),
 (60.20966609999999, 25.0778094),
 (60.20751019999999, 25.1424936),
 (60.225599, 25.0756547),
 (60.2382054, 25.1080054),
 (60.18789030000001, 24.9609122),
 (60.19413939999999, 25.0291263),
 (60.18837519999999, 25.0068399),
 (60.1793862, 24.9494874),
 (60.1694809, 24.9337569),
 (60.16500139999999, 24.9250072),
 (60.159069, 24.9214046),
 (60.1719108, 24.9468514),
 (60.20548979999999, 25.1204966)]
[17]:
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
[17]:

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.

[18]:
from folium.plugins import MarkerCluster
[19]:
# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=11, control_scale=True)
[20]:
# 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"]))
[21]:
# Create a folium marker cluster
marker_cluster = MarkerCluster(locations)

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

# Show map
m
[21]:

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:
[22]:
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()
[22]:
geometry index asukkaita asvaljyys ika0_9 ika10_19 ika20_29 ika30_39 ika40_49 ika50_59 ika60_69 ika70_79 ika_yli80
0 MULTIPOLYGON Z (((25476499.999 6674248.999 0.0... 3342 108 45 11 23 6 7 26 17 8 6 4
1 MULTIPOLYGON Z (((25476749.997 6674498.998 0.0... 3503 273 35 35 24 52 62 40 26 25 9 0
2 MULTIPOLYGON Z (((25476999.994 6675749.004 0.0... 3660 239 34 46 24 24 45 33 30 25 10 2
3 MULTIPOLYGON Z (((25476999.994 6675499.004 0.0... 3661 202 30 52 37 13 36 43 11 4 3 3
4 MULTIPOLYGON Z (((25476999.994 6675249.005 0.0... 3662 261 30 64 32 36 64 34 20 6 3 2
[23]:
from pyproj import CRS
# Define crs
data.crs = CRS.from_epsg(3879)
  • re-project layer into WGS 84 (epsg: 4326)
[24]:
# Re-project to WGS84
data = data.to_crs(epsg=4326)

# Check layer crs definition
print(data.crs)
{'init': 'epsg:4326', 'no_defs': True}
  • Rename columns
[25]:
# Change the name of a column
data = data.rename(columns={'asukkaita': 'pop18'})
[26]:
# 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)
[27]:
# 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()
[27]:
geoid pop18 geometry
0 0 108 MULTIPOLYGON Z (((24.57654 60.18042 0.00000, 2...
1 1 273 MULTIPOLYGON Z (((24.58102 60.18267 0.00000, 2...
2 2 239 MULTIPOLYGON Z (((24.58538 60.19391 0.00000, 2...
3 3 202 MULTIPOLYGON Z (((24.58541 60.19166 0.00000, 2...
4 4 261 MULTIPOLYGON Z (((24.58544 60.18942 0.00000, 2...
  • create an interactive choropleth map from the population grid:
[28]:
# 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
[28]: