Leaflet : removing rectangle
12:47 02 Oct 2022

I need to draw a rectangle on a map with Leaflet, and remove it when I create another one.

I call a function to do that and zoom on the rectangle. It creates the rectangle, but I'm unable to remove it when calling the function again.

I can remove it if I do that just after having created the rectangle.

What's wrong with it ? I'm a Leaflet and Javascript beginner...

Thanks,

function showLoc(lat,lng,zoom) {
    map.setView([lat,lng],zoom);

    locSquare.remove(map)
    //if (map.hasLayer(locSquare)) {locSquare.remove(map)}; 

    var locSquare = L.rectangle([[lat + 0.0208333333, lng - 0.0416666666],[lat - 0.0208333333, lng + 0.0416666666]], {color: "red", weight: 2,fillColor:"red"}).addTo(map);

    //if (map.hasLayer(locSquare)) {locSquare.remove(map)}; 
    }
javascript leaflet