I use Mapbox GL JS and get a trouble with cluster. I add some layers I want to get a list of clustered points by click on cluster.
map.on('click', function(e) {
var cluster = map.queryRenderedFeatures(e.point, { layers: ["cluster"] });
if (cluster.length) {
// get clustered points here
console.log(cluster[0]);
}
});
Work example on jsfiddle https://jsfiddle.net/L3hm8rur/
The feature is now supported in the Mabox GL JS library.
Here is the API Doc - https://www.mapbox.com/mapbox-gl-js/api/#geojsonsource#getclusterchildren
How to get points under a cluster?
map.on('click',/* cluster layer id */ 'clusters', function (e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['clusters'] });
var clusterId = features[0].properties.cluster_id,
point_count = features[0].properties.point_count,
clusterSource = map.getSource(/* cluster layer data source id */'cluster-source');
// Get Next level cluster Children
//
clusterSource.getClusterChildren(clusterId, function(err, aFeatures){
console.log('getClusterChildren', err, aFeatures);
});
// Get all points under a cluster
clusterSource.getClusterLeaves(clusterId, point_count, 0, function(err, aFeatures){
console.log('getClusterLeaves', err, aFeatures);
})
});
EDIT: This is officially supported in recent versions of mapbox-gl-js, so you do not need to use the workaround I suggest below. See the other answer for more info.
Unfortunately, the behavior you're looking for is not supported at this time. The cluster layer does not contain the data of the individual points in the cluster.
A workaround would be to filter your GeoJSON source for points that are within your clusterRadius
distance from the clicked point, and this will give you the points you're looking for.
JSFiddle: https://jsfiddle.net/aznkw784/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With