I’m trying to delete all the markers from my map when the user presses a button, which sounds like it should be very simple so i’m probably missing something quite silly.
I have a global array to store them all in:
var markersArray = [];
I then add all the markers to the map aswell as pushing them onto the array:
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
title: description,
icon: image,
shadow: shadow,
shape: shape
});
markersArray.push(marker);
And finally i have declared a function that SHOULD delete all the markers from the array:
google.maps.Map.prototype.deleteOverlays = function() {
if (markersArray.length) {
var i;
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
This doesn’t work at all however and after countless hours of fiddling with it i’m completely lost. Where am I going wrong?
Thank you for your time 🙂
Your array iterator is wrong (and inefficient).
You were iterating through the properties of the array, not the elements.
See the modified code below:
I have done it this way without any problems, and it is also very efficient: