setFeatureState(
feature:FeatureIdentifier,state:any):this
Defined in: ui/map.ts:3971
Sets the state of a feature.
A feature's state is a set of user-defined key-value pairs that are assigned to a feature at runtime.
When using this method, the state object is merged with any existing key-value pairs in the feature's state.
Features are identified by their feature.id attribute, which can be any number or string.
This method can only be used with sources that have a feature.id attribute. The feature.id attribute can be defined in three ways:
- For vector or GeoJSON sources, including an
idattribute in the original data file. - For vector or GeoJSON sources, using the
promoteIdoption at the time the source is defined. - For GeoJSON sources, using the
generateIdoption to auto-assign anidbased on the feature's index in the source data. If you change feature data usingmap.getSource('some id').setData(..), you may need to re-apply state taking into account updatedidvalues.
Note
You can use the feature-state expression to access the values in a feature's state object for the purposes of styling.
Parameters
| Parameter | Type | Description |
|---|---|---|
feature |
FeatureIdentifier |
Feature identifier. Feature objects returned from Map.queryRenderedFeatures or event handlers can be used as feature identifiers. |
state |
any |
A set of key-value pairs. The values should be valid JSON types. |
Returns
this
Example
// When the mouse moves over the `my-layer` layer, update
// the feature state for the feature under the mouse
map.on('mousemove', 'my-layer', (e) => {
if (e.features.length > 0) {
map.setFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id,
}, {
hover: true
});
}
});
See
Create a hover effect