When working with Google Maps V3 markers, I make sure to store the name of each marker in an array so I can quickly remove all of them from the map at once. For some reason though, when I call my function that is supposed to iterate through the entire array, removing all markers a long the way, the function returns undefined after only removing a few of the markers.
The array (markersArray) before the function:
["markerZip02111", "markerZip02139", "markerZip01002", "markerZip94602", "markerZip02460"]
The function code:
function removeAllMarkers(exceptId) {
$.each(markersArray, function(index, value) {
if(value != exceptId) {
eval(value+".setMap(null);");
markersArray.splice(value, 1);
console.log(value);
}
});
}
What the console displays:
markerZip02111
markerZip01002
markerZip02460
undefined
The array after the function is run:
["markerZip94602", "markerZip02460"]
Clearly the array is running successfully until it hits the “undefined” value and then it stops. What can I do to get around this problem??
I’m pretty sure the reason you’re getting an undefined value during iteration when your starting array doesn’t have any undefined values in it is that you’re removing items from the array while iterating through it. I guess this confuses the jQuery
$.each()iterator.If you look at your output, what is happening is this:
Notice that two of the items never got evaluated: the iterator skipped over them because you changed their indexes by removing items.
If you must remove items as you go it is easy with a conventional for loop that iterates backwards such that removing items won’t screw up the loop counter. (Or you can use a conventional for loop to go forwards as long as you adjust the counter variable each time you remove an item.)
Also, when you do splice you need to pass the index of the item as the first parameter, not the value of the item. So
markersArray.splice(index, 1);notmarkersArray.splice(value, 1);.So, something like: