Reputation: 846
We can now cluster markers in gl-js:
https://www.mapbox.com/mapbox-gl-js/example/cluster/
Is there an equivalent way of marker filters in clustering in mapbox-gl-js as in leaflet like this example:
https://www.mapbox.com/mapbox.js/example/v1.0.0/filtering-marker-clusters/
Upvotes: 3
Views: 2838
Reputation: 31
I have also run into this issue and believe there should be a way of further filtering cluster layers based on a property of the features in the collection. But from my understanding (and I sincerely hope there is a better way that I just haven't figured out yet), there isn't a way to distinguish the clustered features since you declare on the source that it is to be clustered. A workaround that I have come up with is to dynamically add a source and layer as your filter changes.
For example: if you're filtering by subcategory ID's, you can pare down your original FeatureCollection that match that subcategory ID and create a new source with that FeatureCollection with cluster set to true, add your layer for the markers, and then add your cluster layers like they have laid out in their example. And anytime that filter changes, you can either toggle the visibility of that marker layer (haven't tested that part) or just remove it and add the new one repeating those previous steps. Some of the many downsides to this approach is the inability to use your regular filters on the whole dataset (if you had any) and it isn't as performant as if you were using filters.
If you use the earthquakes data from mapbox, the code might look like:
var data = "https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson";
var filterID = 1.87; // Arbitrary number
var paredData = _.filter(data.features, function(feature){
if (feature["Primary ID"] === filterID) {
return feature;
}
})
// Remove all of the layers and source associated
// with a previous filter if needed
if (map.getSource("earthquake-filter") {
map.removeLayer("earthquake-filter");
map.removeLayer("earthquake-filter-cluster");
map.removeLayer("earthquake-filter-cluster-count");
map.removeSource("earthquake-filter");
}
map.addSource("earthquake-filter", {
type: "geojson",
data: {
type: "FeatureCollection",
features: paredData
},
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 50
});
And continue as they do in the example.
Not my favorite solution but it's the only one that works so far that I've found. Hope this helps.
Upvotes: 3