Skip to content

Instantly share code, notes, and snippets.

@yhahn
Created November 27, 2012 19:47
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 yhahn/4156545 to your computer and use it in GitHub Desktop.
Save yhahn/4156545 to your computer and use it in GitHub Desktop.
Exclusive layer switcher with interactivity
<!DOCTYPE html>
<html>
<head>
<script src='http://api.tiles.mapbox.com/mapbox.js/v0.6.6/mapbox.js'></script>
<link href='http://api.tiles.mapbox.com/mapbox.js/v0.6.6/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
#map-ui {
position:absolute;
top:10px;left:10px;
list-style:none;
margin:0;padding:0;
z-index:100;
}
#map-ui a {
font:normal 13px/18px 'Helvetica Neue',Helvetica,sans-serif;
background:#FFF;
color:#3C4E5A;
display:block;
margin:0;padding:0;
border:1px solid #BBB;
border-bottom-width:0;
min-width:138px;
padding:10px;
text-decoration:none;
}
#map-ui a:hover { background:#ECF5FA; }
#map-ui li:last-child a {
border-bottom-width:1px;
-webkit-border-radius:0 0 3px 3px;
border-radius:0 0 3px 3px;
}
#map-ui li:first-child a {
-webkit-border-radius:3px 3px 0 0;
border-radius:3px 3px 0 0;
}
#map-ui a.active {
background:#3887BE;
border-color:#3887BE;
border-top-color:#FFF;
color:#FFF;
}
</style>
<ul id='map-ui'></ul>
<div id='map'></div>
<script>
var map = mapbox.map('map');
var layers = document.getElementById('map-ui');
// Layer loading from an ID is asynchronous so we provide map.interaction.auto
// as the callback for once loading is complete to enabled interaction.
map.addLayer(mapbox.layer().composite(false).id('examples.npr-stations', map.interaction.auto));
map.addLayer(mapbox.layer().composite(false).id('examples.bird-species', map.interaction.auto));
map.centerzoom({ lat: 38.9, lon: -77.03 }, 5);
// Create a layer switcher that toggles layers exclusively.
for (var i = 0; i < map.getLayers().length; i++) {
var n = map.getLayerAt(i).name;
var item = document.createElement('li');
var layer = document.createElement('a');
layer.href = '#';
layer.id = n;
layer.innerHTML = 'Layer ' + (i + 1);
if (i === 0) {
layer.className = 'active';
map.getLayerAt(i).enable();
} else {
map.getLayerAt(i).disable();
}
layer.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
// Disable layers and clear active class out from any layer links.
for (var j = 0; j < map.getLayers().length; j++) {
map.getLayerAt(j).disable();
layers.childNodes[j].childNodes[0].className = '';
}
// Set this layer to active.
this.className = 'active';
map.getLayer(this.id).enable();
map.interaction.refresh();
};
item.appendChild(layer);
layers.appendChild(item);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment