Rafael Alencar
Rafael Alencar

Reputation: 17

Directly update mapbox source features

I'm drawing orders on the map using layers with symbols, this orders has status. Whenever the status changes I'd like to change de color of the symbol.

My layer has this configuration:

map.addLayer({
    id: "orders",
    type: "symbol",
    source: "order-markers",
    layout: {
      "icon-image": [
        "match",
        ["get", "orderStatus"],
        "UNASSIGNED",
        "unassigned-marker",
        "ASSIGNED",
        "assigned-marker",
        "IN_TRANSIT",
        "intransit-marker",
        "CONCLUDED",
        "concluded-marker",
        "UNASSIGNED-marker",
      ],
    },
  });
});

Is there a recommended way to directly access the source and update the status in the properties object ? Or is it right to always overwrite the whole data object with setData ?

I tried to create a state in React with the features but it seems that the features object dont react to the state changes.

Thanks.

Upvotes: 0

Views: 1748

Answers (1)

Chan Youn
Chan Youn

Reputation: 892

I haven't found a way to update a single property on a single feature. What I've always done is to overwrite the data as you've mentioned (i.e. map.getSource('order-markers').setData(/*...*/)) with the whole data object where a feature's property was changed. This is the method mapbox uses in their example for updating with live data: live-update-feature

As an alternative however, you can update a single feature's state. If that's a possibility you can use map.setFeatureState.

for example:

map.setFeatureState(
  {
    source: 'order-markers',
    id: feature.id,
  }, {
    status: "IN_TRANSIT"
  }
);

You'll then have to update your layer style/expressions to use the state instead of property to properly reflect the data as they are slightly different in how you get the values.

Upvotes: 2

Related Questions