Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close infowindow when another marker is clicked

I have the following code to open an infowindow when a specific marker is click and it open a window. Does anyone know how to close the previous infowindow when another one is clicked?.

   google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map1, marker);
        });
like image 815
user1292656 Avatar asked Sep 27 '12 12:09

user1292656


People also ask

How do I put infowindow on marker?

Move an info windowAttach the info window to a new marker using the InfoWindow. open() method. Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.


2 Answers

Just make sure you only create ONE infoWindow in the global scope, like this:

infoWindow = new google.maps.InfoWindow; //static infoWindow for all your markers
google.maps.event.addDomListener(window, 'load', function() {
   //create your markers here
   google.maps.event.addListener(marker, 'click', function() {
               infoWindow.open(map1, marker); //take care with case-sensitiveness
          });
});

UPDATE:

  • Fix case sensitive spotted by Duncan.
  • Illustrate the marker click handlers must be connected after marker creation, both inside page load event.
like image 117
Nelson Avatar answered Oct 21 '22 06:10

Nelson


Create a global variable in your JS file, name it lastOpenedInfoWindow or whatever you want, after that close it before opening a new info window, assign the "lastOpenedInfoWindow" to the currently opened window and so on

google.maps.event.addListener(marker, 'click', (function(marker, content, infowindow) {
        return function() {
            closeLastOpenedInfoWindow();
            infowindow.setContent(content);
            infowindow.open(map, marker);
            lastOpenedInfoWindow = infowindow;
        };
    })(marker, makrerdata[i], infowindow));
}


function closeLastOpenedInfoWindow() {
    if (lastOpenedInfoWindow) {
        lastOpenedInfoWindow.close();
    }
}
like image 33
Baha' Al-Khateib Avatar answered Oct 21 '22 04:10

Baha' Al-Khateib