How to delete an infowindow bound with a marker?

10,441

Solution 1

can't you just delete them along with the markers?

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].infoWindow.setMap(null);
      markersArray[i].infoWindow = null; //this one is not necessary I think nut won't hurt
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

Solution 2

Nothing's really being deleted, just the map property on the marker is being set to null. If you really want to delete the markers, you could use the delete operator.

// Deletes all markers in the array by removing them from the array
function deleteOverlays() {
  if (markersArray) {
    var arrayLength = markersArray.length;
    for (var i = 0; i < arrayLength; i++) {
      delete markersArray[i];
    }
    markersArray.length = 0;
  }
}
Share:
10,441
Rocky
Author by

Rocky

Updated on November 21, 2022

Comments

  • Rocky
    Rocky 7 months

    I wrote a chunk of Google Maps API code follow this idea.

    But, when I delete all markers, the infowindows bound to these markers are not deleted.

    Can anyone show me the solution?

    Thanks.

    This is how I delete the markers:

    // Deletes all markers in the array by removing references to them
    function deleteOverlays() {
      if (markersArray) {
        for (i in markersArray) {
          markersArray[i].setMap(null);
        }
        markersArray.length = 0;
      }
    }
    

    markersArray is a global var which stores all the markers.

    I declared the infowindows like this:

    marker.infowindow = new google.maps.InfoWindow(
            {
                content: '<div>something here</div>'
            });
    
    • duncan
      duncan over 11 years
      How do you 'delete' a marker?
    • Rocky
      Rocky over 11 years
      i edited, can u see what's wrong
  • Matt Jensen
    Matt Jensen almost 8 years
    Actually I found that setting the infoWindow to null was necessary for me.