Have just one InfoWindow open in Google Maps API v3

JavascriptGoogle MapsGoogle Maps-Api-3

Javascript Problem Overview


I need to have only one InfoWindow open on my Google Map. I need to close all other InfoWindows before I open a new one.

Can someone show me how to do this?

Javascript Solutions


Solution 1 - Javascript

You need to create just one InfoWindow object, keep a reference to it, and reuse if for all the markers. Quoting from the Google Maps API Docs:

> If you only want one info window to display at a time (as is the behavior on Google Maps), you need only create one info window, which you can reassign to different locations or markers upon map events (such as user clicks).

Therefore, you may simply want to create the InfoWindow object just after you initialize your map, and then handle the click event handlers of your markers as follows. Let's say you have a marker called someMarker:

google.maps.event.addListener(someMarker, 'click', function() {
   infowindow.setContent('Hello World');
   infowindow.open(map, this);
});

Then the InfoWindow should automatically close when you click on a new marker without having to call the close() method.

Solution 2 - Javascript

Create your infowindow out of the scope so that you can share it.

Here is a simple example:

var markers = [AnArrayOfMarkers];
var infowindow = new google.maps.InfoWindow();

for (var i = 0, marker; marker = markers[i]; i++) {
  google.maps.event.addListener(marker, 'click', function(e) {
    infowindow.setContent('Marker position: ' + this.getPosition());
    infowindow.open(map, this);
  });
}

Solution 3 - Javascript

I had the same problem but the best answer didn't solve it completely, what I had to do in my for statement was using the this relating to my current marker. Maybe this helps someone.

for(var i = 0; i < markers.length; i++){
	name = markers[i].getAttribute("name");
	address = markers[i].getAttribute("address");        
	point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));										
	contentString = '<div style="font-family: Lucida Grande, Arial, sans-serif;>'+'<div><b>'+ name +'</b></div>'+'<div>'+ address +'</div>';					
	marker = new google.maps.Marker({						
		map: map,
		position: point,
		title: name+" "+address,
		buborek: contentString 
	});										
	google.maps.event.addListener(marker, 'click', function(){
		infowindow.setContent(this.buborek); 
		infowindow.open(map,this); 
	});															
	marker.setMap(map); 				
}

Solution 4 - Javascript

a tad late, but I managed to have only one infowindow open by maken infowindow a global variable.

var infowindow = new google.maps.InfoWindow({});

then inside the listner

infowindow.close();
infowindow = new google.maps.InfoWindow({	
	content: '<h1>'+arrondissement+'</h1>'+ gemeentesFiltered							
});
		 			
infowindow.open(map, this);

Solution 5 - Javascript

Declare a globar var selectedInfoWindow; and use it to hold the opened info window:

var infoWindow = new google.maps.InfoWindow({
    content: content
});

// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
    //Check if there some info window selected and if is opened then close it
    if (selectedInfoWindow != null && selectedInfoWindow.getMap() != null) {
        selectedInfoWindow.close();
        //If the clicked window is the selected window, deselect it and return
        if (selectedInfoWindow == infoWindow) {
            selectedInfoWindow = null;
            return;
        }
    }
    //If arrive here, that mean you should open the new info window 
    //because is different from the selected
    selectedInfoWindow = infoWindow;
    selectedInfoWindow.open(map, marker);
});

Solution 6 - Javascript

You need to keep track of your previous http://code.google.com/apis/maps/documentation/v3/reference.html#InfoWindow">InfoWindow</a> object and call the close method on it when you handle the click event on a new marker.

N.B It is not necessary to call close on the shared info window object, calling open with a different marker will automatically close the original. See Daniel's answer for details.

Solution 7 - Javascript

Basically you want one function that keeps reference to one new InfoBox() => delegate the onclick event. While creating your markers (in a loop) use bindInfoBox(xhr, map, marker);

// @param(project): xhr : data for infoBox template
// @param(map): object : google.maps.map
// @param(marker): object : google.maps.marker
bindInfoBox: (function () {
    var options = $.extend({}, cfg.infoBoxOptions, { pixelOffset: new google.maps.Size(-450, -30) }),
        infoBox = new window.InfoBox(options);

    return function (project, map, marker) {
        var tpl = renderTemplate(project, cfg.infoBoxTpl); // similar to Mustache, Handlebars

        google.maps.event.addListener(marker, 'click', function () {
            infoBox.setContent(tpl);
            infoBox.open(map, marker);
        });
    };
}())

var infoBox is assigned asynchronously and kept in memory. Every time you call bindInfoBox() the return function will be called instead. Also handy to pass the infoBoxOptions only once!

In my example I've had to add an extra param to the map as my initialization is delayed by tab events.

InfoBoxOptions

Solution 8 - Javascript

Here is a solution that doesn't need to create only one infoWindow to reuse it. You can continue creating many infoWindows, the only thing you need is to build a closeAllInfoWindows function, and call it before open a new infowindow. So, keeping your code, you just need to:

  1. Create a global array to store all the infoWindows

     var infoWindows = [];
    
  2. Store each new infoWindow in the array, just after the infoWindow = new...

     infoWindows.push(infoWindow);
    
  3. Create the closeAllInfoWindows function

     function closeAllInfoWindows() {
         for (var i=0;i<infoWindows.length;i++) {
             infoWindows[i].close();
         }
     }
    
  4. In your code, call to closeAllInfoWindows() just before open the infoWindow.

Regards,

Solution 9 - Javascript

One smart easy way to do this with jQuery is the following :

            google.maps.event.addListener(marker, 'click', function (e) {
                jQuery(".gm-ui-hover-effect").click();
                marker.info.open(map, this);
            });

It will click on all the closing buttons amongst your tooltips.

Solution 10 - Javascript

My approach allows you to toggle the infoWindow as well.

Global space

var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(contentString);

var lastInfoWindow;

Local space

marker.addListener("click", (e) => {
  if (lastInfoWindow === e.domEvent.srcElement) {
    infoWindow.close();
    lastInfoWindow = null;
  } else {
    infoWindow.open({
      anchor: marker,
      map,
      shouldFocus: false,
    });
    lastInfoWindow = e.domEvent.srcElement;
  }
});

Solution 11 - Javascript

Solved it this way:

function window(content){
    google.maps.event.addListener(marker,'click', (function(){
        infowindow.close();
        infowindow = new google.maps.InfoWindow({
            content: content
        });
        infowindow.open(map, this);
    }))
}
window(contentHtml);

Solution 12 - Javascript

Google Maps allows you to only have one info window open. So if you open a new window, then the other one closes automatically.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoView Question on Stackoverflow
Solution 1 - JavascriptDaniel VassalloView Answer on Stackoverflow
Solution 2 - JavascriptskarEView Answer on Stackoverflow
Solution 3 - JavascriptFerenc TakacsView Answer on Stackoverflow
Solution 4 - Javascriptuser2827958View Answer on Stackoverflow
Solution 5 - JavascriptIgniteCodersView Answer on Stackoverflow
Solution 6 - JavascriptRedBlueThingView Answer on Stackoverflow
Solution 7 - JavascriptTim VermaelenView Answer on Stackoverflow
Solution 8 - JavascriptJortxView Answer on Stackoverflow
Solution 9 - JavascriptHugo TrialView Answer on Stackoverflow
Solution 10 - JavascriptJens TörnellView Answer on Stackoverflow
Solution 11 - JavascriptBilal BoulaichView Answer on Stackoverflow
Solution 12 - JavascriptKimmo PuputtiView Answer on Stackoverflow