javascriptleafletpolygonmaptiler

Leaftjs remove all current polygoones, and redraw all


I am working on a project, where I am using Leaftjs(1.6). And https://api.maptiler.com/maps/streets for tile layer.

In the first time, the polygons are drawing correctly. In my site, I am using an input range, where user can change the input range, it with that value is will update polygons, with new colours and popup value.

So, in the input range callback, first I try to remove all the previous polygons and then redraw it again. It works well if the user changes the input range smoothly.

enter image description here

But the problem arises when the user moves the input range very quickly. I get this kind of map outputs. enter image description here

Here is my input range code

<input type="range" min="1" max="100" value="100" class="slider" id="myRange">

For removing polygons, I used

map.eachLayer(function (layer) {
        if (!!layer.toGeoJSON) {
            map.removeLayer(layer);
            //console.log(layer)
        } else {
            console.log("I am not removing:", layer)
        }
    });

And

for (i in map._layers) {
        if (map._layers[i]._path != undefined) {
            try {
                map.removeLayer(map._layers[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }
        } else {
            console.log(i)
        }
    }

But both are showing similar results.

Here is my complete code,

var slider = document.getElementById("myRange");
var output = document.getElementById("rangeValue");
output.innerHTML = slider.value; // Display the default slider value

var date = Date.parse(myDate)

output.innerHTML = date.toString('d-M-yy');

// Update the current slider value (each time you drag the slider handle)
slider.oninput = function () {
    var date2 = Date.parse(myDate)
    var current = date2.add(-(100 - this.value)).day();
    output.innerHTML = current.toString('d-M-yy');

    map.eachLayer(function (layer) {
        if (!!layer.toGeoJSON) {
            map.removeLayer(layer);
            //console.log(layer)
        } else {
            console.log("I am not removing:", layer)
        }
    });

    // for (i in map._layers) {
    //     if (map._layers[i]._path != undefined) {
    //         try {
    //             map.removeLayer(map._layers[i]);
    //         } catch (e) {
    //             console.log("problem with " + e + map._layers[i]);
    //         }
    //     } else {
    //         console.log(i)
    //     }
    // }

    $.ajax({
        url: 'global/',
        data: {
            'date': current.toString('yyyy-MM-dd')
        },
        dataType: 'json',
        success: function (data) {
            if (data != null) {
                //console.log("Got data")
                //console.log(data.length)
                for (var i = 0; i < data.length; i++) {
                    var coun = data[i];
                    try {
                        var latlngs = countriesLocation[coun.country];
                        if (latlngs != null) {
                            html = "updated popup data"

                            var color = '#ef0909';

                            if (coun.value > 500_000) {
                                color = '#DF0101';
                            } else if (coun.value > 200_000) {
                                color = '#ea2c2c';
                            } else {
                                color = '#BEF781';
                            }

                            var polygon = L.polygon(latlngs, {
                                color: color, fillColor: color,
                                fillOpacity: 0.3
                            }).addTo(map);
                            polygon.bindPopup(html);

                            // console.log(coun.country)
                            // console.log(i)
                        } else {
                            //console.log("I have no lat lon " + coun.country)
                        }
                    } catch (e) {
                        //console.log(e)
                    }
                }
            }
        }
    });
}

How can I fix this, and get clear outputs?


Solution

  • Add your polygons to a L.featureGroup instead to the map. Then you can call fg.clearLayers() and all layers are removed. Also I would clear the layers in the ajax, so if there are multiple request, there are not added multiple times.

    var fg = L.featureGroup().addTo(map);
    slider.oninput = function () {
        var date2 = Date.parse(myDate)
        var current = date2.add(-(100 - this.value)).day();
        output.innerHTML = current.toString('d-M-yy');
    
        fg.clearLayers();
    
        $.ajax({
            url: 'global/',
            data: {
                'date': current.toString('yyyy-MM-dd')
            },
            dataType: 'json',
            success: function (data) {
                if (data != null) {
                    fg.clearLayers();
    
                    for (var i = 0; i < data.length; i++) {
                        var coun = data[i];
                        try {
                            var latlngs = countriesLocation[coun.country];
                            if (latlngs != null) {
                                html = "updated popup data"
    
                                var color = '#ef0909';
    
                                if (coun.value > 500_000) {
                                    color = '#DF0101';
                                } else if (coun.value > 200_000) {
                                    color = '#ea2c2c';
                                } else {
                                    color = '#BEF781';
                                }
    
                                var polygon = L.polygon(latlngs, {
                                    color: color, fillColor: color,
                                    fillOpacity: 0.3
                                }).addTo(fg);
                                polygon.bindPopup(html);
    
                            } else {
                                //console.log("I have no lat lon " + coun.country)
                            }
                        } catch (e) {
                            //console.log(e)
                        }
                    }
                }
            }
        });
    }