Folium
Contents
Folium#
Folium is a Python package for generating interactive maps. It’s based on OpenStreetMap and the Leaflet JavaScript library.
import folium
Related projects:
Basic Usage#
Usage is straight-forward.
m = folium.Map(location=[50.7161, 12.4956], zoom_start=16)
folium.Marker(
[50.7161, 12.4956],
popup='<b>Zwickau University of Technology</b><br />Kornmark 1',
tooltip='Zwickau University of Technology',
icon=folium.Icon(color="red", icon="info-sign")
).add_to(m)
display(m)
For more features have a look at Folium’s Quickstart Guide.
Advanced Features#
Of particular interest for data science purposes are:
image overlays (position raster image on a map)
marker clusters (place many markers on a map)
fast marker clusters (position many markers on a map very efficiently)
Data on Folium maps is organized in layers. Layer visibility may be toggled by the user, if we add layer controls:
import folium.plugins
m = folium.Map(location=[50.7161, 12.4956], zoom_start=17)
folium.plugins.MarkerCluster(
[[50.7161, 12.4956], [50.7161, 12.4966], [50.7171, 12.4956]],
name='some marker'
).add_to(m)
folium.plugins.MarkerCluster(
[[50.7151, 12.4946], [50.7161, 12.4946], [50.7151, 12.4956]],
name='more marker'
).add_to(m)
folium.LayerControl().add_to(m)
display(m)
Exporting a Map#
To generate an HTML file containing the interactive Folium map, call save
. The save
method is inherited by Foliums Map
from branca.elements.Element
as we see from Map
’s documentation. Branca is used by Folium for HTML and JavaScript generation.
m.save('folium.html')
The generated HTML file may be edited to add some more (HTML and JavaScript) content. Alternatively, we may inject some HTML from Python source via ‘get_root’:
m.get_root().html.add_child(folium.Element(
'''
<div style="position: absolute; z-index: 10000; top: 10px; left: 60px; background: white; padding:5px 10px;">
<span style="font-size: 20pt; font-weight: bold; color: black;">Some Title</span><br/>
<span style="font-size: 10pt; color: blue;">some text</span>
</div>
'''
))
display(m)
m.save('folium.html')