Skip to content

Instantly share code, notes, and snippets.

@tristen
Created March 23, 2016 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tristen/0c0ed34e210a04e89984 to your computer and use it in GitHub Desktop.
Save tristen/0c0ed34e210a04e89984 to your computer and use it in GitHub Desktop.
Swap baselayer with a persistent data layer on top
<!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.15.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.15.0/mapbox-gl.css' rel='stylesheet' />
<script src='//d3js.org/d3.v3.min.js' charset='utf-8'></script>
</head>
<body>
<style>
body { margin:0; padding:0; }
.map { position:absolute; top:0; bottom:0; width:100%; }
.menu {
position:absolute;
z-index:1;
top:10px;
right:10px;
border-radius:3px;
width:120px;
}
.menu button {
font:13px/20px 'Helvetica Neue', sans-serif;
background:#3887be;
color:#fff;
display:block;
width:100%;
margin:0;
padding:0;
padding:10px;
border:none;
border-bottom:1px solid rgba(0,0,0,0.25);
cursor:pointer;
}
.menu button:first-child {
border-radius:3px 3px 0 0;
}
.menu button:last-child {
border-radius:0 0 3px 3px;
border:none;
}
.menu button.active,
.menu button:hover {
background-color:#52a1d8;
}
</style>
<nav id='menu' class='menu'></nav>
<div id='map' class='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoidHJpc3RlbiIsImEiOiJiUzBYOEJzIn0.VyXs9qNWgTfABLzSI3YcrQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v8',
center: [-88.1373, 35.1374],
zoom: 4
});
var baseLayers = [{
label: 'Streets',
id: 'streets-v8'
}, {
label: 'Light',
id: 'light-v8'
}, {
label: 'Dark',
id: 'dark-v8'
}];
var menu = document.getElementById('menu');
var geojson;
function addDataLayer() {
map.addSource('urban-areas', {
'type': 'geojson',
'data': geojson
});
map.addLayer({
'id': 'urban-areas-fill',
'type': 'fill',
'source': 'urban-areas',
'paint': {
'fill-color': '#f08',
'fill-opacity': 0.4
}
});
}
map.on('style.load', function () {
// Triggered when `setStyle` is called.
if (geojson) addDataLayer();
});
map.on('load', function () {
// Make an ajax request to the external source
d3.json('https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_urban_areas.geojson', function(err, data) {
if (err) return console.log(err);
geojson = data;
addDataLayer();
});
baseLayers.forEach(function(l) {
var button = document.createElement('button');
button.textContent = l.label;
button.addEventListener('click', function() {
map.setStyle('mapbox://styles/mapbox/' + l.id);
});
menu.appendChild(button);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment