I am trying to get Mapbox GL work in my React code as below:

I have a property called strength in each of my features in a FeatureCollection of a mapbox-gl map. I want to display a circle (ideally a marker) based on the value of strength property (0-3: green, 4-7: yellow, 8+: red). To test this, I am initially having three features with strength as 3(green), 6(yellow), and 9(red) respectively. I have a button on click of which the strength of all the three features updates to 8. At this point, I want all the circle colors to become red. However, there is no change in the colors.

The click handler of the button is as below:

handleClick = () => {
  const newFeatures = this.state.features.map(feature => ({...feature}));
  newFeatures.forEach(feature => feature.properties.strength = 8);
  this.setState({feature: newFeatures}, () => this.state.features.forEach(feature => console.log(feature.properties.strength))

The features are defined in the component state and componentDidUpdate looks like this:

componentDidUpdate() {
  console.log('Component Updated');
  this.state.features.forEach(feature => console.log(feature.properties.strength));
  this.map.getSource('institutions')._data.features.forEach(feature => console.log(feature.properties.strength));
  this.map.setPaintProperty("institutions-layer", 'circle-color', generatePropertyFunction());

generatePropertyFunction looks like this:

function generatePropertyFunction() {
  const propertyFunction = {
    property: "strength",
    type: "categorical",
    default: "rgba(0,0,0,0)",
    stops: [
      [0, '#7ff000'],
      [1, '#7ff000'],
      [2, '#7ff000'],
      [3, '#7ff000'],
      [4, '#ffff00'],
      [5, '#ffff00'],
      [6, '#ffff00'],
      [7, '#ffff00'],
      [8, '#ff0000'],
      [9, '#ff0000'],
      [10, '#ff0000']
  return propertyFunction

This works the first time the map is rendered as the 3 locations are marked in green, yellow and red as intended. But after click of button, when the property strength is updated to 8 (this is verified in both console.log statements) the colors of the marker don't change. However, on click of button, if I explicitly set the circle-color to any one color, it works as below:

this.map.setPaintProperty("institutions-layer", 'circle-color', '#ff0000');

Am I missing something here or is this a bug?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.