此功能现在已在 Mapbox GL js 中 -https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/ https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/
要点:
使用设置数据源时map.addSource
,确保您定义了cluster: true
and clusterRadius: int
,像这样:
map.addSource( 'sourceName', {
type: "geojson",
data: {
type: 'FeatureCollection',
features: [JSON]
},
cluster: true,
clusterRadius: 80,
});
这将推动mapbox对你的图标进行聚类,但是你需要告诉mapbox当它对这些图标进行聚类时要做什么:
map.on( 'moveend', updateMarkers ); // moveend also considers zoomend
业务(根据相关性进行了精简):
function updateMarkers(){
var features = map.querySourceFeatures( 'sourceName' );
for ( var i = 0; i < features.length; i++ ) {
var coords = features[ i ].geometry.coordinates;
var props = features[ i ].properties;
if ( props.cluster ){ // this property is only present when the feature is clustered
// generate your clustered icon using props.point_count
var el = document.createElement( 'div' );
el.classList.add( 'mapCluster' );
el.innerText = props.point_count;
marker = new mapboxgl.Marker( { element: el } ).setLngLat( coords );
} else { // feature is not clustered, create an icon for it
var el = new Image();
el.src = 'icon.png';
el.classList.add( 'mapMarker' );
el.dataset.type = props.type; // you can use custom data if you have assigned it in the GeoJSON data
marker = new mapboxgl.Marker( { element: el } ).setLngLat( coords );
}
marker.addTo( map );
}
}
注意:不要复制粘贴此代码,而是将其与https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/ https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/了解整体情况。希望这可以帮助!