lundi 11 mars 2019

javascript remove leaflet layer when checkbox is unchecked

I have an JS object where the 1st value is the div id referring to the checkbox, 2nd value is where the data is getting pulled from and the 3rd is the color

var layers={childcares: ["#childcares",'http://127.0.0.1:8000/childcare_data/','orange'], childcare_buff: ["#childcaresbuff","http://127.0.0.1:8000/childcare_buff_data/","orange"],
            religious: ["#religious","http://127.0.0.1:8000/religious_data/","blue"], religious_buff: ["#religiousbuff","http://127.0.0.1:8000/religious_buff_data/","blue"],
            park: ["#parks","http://127.0.0.1:8000/park_data/","green"],park_buff: ["#parksbuff","http://127.0.0.1:8000/park_buff_data/","green"],
            school: ["#schools","http://127.0.0.1:8000/school_data/","red"],school_buff: ["#schoolsbuff","http://127.0.0.1:8000/school_buff_data/","red"]
            };

now I have these two functions

    function color(feature, color_chosen, opacity){
        return{
        color: color_chosen,
        fillOpacity: opacity}
       };

this color one above is fairly simple and just sets the color

the legend_click one is where I am getting problems

    function legend_click(id,layer_api,color_layer) {
        $(id).click(function () {
          var layer_add=new L.GeoJSON.AJAX(layer_api,{
            style: color(layer_add,color_layer,0.8),
            onEachFeature: function(feature,layer_add){
             layer_add.bindPopup('<b>Buffer Type</b> = ' +feature.properties.buff+ '<br>'
                            +'<b>Address</b> = '+feature.properties.address+ '<br>' +'<b>Buffer Distance</b> = '+feature.properties.buff_dist)
                    }
                   }
                );
            if ($(id).prop('checked')==true) {
                layer_add.addTo(map);
                //map.fitBounds(layer_add.getBounds())
            }
            else if ($(id).prop('checked')==false) {
                console.log('noury') 
                map.removeLayer(layer_add);
            }
        })
    };

looping through the layers like this

for (var key in layers){
        console.log(layers[key])
        legend_click(layers[key][0],layers[key][1],layers[key][2])
    };

so in the map when I click on the checkbox the layer correctly gets added to the display but when I uncheck the checkbox is it throws error and prints out noury to the console.




Aucun commentaire:

Enregistrer un commentaire