简体   繁体   中英

How to delete the leaflet layer and redraw it again?

I'm using the following JavaScript code to draw the polygons in the map:

var map = L.map('map').setView([], 10);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=QA7i5Mpkd_m30IGElHziw', {
    maxZoom: 18,
    attribution: 'Map data &copy; <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://mapbox.com">Mapbox</a>',
    id: 'mapbox.light'
}).addTo(map);
map.doubleClickZoom.disable();

// get color depending on population density value
function getColor(d) {
    return  d > 3000 ? '#006400' :
            d > 2500 ? '#FFEDA0' :
            d > 2000 ? '#FFEDA0' :
            d > 1500 ? '#c8ff58' :
            d > 50   ? '#FFEDA0' :
            d > 20   ? '#6fdc6f' :
            d > 10   ? '#6fdc6f' :
                       '#FFEDA0';
}

function style(feature) {
    return {
        weight: 2,
        opacity: 1,
        color: '#999',
        fillOpacity: 0.7,
        fillColor: getColor(feature.properties.state1)
    };
}

function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#666',
        dashArray: '',
        fillOpacity: 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
        layer.bringToFront();
    }

    info.update(layer.feature.properties);
}

function resetHighlight(e) {
    geojson.resetStyle(e.target);
     info.update();
}

function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
    map.doubleClickZoom.disable();
}

function searchText(e,feature) {
    var layer = e.target;
    var search = {
        'zone': layer.feature.properties.name,
        'zone_id':layer.feature.id
    };
    $.ajax({
        type: "POST",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        url: "http:dataurl",
        data: JSON.stringify(search), // Note it is important
        success :function(result) {
            // do what ever you want with data
            //   alert("suc");

        },
        error:function(error){
            //alert("success");
            }
    });
 }


var lastClickedLayer;

function onMapClick(e,feature) {
    var layer = e.target;       
    $("#grid_name").html(layer.feature.properties.name);
    set_zone(layer.feature.id);
    searchText(e,feature);
}

function mapupdatecolor(startDate,endDate){

    $.getJSON('http:dataurl', function(data) {
        //console.log(data);
        for (i = 0; i <80; i++) { 
            console.log("1 time state1 in console--"+campus['features'][i]['properties']['state1']);
            campus['features'][i]['properties']['state1']=data[i].state1;
            console.log("2 time state1 in console after change--"+campus['features'][i]['properties']['state1']);
        }

        map.removeLayer(L.geoJson);

        var geojson = L.geoJson(campus, {
            style: style,
             onEachFeature: onEachFeature
        }).addTo(map);
    });
}

function onEachFeature(feature, layer) {
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        //click: zoomToFeature
        click:onMapClick
    });
}

geojson = L.geoJson(campus, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
    this._div.innerHTML = '<h4><b>Zones<b></h4>' +  (props ?
        '<b>' + props.name + '</b><br />'  
        : 'Hover over a zone');
};

info.addTo(map);

campus is the variable of the geoJson data of the polygon coordinates.

Here I have the function mapupdatecolor which updates the color of the polygon when I click a button. But now instead of updating the color in the polygon of the current layer it adds a new layer on the map with updated color of polygons. I am using map.removeLayer(L.geoJson); to remove the previous layer but it is not removing the previous layer.

Move the declaration of the layer outside your mapupdatecolor function.

var geojsonLayer;

Then, inside mapupdatecolor , remove the layer if it exists...

function mapupdatecolor() {
    fetch('http://dataurl').then(response=>response.json()).then(jsonData=>{

        if (geojsonLayer) { geojsonLayer.remove(); }

...then create the layer again with the newly fetched data

        geojsonLayer = L.geoJson(jsonData, {style: style, onEachFeature: onEachFeature })
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM