问题
my issue is I can't remove layer of each checkbox, I had already post this issue, unfortunately I didn't get any answer. I'm trying now to use layer group which I add to it layer for each clicked checkbox, but when I tried to remove each layer, it remove the last one, so I noticed that the layers are not added to layer group. So how to add layers to layer group dynamically, in other words how to add layer each time I clicked on a given checkbox? Can you help me please to figure out what is the problem? Any help is appreciated. Here is a snippet of code:
php file:
<script type="text/javascript">
$(document).ready(function(){
$('input[id^="DisplayCheckbox"]').on('click',function()
{
parent = $(this).val();
Coord = $(this).parents('#' + parent).find("li.Liste").text();
window.valChk = $(this).val();
if($(this).is(":checked"))
{
valChk = $(this).val();
$.drawPoly(Coord);
}else
{
$.removePoly(valChk);
}
});
});
</script>
external jquery file:
$.drawPoly = function(data)
{
data = $.parseJSON(data);
var geojsonFeature =
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": data.type,
"coordinates": data.coordinates
}
}]
};
window.poly=L.geoJson(geojsonFeature);
poly.id = valChk;
layerGrp=L.layerGroup([poly]);
addLayer(valChk);
};
function addLayer(id){
layerGrp.eachLayer(function (layer) {
if(layer.id == id){
layerGrp.addLayer(layer).addTo(map);
map.fitBounds(layer.getBounds());
console.log(layer._leaflet_id);
}
});
}
$.removePoly = function(id)
{
layerGrp=L.layerGroup([poly]);
layerGrp.eachLayer(function (layer) {
if(layer.id == id)
{
console.log(layer._leaflet_id);
layerGrp.removeLayer(layer);
}
});
};
回答1:
It seems to me that the answer to your previous question on that issue is still valid for the code you posted here: you seem to have a scoping issue (actually, several of them).
To be more specific, your layerGrp variable is used globally, and re-assigned within $.removePoly (statement layerGrp=L.layerGroup([poly])). Therefore you lose reference to the previous layers you added to map in addLayer, and you can no longer remove them.
Your code is quite overly complicated, making it difficult to understand what it does.
Once you simplify it, I am sure you will be able to solve your issue.
来源:https://stackoverflow.com/questions/42389595/cant-add-layers-dynamically-to-layer-group-when-click-checkboxes-using-leaflet