Visualize points as cluster maps in Leaflet
This tutorial shows how to visualize points as cluster maps with Leaflet JS. Learn how to group data points into clusters for effective data analysis and visualization.
In this Leaflet example, we use the Leaflet.markercluster plugin to create a cluster map with smooth animations and high-performance.
NPM module setup
npm install --save @maptiler/leaflet-maptilersdk leaflet leaflet.markercluster
import { MaptilerLayer, MapStyle } from '@maptiler/leaflet-maptilersdk';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet.markercluster';
import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
const key = 'YOUR_MAPTILER_API_KEY_HERE';
const map = new L.Map('map', {maxZoom: 22}).setView([0, 20], 1);
const mtLayer = new MaptilerLayer({
style: MapStyle.DATAVIZ.LIGHT,
apiKey: key,
}).addTo(map);
const markers = L.markerClusterGroup();
(async () => {
const response = await fetch('https://docs.maptiler.com/sdk-js/assets/earthquakes.geojson');
const jsonData = await response.json();
for (let i = 0; i < jsonData.features.length; i++) {
const feature = jsonData.features[i];
const title = feature.properties.mag;
const marker = L.marker(new L.LatLng(feature.geometry.coordinates[1], feature.geometry.coordinates[0]), { title: title });
marker.bindPopup(`${title}`);
markers.addLayer(marker);
}
map.addLayer(markers);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Visualize points as cluster maps in Leaflet | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
#map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.
Related examples
Plotting millions of points in Leaflet
ExamplesDisplay millions of points efficiently in Leaflet using maptilersdk.
How to create a heatmap layer in Leaflet
ExamplesCreate heatmap layers in Leaflet using the maptilersdk plugin.