2
votes

I have an application in which polygons are added to Mapbox layers dynamically. I'm using a match expression to style the polygon fills, but I'm having problems figuring out the syntax of the expression with array inputs.

Here's a quick example of what I'm trying to do: https://stackblitz.com/edit/angular-bpuswd?file=src%2Fapp%2Fapp.component.ts

I have a layer with the feature property states. I want to associate each state with a different fill color, per this official mapbox example for data-driven styles:

// want to match New York to color #F0F and Pennsylvania to color #FF0
const states = ['New York', 'Pennsylvania'];
const colors = ['#F0F', '#FF0'];
const statesAndColors = ['New York', '#F0F', 'Pennsylvania', '#FF0'];

this.map.addLayer({
  id: 'states',
  type: 'fill',
   source: {
      type: 'geojson',
      data: POLYGONS,
   },
   paint: {
     // doesn't work
     'fill-color': ['match', ['string', ['get', 'state']], states, colors, '#AAAAAA']

     // also doesn't work
     // 'fill-color': ['match', ['string', ['get', 'state']], statesAndColors, '#AAAAAA']

     // below example works
     // 'fill-color': ['match', ['string', ['get', 'state']], 'New York', '#F0F', 'Pennsylvania', '#FF0', '#AAAAAA']
    }
});

The mapbox expression match documentation states that you can use 'an array of literal values, whose values must be all strings or all numbers (e.g. [100, 101] or ["c", "b"]). The input matches if any of the values in the array matches, similar to the deprecated "in" operator.'

But my examples above do not work like I would expect. How do I format the expression to read in these styles as arrays? (Note: This example application can use the direct matching just fine because the New York and Pennsylvania values are hardcoded, but my actual application has polygons uploaded dynamically, so they're unknown at runtime.)

1

1 Answers

5
votes

Your issue here is just a Javascript syntax issue. statesAndColors is an array, whereas you need to pass in the individual values of the array. You can use the spread operator (...) to do that.

So, change this:

'fill-color': ['match', ['string', ['get', 'state']], statesAndColors, '#AAAAAA']

to this:

'fill-color': ['match', ['string', ['get', 'state']], ...statesAndColors, '#AAAAAA']

(Source: I actually wrote the sentence in the documentation you're quoting :))