3

I have a function that will recreate polyline on click event. it works but the refresh layer still got the previous polyline. only when I zoom the map the previous polyline is gone.

My code.

function buildHotline(response) {
    //clearMap();
    //clear_polyline();
    document.getElementById('mapid').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
    //document.getElementById('map').innerHTML = "<div id='mapid' style='width: 100%; height: 100%;'></div>";
    var tiles = L.tileLayer('http://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', {
    attribution: 'Tiles courtesy of <a href="http://openstreetmap.se/" target="_blank">OpenStreetMap Sweden</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'});


    var map = new L.map('map', {
        layers: [tiles],
        scrollWheelZoom: true,
        dragging: true,
        tap: false
    });


    var hotlineLayer = L.hotline(response, {
        min: 0,
        max: 120,
        palette: {
            0.0: '#3ebcef',
            0.5: '#78b3d3',
            1.0: '#000203'
        },
        weight: 5,
        outlineColor: '#000203',
        outlineWidth: 1
    });



    //clear first
    clear_polyline();

    bounds = hotlineLayer.getBounds();
    map.fitBounds(bounds);



    hotlineLayer.addTo(map);


    function clear_polyline() {
        try {
            // statements
            setTimeout(function(){ map.invalidateSize()}, 400);
            //alert("erase line");
            map.removeLayer( hotlineLayer );

        } catch(e) {
            // statements
            console.log(e);
        }

    }

}

where do I have to put the clear_polyline to clear it first before the new polyline is created. Thanks

Shafiq Mustapa
  • 433
  • 3
  • 7
  • 16

1 Answers1

0

Put the reference to hotlineLayer outside the scope of the buildHotline() function, so that several runs of that function can refer to the same instance of hotlineLayer.

Then, check if it's undefined, remove it if it isn't, and re-assign with the newly built instance.

i.e.:

var thing;

function refreshThing() {
    if (thing) { remove(thing); }
    thing = newThing();
}

See also How to remove L.rectangle(boxes[i]) , as the solution is pretty similar.

IvanSanchez
  • 18,272
  • 3
  • 30
  • 45