I'm trying to allow my Mapbox zones to have both clicked and hover states. Once something has been clicked I want that to persist, stay in that state, even if I then hover on another tile.
In implementing it though, what happens is when I click it turns to the clicked state, but moving my mouse on that area or another tile changes it from clicked back to hover.
Here is a demo of this: https://codepen.io/hiven/pen/zYPbRNK
The key bit of code is here:
if (hoveredStateId !== null) {
map.setFeatureState(
{ source: "states", id: hoveredStateId },
{ mystate: null }
);
}
if (hoveredStateId !== 2) {
hoveredStateId = e.features[0].id;
map.setFeatureState(
{ source: "states", id: hoveredStateId },
{ mystate: 1 }
);
}
The state 1 is hover, state 2 is clicked. With this code I thought it would only set the state to hover if the tile is not at clicked state (2) already. However this doesn't seem to work, as moving your mouse on a clicked tile changes it to hover state.
Where have I gone wrong?
You didn't include quite enough code above. The key bit of code is actually this:
map.on('mousemove', 'state-fills', (e) => {
if (e.features.length > 0) {
if (hoveredStateId !== null) {
map.setFeatureState({
source: "states",
id: hoveredStateId
}, {
mystate: null
});
}
It says: when the mouse moves over anything, clear the current state.
Also, this is clearly wrong:
if (hoveredStateId !== 2) {
You seem to have confused the state (null, 1 or 2) with the id of the feature (any number 0 or greater).