mapbox-gl支持点图层的聚合效果,在使用geojson加载大量的点数据时,通过聚合效果,能够流畅进行浏览,同时能够达到良好的显示效果。
mapbox-gl在geojson的矢量图层上,支持聚合,vector tile矢量瓦片不支持。 mapbox-gl聚合的实现:
//添加一个geojson图层,设置cluster为true,开启聚合
map.addSource('poidata', {
type: 'geojson',
data: 'data/poicluster.geojson',
cluster: true,
//最大的聚合级别,超过级别不进行聚合
clusterMaxZoom: 12,
//聚合的半径,单位是像素
clusterRadius: 80,
//最小聚合的点数量
clusterMinPoints:2
}); 在数据源设置聚合后,mapbox-gl会在数据源中,自动添加一个point_count属性,所以,在geojson源数据的属性中,要保持不要重名。
//添加聚合的圆圈效果,图层过滤中,显示有point_count属性的数据
map.addLayer({
id: 'clusters',
type: 'circle',
source: 'poidata',
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
]
}
});
//添加聚合的点数量,取point_count属性值,或者point_count_abbreviated,显示缩写值,如3k等
map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'poidata',
filter: ['has', 'point_count'],
layout: {
'text-field': '{point_count}',
'text-font': ['Arial Unicode MS Bold'],
'text-size': 12
}
});
//显示未聚合的点图层
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'poidata',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#ffff00',
'circle-radius': 4,
'circle-stroke-width': 1,
'circle-stroke-color': '#fff'
}
});

上述效果,也可以用symbol图层进行代替,根据缩放级别,显示图标大小,显示聚合的效果。