Hi, i have the following problem: I have a map in leaflet linked to a change function in jquery, depending on the ID that I receive in the "select" of the previous query, the case is entered below in JS:
//First the map
var map = L.map('map').setView([XXXX, XXXXX], 12);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
minZoom: 12,
maxZoom: 100
}).addTo(map);
function popup(feature, layer) {
if (feature.properties && feature.properties.COMUNA)
{
layer.bindPopup( "<strong>" "INF.EX: " "</strong>" feature.properties.INF);
}
};
//Finish the map
//Start the CASE
$("body").on("change", "[name=EXAMPLE]", function ()
{
var NUM = $('#EXAMPLE').val();
switch (NUM) {
case '1':
map.setView([XXXX, XXXX], 15,{
animate: true
});
var examplemap= L.geoJson(EXAMPLE_01, {
onEachFeature: popup
});
L.geoJson(EXAMPLE01).addTo(map);
examplemap.addTo(map);
break;
case '2':
map.setView([XXXX, XXXX], 15,{
animate: true
});
var examplemap= L.geoJson(EXAMPLE_02, {
onEachFeature: popup
});
L.geoJson(EXAMPLE02).addTo(map);
examplemap.addTo(map);
break;
}});
At the moment of choosing another case (Stored in a select in HTML ) the data that the first case that I have chosen gave me is still stored in the map, how could I get these data that are in the map to be deleted so that Does the other case apply?
If there is a need for another part of the code or if there is any inconsistency, you can tell me, thanks!
CodePudding user response:
To reset everything on your map you can use the eachLayer
method of your map, to remove all layers previously added:
map.eachLayer((layer) => {
layer.remove();
});
[EDIT] To only delete a specific layer, you need to keep track of it:
var map = L.map('map').setView([XXXX, XXXXX], 12);
var myLayer = new L.LayerGroup();
...
// inside your case otpions:
// remove everything from your layer (you should move this to a function)
myLayer.eachLayer((layer) => {
layer.remove();
});
// and then instead of adding to your map, add the layer to your myLayer
examplemap.addTo(myLayer);