Кластеризация позволяет группировать близкие точки на карте и отображать их как один объект с количеством элементов внутри. Реализуется через параметры GeoJSONSource.
| Параметр | Тип | По умолчанию | Описание |
|---|---|---|---|
cluster |
boolean | false |
Включить кластеризацию |
clusterRadius |
number | 50 |
Радиус в пикселях, в котором точки объединяются в кластер |
clusterMaxZoom |
number | — | Максимальный уровень масштаба для кластеризации. По умолчанию — maxZoom - 1 |
clusterMinPoints |
number | 2 |
Минимальное количество точек для образования кластера |
clusterProperties |
object | — | Агрегатные значения, рассчитываемые для каждого кластера |
map.addSource('earthquakes', {
type: 'geojson',
data: 'https://yourservername.ru/earthquakes.geojson',
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 50
});
map.addLayer({
id: 'clusters',
type: 'circle',
source: 'earthquakes',
filter: ['has', 'point_count'],
paint: {
'circle-color': [
'step', ['get', 'point_count'],
'#51bbd6', 100,
'#f1f075', 750,
'#f28cb1'
],
'circle-radius': [
'step', ['get', 'point_count'],
20, 100,
30, 750,
40
]
}
});
map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'earthquakes',
filter: ['has', 'point_count'],
layout: {
'text-field': '{point_count_abbreviated}',
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12
}
});
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'earthquakes',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 4,
'circle-stroke-width': 1,
'circle-stroke-color': '#fff'
}
});
map.on('click', 'clusters', function(e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['clusters'] });
var clusterId = features[0].properties.cluster_id;
map.getSource('earthquakes').getClusterExpansionZoom(
clusterId,
function(err, zoom) {
if (err) return;
map.easeTo({
center: features[0].geometry.coordinates,
zoom: zoom
});
}
);
});
// Изменить курсор при наведении на кластер
map.on('mouseenter', 'clusters', function() {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'clusters', function() {
map.getCanvas().style.cursor = '';
});
// Получить первые 10 точек кластера
map.getSource('earthquakes').getClusterLeaves(
clusterId,
10, // limit
0, // offset
function(err, features) {
if (err) return;
console.log('Точки кластера:', features);
}
);
// Получить дочерние элементы на следующем уровне масштаба
map.getSource('earthquakes').getClusterChildren(
clusterId,
function(err, features) {
if (err) return;
console.log('Дочерние элементы:', features);
}
);