I have the following array:
test = ['a', 'b', 'c']
I would like to filter objects on the map if they exist in the array. Is it possible to use this filter with array:
mapObj.setFilter("hover", ['all', ["in", "letter", test[0]]]);
Or alternately, what is the best way to filter object that exist in the array?
Well mapbox's setFilter function does not accept an array as a parameter. You will need to use a format that fits their API which is basically described here under "Set Membership Filters".
https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter
To filter multiple variables the Set Membership Filters require a specific format which is
["in", key, v0, ..., vn]
Where v0 to vn are elements of your array which yields
["in", "letter", "a", "b", "c"]
One could write a function to convert an array to this format. Maybe like this:
function buildFilter(arr) {
var filter = ['in', 'letter'];
if (arr.length === 0) {
return filter;
}
for(var i = 0; i < arr.length; i += 1) {
filter.push(arr[i]);
}
return filter;
}
var filterBy = ['a', 'b', 'c'];
var myFilter = buildFilter(filterBy);
console.log(myFilter);
// then you would use it like this:
// mapObj.setFilter("hover", buildFilter(['a', 'b', 'c']));
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