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)};
}
I have made this code from yours to produce the desired output, see below.
You will need to replace the default class name I have put in classRectangle
to the one you want.
In the code you wrote there was a problem with the variable locSquare
at the line 3. This variable is not defined before you try to remove it from the map because you define it two lines below with the var locSquare
.
You should have put the initialization of the variable outside the function for it to work.
This is what we call the scope of a variable. If you initialize it as you do inside the function, once the function is finished you will not be able to use this variable.
Instead of using a variable, you can choose to use an option available for the Rectangle object in Leaflet : className
. With this option you can specify to Leaflet that this Rectangle has to use the CSS class you provided. In this way if you want to remove the Rectangle from the map you can just specify which class you want to target.
/**
* @param {number} lat
* @param {number} lng
* @param {number} zoom
*/
function showLoc(lat,lng,zoom) {
// Here is the class we will use to name the Rectangle we want to display on the map and eventually delete
const classRectangle = 'your_class_here';
// We retrieve every Rectangle on the map with the class specified before. We should only have zero or one class
classes = document.getElementsByClassName(classRectangle);
if(classes.length > 0) // If there is more than zero element that means we already have a rectangle on the map
{
classes[0].remove(); // we remove the existing Rectangle from the DOM and the map
}
let locSquare = L.rectangle(
[
[lat + 0.0208333333, lng - 0.0416666666],
[lat - 0.0208333333, lng + 0.0416666666]
],
{
color: "red",
weight: 2,
fillColor: "red",
className: classRectangle // the option className is used to add a class to the DOM element that will be created
}
).addTo(map);
map.setView([lat, lng], zoom); // We set the view depending on the params call with the function
}