1

I am using Mapbox Studio for mapping/styling and the GL JS for adding user interactivity. I want to be able to change individual polygon color on mouseenter that is part of 44 polygons total in one layer.

I've checked the Mapbox documentation/examples/tutorials and am only finding answers to using this type of feature when using map.addLayer() it directly in the JS. I managed to change opacity but only for whole layer.

I have tried using this from another SO post but it fills all of the polygons in the entire layer in black, the backup color.

  'Icons', 
  'icon-opacity', 
  ['match', ['get', 'id'], 'example-id', 0.5 , 1]

My code:

map.on('mouseenter', 'pta-cos-polygons', (e) => {
    const feature = e.features[0];
    map.setFeatureState({
        source: 'composite',
        sourceLayer: 'pta-cos-polygons',
        id: feature.id,
    },
    {hover: true}
    );
            
map.setPaintProperty(
    'pta-cos-polygons',
    'fill-color',
    ['match', ['get', 'id'], 'feature.id', 'red', 'black']
    );
});

I don't know if it's just a matter of knowing the proper syntax, but it seems that if I have the id of the specific polygon (which I do) I should be able to do this.

1 Answers1

0

You're setting the hover state on a feature, so you should use hover to determine the color, not the feature ID, like this:

map.setPaintProperty(
    'pta-cos-polygons',
    'fill-color',
    ['case', ['to-boolean', ['feature-state','hover']], 'red', 'black']
    );
});

Note that you also need some more code to remove the hover feature-state when the mouse moves out, otherwise all your features will progressively turn red.

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • Oh I see--thanks for the clarification. How can I preserve the colors of the other polygons that already have colors defined in the mapbox style file, since the 'case' statement requires 4 parameters? The 'red' and 'black' were only for testing purposes. – Melissa DeMund Aug 07 '21 at 18:55
  • Next time I suggest putting in all of your goals up front. You can ask another question if you need to. – Steve Bennett Aug 08 '21 at 02:46