Effortless Marker Clustering with Leaflet.markercluster
30th Dec 2024
When working with maps, a common challenge is displaying a large number of markers without overwhelming the user or compromising performance. Leaflet.markercluster solves this problem by grouping markers into clusters dynamically, creating cleaner, faster, and more interactive maps.
In this guide, we’ll learn how to add Leaflet.markercluster to your Leaflet map and make the most of its features.
Why Use Leaflet.markercluster?
- Cleaner Maps: Groups nearby markers into clusters to reduce clutter.
- Improved Performance: Loads markers more efficiently, even with thousands of points.
- Interactive Features: Lets users explore dense clusters with ease, thanks to spiderfying and custom events.
How to Add Leaflet.markercluster to Your Map
-
Step 1: Set Up Your Project
Add Leaflet and Leaflet.markercluster to your project.
Using npm:
npm install leaflet leaflet.markercluster
Using a CDN:
-
Step 2: Create a Basic Leaflet Map
Add a map to your HTML:
Initialize the map in JavaScript:
const map = L.map('map').setView([51.505, -0.09], 13); // Add a tile layer (e.g., OpenStreetMap) L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap contributors', }).addTo(map); -
Step 3: Add Marker Clustering
Create a marker cluster group and add your markers to it:
Initialize the map in JavaScript:
const markers = L.markerClusterGroup(); // Example: Adding 100 random markers for (let i = 0; i < 100; i++) { const lat = 51.5 + Math.random() * 0.1 - 0.05; const lng = -0.09 + Math.random() * 0.1 - 0.05; const marker = L.marker([lat, lng]); marker.bindPopup(Marker ${i + 1}); markers.addLayer(marker); } // Add the cluster group to the map map.addLayer(markers);That’s it! You now have a map with dynamic marker clustering.
Enhancing Your Marker Clustering
Custom Cluster Icons
Make clusters stand out by customizing their appearance:
const customCluster = L.markerClusterGroup({
iconCreateFunction: function (cluster) {
const count = cluster.getChildCount();
return L.divIcon({
html: ${count},
className: 'custom-cluster-icon',
iconSize: [40, 40],
});
},
});
// Add markers to the custom cluster group
customCluster.addLayer(L.marker([51.5, -0.09]));
map.addLayer(customCluster);
Style .custom-cluster and .custom-cluster-icon using CSS for a polished look.
Handle Dense Marker Overlaps with Spiderfying
Dense clusters are automatically spiderfied when zoomed in. Customize this behavior with options:
const clusterGroup = L.markerClusterGroup({
spiderfyOnMaxZoom: true,
showCoverageOnHover: true,
zoomToBoundsOnClick: true,
});
// Add the cluster group to the map
map.addLayer(clusterGroup);
Listen to Cluster Events
Add interactivity by listening to cluster-specific events:
markers.on('clusterclick', (event) => {
console.log('Cluster clicked:', event.layer);
});
markers.on('mouseover', (event) => {
console.log('Marker hovered:', event.layer);
});
Performance Tips for Large Datasets
- Limit Marker Rendering: Use clustering to avoid displaying all markers at once.
- Lazy Loading: Fetch marker data only for the visible map area.
- Optimize Marker Data: Use lightweight data structures to reduce memory usage.
Conclusion
Leaflet.markercluster makes handling large numbers of markers straightforward and efficient. Whether you’re building a map for analytics, logistics, or any location-based application, this plugin ensures your maps stay clean, interactive, and performant.