Last active
December 20, 2015 19:58
-
-
Save bmcbride/6186672 to your computer and use it in GitHub Desktop.
jQuery form layer toggling logic for Leaflet maps.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('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')]); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use with a standard HTML form like so:
Input id should match the layer variable...