I am using Leaflet.js for a map. Now I want to remove added layers from the map. By clicking the input #button all checked checkboxes shall be changed to unchecked and all corresponding layers shall be removed from the map.
To remove a layer from the map the id of the layer is needed. This id equals the id of the corresponding checkbox. That's why I use jQuery to get the ids of all checked checkboxes and store their value in an object, here called someObj.idsChecked.
When I try to use the stored value val to remove one layer it doesn't work while the console.log displays the wanted value. Here for example: mapcat52.
While inserting the previous id hard coded into the function like map.removeLayer(mapcat52) it works as expected.
Where is the error in my code or my thoughts?
Any help is much appreciated.
The HTML
<input type="button" id="selectnone" value="deselect all" />
<!-- checkboxes -->
<input id="mapcat52" type="checkbox" name="maplayer" class="maplayer">
<label for="mapcat52">Map Layer One</label>
<input id="mapcat53" type="checkbox" name="maplayer" class="maplayer">
<label for="mapcat53">Map Layer Two</label>
...
The JS:
$('#selectnone').click(function() {
var someObj = {};
someObj.idsChecked = [];
$("input:checkbox").each(function() {
if ($(this).is(":checked")) {
someObj.idsChecked.push($(this).attr("id"));
}
}).attr('checked', false);
$.each(someObj.idsChecked,function(id, val) {
// displays the wanted value, e.g. "mapcat52" if checkbox with this id is checked
console.log(val);
// does not work: inserted value
map.removeLayer(val);
// works: hard coded value of the leaflet.js/input id
map.removeLayer(mapcat52);
});
});
According to the Leaflet API doc http://leafletjs.com/reference.html#map-removelayer, removeLayer takes an ILayer parameter:
removeLayer( <ILayer> layer )
but you're passing it a String:$(this).attr("id")
It looks like you do have the layer object in a variable already: mapcat52. You could save the layer objects when you create them, then look them up by id to pass to removeLayer:
I would say the easiest way to remove/add (toggle) layers from the map would be to use a LayerGroup.
Before adding individual layers to the map, add them to a LayerGroup instead and then add that LayerGroup to your map.
Then when you have to remove the layers, just call the clearLayers() function.
Check out the API for LayerGroup http://leafletjs.com/reference.html#layergroup
Example
When remove checkbox is checked
I wrote the below example to show how to remove multiples geoJSON layer.
///adding geoJSON data
////// function to remove geoJSON layers
//// calling function
removeMarkers();