TransWikia.com

How to remove layer from layer control in Leaflet

Geographic Information Systems Asked by Pelzhong on July 31, 2021

I have an AJAX call to dynamically create heatmap from database on an addOverlay layercontrol. This event is handled by a button whose text changes upon click event. I am able to add layer to map but not able to remove (when I remove and add again by clicking "generate heatmap", a new "HWC HeatMap" is added each time on LayerControl). How can I solve this problem?

<button id="btnHeatMap" class='btn btn-primary btn-block'>Generate HeatMap</button>

$("#btnHeatMap").click(function(){
    var heatMapPoints = [];
    var heatHWC;
    $.ajax({
        url:'heatmap.php',
        success: function(response){
            jsnHWC = JSON.parse(response);
            jsnHWC.features.forEach(function(feature){
                heatMapPoints.push([feature.geometry.coordinates[1],feature.geometry.coordinates[0], 0.5]);
            });
            heatHWC = L.heatLayer(heatMapPoints, {
                radius: 25,
                minOpacity: 0.4,
                gradient: {0.3: 'green', 0.7: 'yellow', 1: 'red'}
            });
            
            if($("#btnHeatMap").html()=="Generate HeatMap") {
                heatHWC.addTo(mymap);
                ctlLayers.addOverlay(heatHWC, "HWC HeatMap");
                $("#btnHeatMap").html("Remove HeatMap");
            } else {
                if(mymap.hasLayer(heatHWC)){
                    mymap.removeLayer(heatHWC);
                }
                $("#btnHeatMap").html("Generate HeatMap");
            }
        },
        error: function(xhr, status, error) {
            console.log("ERROR: "+error);
        }
    });
});

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP