Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapbox. Get list of points by click on cluster

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/

like image 860
Anatoliy Novoselov Avatar asked Jul 29 '16 05:07

Anatoliy Novoselov


2 Answers

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);
  })

});
like image 197
Ashish Singh Avatar answered Nov 05 '22 16:11

Ashish Singh


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/

  • disclaimer - I work at Mapbox
like image 42
mollymerp Avatar answered Nov 05 '22 18:11

mollymerp