Search code examples
javascriptmapboxmapbox-gl-jsmapbox-gl

How to write expression for inputting multiple values in Mapbox JS setFilter() for filtration?


I can successfully pass single value in my mapbox setFilter() by using expressions like these:

var business_domain_values = {0 : 'Corporate', 1 : 'Industrial',
                                  2 : 'Infrastructure', 3 : 'Institutional',
                                  4 : 'Commercial', 5 : 'Residential', 
                                  6 : 'Healthcare', 7 : 'Science & Technology', 
                                  8 : 'Financial Facilities'};

map.setFilter('AW', ['any', ['in', 'Corporate', ['get', 'Business_Unit']]]); 
                              OR
map.setFilter('Key Prospect', ['==', ['get', 'Business_Unit'], business_domain_values[0]]);

However, I want to pass multiple values like Commercial, Industrial etc. for filtering out. Trying hard to build expressions like

Approach #1.

 map.setFilter('AW', ['any', ['in', ['Corporate', 'Industrial'], ['get', 'Business_Unit']]]);

This resulted in

evented.js:145 Error: layers.AW.filter[1][1][0]: Unknown expression "Corporate". If you wanted a literal array, use ["literal", [...]].

Approach #2.

map.setFilter('AW', ['any', ['in', ['literal', ['Corporate', 'Industrial']], ['get', 'Business_Unit']]]);

This resulted in

evented.js:145 Error: layers.AW.filter[1]: Expected first argument to be of type boolean, string, number or null, but found array<string, 2> instead

Thanks for your time reading into this and your efforts you put into this are valuable.


Solution

  • Hit a similar snag last year. Think I have a solution for you! You need to switch the ordering of the the ["get"] argument and ["literal"] arguments I believe. This snippet should work for you.

    map.setFilter("AW", [
      "any",
      ["in", ["get", "Business_Unit"], ["literal", ["Corporate", "Industrial"]]
    ]);
    

    Here is a code sandbox link with a working example https://codesandbox.io/s/mapbox-filters-example-hhtg5

    Hope this helps! I have been writing a series of guides for Mapbox that you might be interested in too. Here are some links: