Skip to content

Instantly share code, notes, and snippets.

@bmcbride
Last active December 20, 2015 19:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmcbride/6186672 to your computer and use it in GitHub Desktop.
Save bmcbride/6186672 to your computer and use it in GitHub Desktop.
jQuery form layer toggling logic for Leaflet maps.
$('input[name="basemapLayers"]').change(function () {
// Remove unchecked layers
$('input:radio[name="basemapLayers"]:not(:checked)').each(function () {
map.removeLayer(window[$(this).attr('id')]);
});
// Add checked layer
$('input:radio[name="basemapLayers"]:checked').each(function () {
map.addLayer(window[$(this).attr('id')]);
});
});
$('input:checkbox[name="overlayLayers"]').change(function () {
var layers = [];
function sortByKey(array, key) {
return array.sort(function (a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
if ($('#' + $(this).attr('id')).is(':checked')) {
$('input:checkbox[name="overlayLayers"]').each(function () {
// Remove all overlay layers
map.removeLayer(window[$(this).attr('id')]);
if ($('#' + $(this).attr('id')).is(':checked')) {
// Add checked layers to array for sorting
layers.push({
'z-index': $(this).attr('z-index'),
'layer': $(this)
});
}
});
// Sort layers array by z-index
var orderedLayers = sortByKey(layers, 'z-index');
// Loop through ordered layers array and add to map in correct order
$.each(orderedLayers, function () {
map.addLayer(window[$(this)[0].layer[0].id]);
});
} else {
// Simply remove unchecked layers
map.removeLayer(window[$(this).attr('id')]);
}
});
@bmcbride
Copy link
Author

bmcbride commented Aug 8, 2013

Use with a standard HTML form like so:

<form>
    <input type="radio" name="basemapLayers" id="mapquestOSM" checked> Streets
    <input type="radio" name="basemapLayers" id="mapquestOAM"> Imagery

    <input type="checkbox" name="overlayLayers" id="boroughs" z-index="2" checked> Boroughs
    <input type="checkbox" name="overlayLayers" id="subwayLines" z-index="1"> Subway Lines
</form>

Input id should match the layer variable...

var mapquestOSM = L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {
    maxZoom: 19,
    subdomains: ["otile1", "otile2", "otile3", "otile4"],
    attribution: 'Tiles courtesy of <a href="http://www.mapquest.com/" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png">. Map data (c) <a href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a> contributors, CC-BY-SA.'
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment