I have a google map using V3 of the API. It has one marker on it which is draggable and then a load of other markers that are static. I have set up a dragend listener for the draggable marker which calls a function called clear_markers() like so:
google.maps.event.addListener(marker_0, "dragend", function() {
clear_markers();
});
function clear_markers()
{
if (markers) {
for (var i = 1; i <= markers.length; i++ ) {
if(typeof markers[i] !== "undefined") {
markers[i].setMap(null);
}
}
}
}
The reason I start the for loop at 1 and not 0 is that my draggable marker is the first marker so I want to clear all markers from the map except this one.
Here is the problem:
If I call clear_markers(); in any other way it works fine and the markers are removed from the map, so something like this works:
$('#mybutton').click(function() {
clear_markers();
});
When you drag and drop the green marker though and it’s called from the dragend listener it does not work. The markers do get removed but then they immediately get re added again. I know they do get removed because if I put something in the clear_markers() function just after the for loop that kills the script, the markers get removed. But if the script is allowed to continue they are still there meaning they have been removed and then instantly added back on again.
I’m not calling any other code so it seems like a bug with the api to me. Does anyone have any ideas?
Here is a working example showing the problem:
Remove the markerClusterer. It is adding the markers back in and you aren’t using it.
Update:
Since you need to keep it, if you want the markers to not be displayed, you need to remove them from the markerClusterer:
(but you will need to make it global to use it that way)