Marker clusters can be a good way to simply a map containing many markers. When the map is zoomed out nearby markers are combined together into a cluster, which is separated out when the map zoom level is closer. In this post I show you how Folium marker clusters are easy to set up and use.
Folium Marker Clusters – an example
To show what folium marker clusters can do I’m going to use the example of a simple map I’ve looked at before – public toilets in the town of Colchester.
Before Marker Clusters
Here’s what the map looked like before clustering the markers. All points are shown at all zoom levels. (You can see the code for this map here)
After Marker Clusters
In this next map the markers close to each other have been clustered together.
Double click on a cluster to zoom in and see the points it included.
You can also mouse-over a cluster to see the area that it represents.
We can Also Add Markers Not Included In a Cluster
See the code below for how to do this.
How to Add Marker Clusters To a Map
The code to create a marker cluster is:
marker_cluster = folium.MarkerCluster("Cluster Name").add_to(my_map)
We then add markers to this cluster, rather than directly to the map:
Although we can still add points directly to the map (not attached to a cluster):
folium.Marker([51.8860942,0.8336077], popup="not included in marker cluster").add_to(my_map)
Here is the code for the examples above:
import os import folium import pandas as pd from bng_to_latlon import OSGB36toWGS84 # Load map centred on Colchester uk = folium.Map(location=[51.8860942,0.8336077], zoom_start=10, control_scale=True) # Load locally stored colchester public toilets data toilets = pd.read_csv("public-toilets.csv") # create a marker cluster called "Public toilet cluster" marker_cluster = folium.MarkerCluster("Public toilet cluster").add_to(uk) #add a marker for each toilet, add it to the cluster, not the map for each in toilets.iterrows(): popup = 'Add <b>test</b>' print(list([each.GeoY,each.GeoX])) print(list(OSGB36toWGS84(each['GeoX'],each['GeoY']))) folium.Marker(list(OSGB36toWGS84(each['GeoX'],each['GeoY'])), popup=popup).add_to(marker_cluster) # we can also add a marker directly to the map, outside of the clustering folium.Marker([51.8860942,0.8336077], popup="not included in marker cluster",icon=folium.Icon(color='red',icon='info-sign')).add_to(uk) # Save map uk.save("./colch_toilets_clusters.html")