0
votes

I would like to set an icon-image based on a data value (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions).

Also see https://github.com/mapbox/mapbox-gl-js/issues/6935 which has a few examples for how to do this.

I've tried a few things ...

Using match

'icon-image': [
  'match',
  ['get', 'tap_ports'],
  2,
  '{tubes}-circle-15',
  4,
  '{tubes}-square-15',
  8,
  '{tubes}-octagon-15',
  '{tubes}-circle-15' // default
]

Using case

'icon-image': [
  'case',
  ['==', ['get', 'tap_ports'], 2],
  '{tubes}-circle-15',
  ['==', ['get', 'tap_ports'], 4],
  '{tubes}-square-15',
  ['==', ['get', 'tap_ports'], 4],
  '{tubes}-octagon-15',
  '{tubes}-circle-15' // default
]

Using property and stops

'icon-image': {
  property: 'tap_ports',
  type: 'categorical',
  stops: [
    [2, '{tubes}-circle-15'],
    [4, '{tubes}-square-15'],
    [8, '{tubes}-octagon-15']
  ]
}

All of those don't produce any icons.

Also, if I try to log the rendered features from that layer using queryRenderedFeatures I see only empty arrays, so the features aren't rendering due to my attempts.

If I simply set

'icon-image': '{tubes}-circle-15'

everything renders fine, but only as circles of course.

1

1 Answers

0
votes

Thanks for the suggestion @ChaseChoi.

When I first tried the steps it didn't work either but then I added a debug statement for my layer that was causing problems.

map.on('zoom', () => {
  console.log(map.queryRenderedFeatures({ layers: ['tubes'] }))
})

In here I noticed that the layout.image-icon property was something like {tubes}-circle-15, rather than blue-circle-15. {tubes} should have been a color.

So, staying with the steps approach I used the concat expression and it worked!

'icon-image': [
  'step',
  ['get', 'tap_ports'],
  ['concat', ['get', 'tubes'], '-circle-15'], // default
  2,
  ['concat', ['get', 'tubes'], '-circle-15'],
  4,
  ['concat', ['get', 'tubes'], '-square-15'],
  8,
  ['concat', ['get', 'tubes'], '-octagon-15']
]

I went back and tried the other approaches, using concat this time, and they all work expect for the "property and stops" approach.