Interactive maps on Leaflet¶
Whenever you go into a website that has some kind of interactive map, it is quite probable that you are wittnessing a map that has been made with a JavaScipt library called Leaflet (the other popular one that you might have wittnessed is called OpenLayers).
There is also a Python module called Folium that makes it possible visualize data that’s been manipulated in Python on an interactive Leaflet map.
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. There are few parameters that we can use to adjust how in our Map instance that will affect how the background map will look like.
import folium
# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles='Stamen Toner',
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. We can already now save the map without any content. It will now just show the basemap in such a way that we initialized it. Let’s save the map as
/home/geo/base_map.html
.
In [1]: outfp = "/home/geo/base_map.html"
In [2]: m.save(outfp)
Take a look at the map by clicking it with right mouse and open it with Google Chrome which then opens it up in a web browser.
- Let’s change the basemap style to
Stamen Toner
and change the location of our map slightly. Thetiles
-parameter is used for changing the background map provider and map style (see here for all possible ones).
# 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)
# Filepath to the output
outfp = "/home/geo/base_map2.html"
# Save the map
m.save(outfp)
Task
Play around with the parameters and save the map and see how those changes affect the look of the map.
Adding layers to the map¶
Adding layers to a web-map is fairly straightforward and similar procedure as with Bokeh and we can use familiar tools to handle the data, i.e. Geopandas. Our ultimate aim is to create a plot like this where population in Helsinki and the address points are plotted on top of a web-map: