Skip to content

Instantly share code, notes, and snippets.

@andrewharvey
Created January 24, 2018 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewharvey/681739a659c6e9d2b180dac310e24ff6 to your computer and use it in GitHub Desktop.
Save andrewharvey/681739a659c6e9d2b180dac310e24ff6 to your computer and use it in GitHub Desktop.
Create a hover effect // source https://jsbin.com/cuvoper
<!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://www.alantgeo.com.au/share/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.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.eyJ1IjoiYWxhbnRnZW8tcHJlc2FsZXMiLCJhIjoiNkRKcXdVdyJ9.XVLiu2tRo5f2P__oBfdqsw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-100.486052, 37.830348],
zoom: 2
});
map.on('load', function () {
map.addSource("states", {
"type": "geojson",
"data": "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_admin_1_states_provinces.geojson"
});
map.addLayer({
"id": "state-fills",
"type": "fill",
"source": "states",
"layout": {},
"paint": {
"fill-color": "#627BC1",
"fill-opacity": 0.5
}
});
map.addLayer({
"id": "state-borders",
"type": "line",
"source": "states",
"layout": {},
"paint": {
"line-color": "#627BC1",
"line-width": 2
}
});
// When the user moves their mouse over the states-fill layer, we'll update the filter in
// the state-fills-hover layer to only show the matching state, thus making a hover effect.
map.on("mousemove", "state-fills", function(e) {
map.setPaintProperty("state-fills", 'fill-opacity', ["case", ["==", ["get", "name"], e.features[0].properties.name], 0.8, 0.5]);
});
// Reset the state-fills-hover layer's filter when the mouse leaves the layer.
map.on("mouseleave", "state-fills", function() {
map.setPaintProperty("state-fills", 'fill-opacity', 0.5);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment