Skip to content

Instantly share code, notes, and snippets.

@malwoodsantoro
Last active August 25, 2022 17:49
Show Gist options
  • Save malwoodsantoro/9a636184da2511ab13a19c2b14053724 to your computer and use it in GitHub Desktop.
Save malwoodsantoro/9a636184da2511ab13a19c2b14053724 to your computer and use it in GitHub Desktop.
Use feature state to change features to same color on hover
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Create a hover effect</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibWFsLXdvb2QiLCJhIjoiY2oyZ2t2em50MDAyMzJ3cnltMDFhb2NzdiJ9.X-D4Wvo5E5QxeP7K_I3O8w';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-100.486052, 37.830348],
zoom: 2
});
var hoveredStateId = null;
map.on('load', function () {
map.addSource("shapes", {
"type": "geojson",
"data": "./shape-data.geojson"
});
// The feature-state dependent fill-opacity expression will render the hover effect
// when a feature's hover state is set to true.
map.addLayer({
"id": "shape-fills",
"type": "fill",
"source": "shapes",
"layout": {},
"paint": {
"fill-color": ['case',
["boolean", ["feature-state", "hover"], false],
"#fff",
['match',['get', 'test'],
'foo', '#90e2bc',
'bar', '#faff67',
'baz', '#a0aabf',
'#a0aabf']],
"fill-opacity": 1,
}
});
map.on("mousemove", "shape-fills", function(e) {
if (e.features.length > 0) {
if (hoveredStateId) {
map.setFeatureState({source: 'shapes', id: hoveredStateId}, { hover: false});
}
console.log(e.features[0].id)
hoveredStateId = e.features[0].id;
map.setFeatureState({source: 'shapes', id: hoveredStateId}, { hover: true});
}
});
map.on("mouseleave", "shape-fills", function() {
if (hoveredStateId) {
map.setFeatureState({source: 'shapes', id: hoveredStateId}, { hover: false});
}
hoveredStateId = null;
});
});
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment