MapSnippets logoMapSnippets logo

Marker Clustering with Leaflet

Leaflet

Group nearby markers into expandable clusters using the Leaflet.markercluster plugin for better performance with large datasets.

progress_activityLoading map...
const map = L.map('map').setView([48.8566, 2.3522], 12);
L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
  tileSize: 256,
  attribution: '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
const markers = L.markerClusterGroup();
const points = [
  [48.8584, 2.2945], [48.8606, 2.3376], [48.8530, 2.3499],
  [48.8738, 2.2950], [48.8462, 2.3464], [48.8620, 2.3522],
  [48.8490, 2.3080], [48.8650, 2.3210], [48.8430, 2.3680],
  [48.8710, 2.3150], [48.8550, 2.2830], [48.8670, 2.3600]
];
points.forEach(p => markers.addLayer(L.marker(p)));
map.addLayer(markers);

How it works

The Leaflet.markercluster plugin groups nearby markers into numbered clusters that split apart as the user zooms in. Create an L.markerClusterGroup(), add individual markers to it with addLayer(), then add the group to the map. The plugin handles clustering logic and animations automatically.

Cluster icons show the count of contained markers and are color-coded by density. Clicking a cluster zooms to reveal its children. For large datasets (thousands of markers), this dramatically improves performance and readability compared to rendering every marker individually.

Key APIs

API Description Docs
L.markerClusterGroup() Create cluster group github.com/Leaflet/Leaflet.markercluster
.addLayer() Add marker to cluster group leafletjs.com/reference.html#layergroup-addlayer

FAQ

How do I customize the cluster icon appearance?

Pass an iconCreateFunction option to L.markerClusterGroup() that returns an L.divIcon with your own HTML and CSS classes.

Does markercluster work with custom icons?

Yes. Markers with custom L.icon instances cluster normally: only the cluster icon itself needs separate styling.

Common mistakes

  • Forgetting to include both MarkerCluster.css and MarkerCluster.Default.css: clusters will appear unstyled
  • Adding markers directly to the map instead of to the markerClusterGroup: they won’t cluster
  • Loading the markercluster script before Leaflet: the plugin depends on L being defined first
auto_awesome

Build maps using Leaflet with AI

Generate code like this marker clustering with leaflet example using the Leaflet skill in your IDE.