Skip to content

Instantly share code, notes, and snippets.

@tristen
Created July 14, 2016 20:20
Show Gist options
  • Save tristen/9d481a6e81941d7b79e974f440d29f81 to your computer and use it in GitHub Desktop.
Save tristen/9d481a6e81941d7b79e974f440d29f81 to your computer and use it in GitHub Desktop.
Using a temporary source to highlight
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></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.21.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.21.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.eyJ1IjoidHJpc3RlbiIsImEiOiJiUzBYOEJzIn0.VyXs9qNWgTfABLzSI3YcrQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-100.486052, 37.830348],
zoom: 2
});
var geojson = {
}
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"
});
// Hovered areas receive an outline state
var source = new mapboxgl.GeoJSONSource({
data: {
type: 'FeatureCollection',
features: []
}
});
map.addSource('polygon-hover', source);
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
}
});
map.addLayer({
'id': 'polygon-hover',
'source': 'polygon-hover',
'type': 'line',
'paint': {
'line-color': 'rgba(0,0,0,0.5)',
'line-width': 1
}
});
// When the user moves their mouse over the page, we look for features
// at the mouse position (e.point) and within the states layer (states-fill).
// If a feature is found, then we'll update the filter in the route-hover
// layer to only show that state, thus making a hover effect.
map.on("mousemove", function(e) {
var features = map.queryRenderedFeatures(e.point, { layers: ["state-fills"] });
map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
if (features.length) {
source.setData({type: 'FeatureCollection', features: [features[0]]});
} else {
source.setData({type: 'FeatureCollection', features: []});
}
});
// Reset the route-hover layer's filter when the mouse leaves the map
map.on("mouseout", function() {
map.setFilter("route-hover", ["==", "name", ""]);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment