Mapbox filters based on array

Viewed 5335

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?

5 Answers

["in", "letter", ...test] in ES6

should work.

You can also use:

['in', 'letter'].concat(test);

Where test is your array of values.

Actually there is a native way of doing this, as shown in the "Filter features within mapview" example.

You will have to use a unique attribute of your elements (ideally a unique ID). In your case, given that the attribute is "letter", the code would be the following:

mapObj.setFilter('hover', ['match', ['get', 'letter'], test, true, false])

For a better understanding of the code, take a look at the documentation about the match expression.

I used it with .map like in this. I think you should avoid an extra method for concatenation.

         this.$store.map.setFilter(layerName, [
          'match',
          ['get', filterPropertyName],
          currentValues.map((feature) => {
            return feature;
          }),
          true,
          false
        ])
Related