1

I'm creating a Google map with multiple markers. At the moment each marker has an infowindow, how can I only have one infowindow open at a time?

At the moment it closes all windows on clicking the map.

I know this question has been asked a few times but the code seems vastly different to mine.

// if marker contains HTML, add it to an infoWindow
if( $marker.html() )
{
    // create info window
    var infowindow = new google.maps.InfoWindow({
        content     : $marker.html()
    });

    // show info window when marker is clicked
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open( map, marker );
    });

    google.maps.event.addListener(map, 'click', function(event) {
        if (infowindow) {
            infowindow.close(); }
        }); 

}
Rob
  • 6,304
  • 24
  • 83
  • 189
  • You're creating new infoWindow's for each marker and also event listeners for each of those infowindows. Most people get around this by setting up just one infoWindow, and setting it's position and content when a marker is clicked. This is also optimal in terms of performance. If that doesn't suit, you could in theory close all infowindows when opening a new one, but you would need to store in an array and loop through. – Paul Thomas Dec 01 '16 at 15:16
  • duplicate of [Google Maps API - only one infowindow open at once](http://stackoverflow.com/questions/33713676/google-maps-api-only-one-infowindow-open-at-once) – geocodezip Dec 01 '16 at 15:17

1 Answers1

3

Try this: declare just one infowindow (global to the map, not one by marker).

var infoWindow;
...
if( $marker.html() ){
    google.maps.event.addListener(marker, 'click', function() {
      if (infoWindow) infoWindow.close(); 
      infoWindow = new google.maps.InfoWindow({
         content     : $marker.html()
       });
       infoWindow.open( map, marker );
    });
}
Thierry
  • 5,133
  • 3
  • 25
  • 30