Skip to content

Instantly share code, notes, and snippets.

@tristen
Created July 1, 2014 14:01
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 tristen/6ad0cfe8c0913c85a008 to your computer and use it in GitHub Desktop.
Save tristen/6ad0cfe8c0913c85a008 to your computer and use it in GitHub Desktop.
Toggle geojson layers with checkboxes
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Filter by feature layer</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v1.6.4/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v1.6.4/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
.filter-ui {
background:#fff;
position:absolute;
top:10px;
right:10px;
z-index:100;
padding:10px;
border-radius:3px;
}
</style>
<nav id='filters' class='filter-ui'>
</nav>
<div id='map'></div>
<script>
var map = L.mapbox.map('map', 'examples.h186knp8')
.setView([32.5, 41.1], 2);
var filters = document.getElementById('filters');
var layerOne = L.mapbox.featureLayer()
.loadURL('brazil.geojson')
.on('ready', layer);
var layerTwo = L.mapbox.featureLayer()
.loadURL('russia.geojson')
.on('ready', layer);
function layer() {
var layer = this;
var name = layer.getGeoJSON().name;
var item = filters.appendChild(document.createElement('div'));
var checkbox = item.appendChild(document.createElement('input'));
var label = item.appendChild(document.createElement('label'));
checkbox.type = 'checkbox';
checkbox.id = name;
label.innerHTML = name;
label.setAttribute('for', name);
checkbox.addEventListener('change', update);
function update() {
(checkbox.checked) ? layer.addTo(map) : map.removeLayer(layer);
}
}
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
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