1、你需要一些点数据来进行聚合。这些数据可以是从API获取的,也可以是静态的GeoJSON数据。下面是一个示例GeoJSON数据:
var geoJsonData = {
"type": "FeatureCollection",
"features": [
{"type": "Feature", "geometry": {"type": "Point", "coordinates": [-100, 40]}},
{"type": "Feature", "geometry": {"type": "Point", "coordinates": [-95, 37]}},
// 更多点数据...
]
};
2、引入数据源,添加三个图层。聚合图层由三部分组成:聚合状态下图层、聚合数字,非聚合状态下的图层。
map.addSource('earthquakes', {
type: 'geojson',
generateId: true,
cluster: true,
clusterMaxZoom: 14, // 聚合的最大缩放级别
clusterRadius: 50, // 聚合半径
data: geoJsonData // 初始数据
});
//聚合图层-点
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'
}
});