I am trying to create an interactive map with cluster that need to be displayed when user checks a box and removed when the box is unchecked again. So far everything is working well, the cluster work and everything, but I have noticed a strange behavior that I can't explain and fix : every time I uncheck the box and check it again, the number displayed in the cluster is incremented by the amount of marker in that region (so it somehow never gets reseted to zero when I do "clearMarkers"
Here is the code for the function concerned :
//Display or remove PREDICTED accident's markers.
function toDisplayPredictedAccidents ()
{
//If the checkbox is checked : Display all the PREDICTED accident's markers.
if(checkBoxPredicted.checked == true)
{
for (i = 0; i < predictedAccidentArray.length; i++)
{
marker = new google.maps.Marker
({
position: new google.maps.LatLng(predictedAccidentArray[i][1], predictedAccidentArray[i][2]),
icon : iconPredicted
});
markersPredicted.push(marker); //Put the created marker in an array.
//Create the pop-up when we click on the marker.
google.maps.event.addListener(marker, 'click', (function(marker, i)
{
return function()
{
infowindow.setContent(predictedAccidentArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
markerClusterPredicted = new MarkerClusterer(map, markersPredicted);
}
else
{
clearPredictedMarkers();
markerClusterPredicted.clearMarkers();
}
}
//clearMarkers and setAllMap are related and aim to REMOVE all the PREDICTED accident's markers.
function clearPredictedMarkers() {
setAllMapPredicted(null, markersPredicted);
}
function setAllMapPredicted(map, markersArray)
{
for (var i = 0; i < markersArray.length; i++)
{
markersPredicted[i].setMap(map);
}
}
Anyone knows how to fix this behavior ? :)
Just for anyone who is searching on the internet for actual answer (since this question is very old):
var markerCluster = new MarkerClusterer(map, markers);
markerCluster.clearMarkers();
this will remove all markers in markerCluster.
Everything can be found here: https://googlemaps.github.io/js-marker-clusterer/docs/reference.html¨
Update 10.11.2020
js-marker-clusterer
has moved and the old repo is no longer maintained. Instead, you should use https://github.com/googlemaps/v3-utility-library
Update 13.1.2022
I think links should be probably updated once again. I was able to find 2 repos and I do not know a difference:
https://github.com/googlemaps/js-markerclustererplus
https://github.com/googlemaps/js-markerclusterer
And here is documentation: https://googlemaps.github.io/js-markerclusterer/
markerCluster.remove(myMarker);
If you have a list of markers to remove just do that :
for (var i = 0; i < markers.length; i++) {
markerCluster.removeMarker(markers[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With