In my Google Maps application I can place markers on the map, and I keep a reference to each of the markers placed, along with some extra information in an array called markers
.
Adding markers is easy, I just push()
the newly created object onto the array (markers.push(marker)
);
However, when it comes to removing an arbitrary marker from the array, given an index of the slot, it doesn't behave as expected. My function is:
function deleteMarker(markerIndex) {
if (markerIndex!='' && markerIndex>=0 && markerIndex<markers.length) {
if (confirm('Do you really want to remove this marker from the map?')) {
alert('deleting marker '+markerIndex); //debugging purposes
markers.splice (markerIndex, 1);
}
}
}
I have no previous experience with the splice() function, but looking at its description @ w3schools it seems to be pretty straight-forward. However, I get the following behaviour:
markers.splice()
does nothing. So what am I doing wrong?
And also, when markerIndex
is 0 no confirmation box is shown. At first I assumed the lengthy if-condition evaluated to false and so the whole code block was skipped, however, using Firebug to step through the calls I found out that the condition holds (of course) for index 0 when array is non-empty, next step reveals that the if (confirm(...))
and alert('deleting...)
are skipped and markers.splice()
is called (but nothing happens). This behaviour is so strange I decided to open this question.
Can anyone please clarify what's going on?
I thought that deleting markers will be the easiest bit of functionality one could do. I can add them, edit their contents, even clear all markers (pop()
-ing markers off the markers
array until empty) and all works nicely.