Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapbox filters based on array

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?

like image 714
guyyug Avatar asked Aug 09 '17 16:08

guyyug


1 Answers

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']));
like image 146
Andi-lo Avatar answered Oct 21 '22 14:10

Andi-lo