Google Maps: Auto close open InfoWindows?

JavascriptGoogle MapsGoogle Maps-Api-3

Javascript Problem Overview


On my site, I'm using Google Maps API v3 to place house markers on the map.

The InfoWindows stay open unless you explicitly click the close icon. Meaning, you can have 2+ InfoWindows open at a time if you hover over the map marker.

Question: How do I make it so that only the current active InfoWindow is open and all other InfoWindows are closed? Meaning, no more than 1 InfoWindow will be open at a time?

Javascript Solutions


Solution 1 - Javascript

There is a close() function for InfoWindows. Just keep track of the last opened window, and call the close function on it when a new window is created.

Solution 2 - Javascript

alternative solution for this with using many infowindows: save prev opened infowindow in a variable and then close it when new window opened

var prev_infowindow =false; 
...
base.attachInfo = function(marker, i){
	var infowindow = new google.maps.InfoWindow({
		content: 'yourmarkerinfocontent'
    });
	
	google.maps.event.addListener(marker, 'click', function(){
	    if( prev_infowindow ) {
           prev_infowindow.close();
        }
	    
        prev_infowindow = infowindow;
	    infowindow.open(base.map, marker);
    });
}

Solution 3 - Javascript

//assuming you have a map called 'map'
var infowindow = new google.maps.InfoWindow();

var latlng1 = new google.maps.LatLng(0,0);
var marker1 = new google.maps.Marker({position:latlng1, map:map});
google.maps.event.addListener(marker1, 'click',
    function(){
        infowindow.close();//hide the infowindow
        infowindow.setContent('Marker #1');//update the content for this marker
        infowindow.open(map, marker1);//"move" the info window to the clicked marker and open it
    }
);
var latlng2 = new google.maps.LatLng(10,10);
var marker2 = new google.maps.Marker({position:latlng2, map:map});
google.maps.event.addListener(marker2, 'click',
    function(){
        infowindow.close();//hide the infowindow
        infowindow.setContent('Marker #2');//update the content for this marker
        infowindow.open(map, marker2);//"move" the info window to the clicked marker and open it
    }
);

This will "move" the info window around to each clicked marker, in effect closing itself, then reopening (and panning to fit the viewport) in its new location. It changes its contents before opening to give the desired effect. Works for n markers.

Solution 4 - Javascript

My solution.

var map;
var infowindow = new google.maps.InfoWindow();
...
function createMarker(...) {
var marker = new google.maps.Marker({
     ...,
     descrip: infowindowHtmlContent  
});
google.maps.event.addListener(marker, 'click', function() {
    infowindow.setOptions({
		content: this.descrip,
		maxWidth:300
	});
    infowindow.open(map, marker);
});

Solution 5 - Javascript

> Declare a variable for active window

var activeInfoWindow; 

> and bind this code in marker listener

 marker.addListener('click', function () {
    if (activeInfoWindow) { activeInfoWindow.close();}
    infowindow.open(map, marker);
    activeInfoWindow = infowindow;
});

Solution 6 - Javascript

From this link http://www.svennerberg.com/2009/09/google-maps-api-3-infowindows/:

> Teo: The easiest way to do this is to > just have one instance of the > InfoWindow object that you reuse over > and over again. That way when you > click a new marker the infoWindow is > “moved” from where it’s currently at, > to point at the new marker. > > Use its setContent method to load it > with the correct content.

Solution 7 - Javascript

There is a easier way besides using the close() function. if you create a variable with the InfoWindow property it closes automatically when you open another.

var info_window;
var map;
var chicago = new google.maps.LatLng(33.84659, -84.35686);

function initialize() {
    var mapOptions = {
        center: chicago,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    
    info_window = new google.maps.InfoWindow({
        content: 'loading'
    )};
    
createLocationOnMap('Location Name 1', new google.maps.LatLng(33.84659, -84.35686), '<p><strong>Location Name 1</strong><br/>Address 1</p>');
createLocationOnMap('Location Name 2', new google.maps.LatLng(33.84625, -84.36212), '<p><strong>Location Name 1</strong><br/>Address 2</p>');

}

function createLocationOnMap(titulo, posicao, conteudo) {            
    var m = new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        title: titulo,
        position: posicao,
        html: conteudo
    });            

    google.maps.event.addListener(m, 'click', function () {                
        info_window.setContent(this.html);
        info_window.open(map, this);
    });
}

Solution 8 - Javascript

var map;
var infowindow;
...
function createMarker(...) {
    var marker = new google.maps.Marker({...});
    google.maps.event.addListener(marker, 'click', function() {
        ...
        if (infowindow) {
            infowindow.close();
        };
        infowindow = new google.maps.InfoWindow({
            content: contentString,
            maxWidth: 300
        });
        infowindow.open(map, marker);
    }
...
function initialize() {
    ...
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    ...
    google.maps.event.addListener(map, 'click', function(event) {
        if (infowindow) {
            infowindow.close();
        };
        ...
    }
}

Solution 9 - Javascript

How about -

google.maps.event.addListener(yourMarker, 'mouseover', function () {
        yourInfoWindow.open(yourMap, yourMarker);
        
    });

google.maps.event.addListener(yourMarker, 'mouseout', function () {
        yourInfoWindow.open(yourMap, yourMarker);
        
    });

Then you can just hover over it and it will close itself.

Solution 10 - Javascript

I stored a variable at the top to keep track of which info window is currently open, see below.

var currentInfoWin = null;
google.maps.event.addListener(markers[counter], 'click', function() {      
    if (currentInfoWin !== null) {
        currentInfoWin.close(map, this); 
    }
    this.infoWin.open(map, this); 
    currentInfoWin = this.infoWin;  
}); 

Solution 11 - Javascript

Here is what I used if you are using many markers in a for loop (Django here). You can set an index on each marker and set that index every time you open a window. Closing the previously saved index:

markers = Array();
infoWindows = Array();
var prev_infowindow =false;
{% for obj in objects %}
var contentString = 'your content'
var infowindow = new google.maps.InfoWindow({
            content: contentString,
          });
var marker = new google.maps.Marker({
               position: {lat: {{ obj.lat }}, lng: {{ obj.lon }}},
               map: map,
               title: '{{ obj.name }}',
               infoWindowIndex : {{ forloop.counter0 }}
          });
google.maps.event.addListener(marker, 'click',
            function(event)
            {
           if( prev_infowindow ) {
               infoWindows[prev_infowindow].close();
                }
                prev_infowindow = this.infoWindowIndex;
                infoWindows[this.infoWindowIndex].open(map, this);
            }
        );

        infoWindows.push(infowindow);
        markers.push(marker);

      {% endfor %}

Solution 12 - Javascript

var contentString = "Location: " + results[1].formatted_address;	
google.maps.event.addListener(marker,'click', (function(){ 
    infowindow.close();
    infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    infowindow.open(map, marker);
}));

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
QuestionTedView Question on Stackoverflow
Solution 1 - JavascriptChris BView Answer on Stackoverflow
Solution 2 - JavascriptmikeView Answer on Stackoverflow
Solution 3 - JavascriptJoel MellonView Answer on Stackoverflow
Solution 4 - JavascriptkaidojView Answer on Stackoverflow
Solution 5 - JavascriptHardeep SinghView Answer on Stackoverflow
Solution 6 - JavascriptKeith AdlerView Answer on Stackoverflow
Solution 7 - JavascriptMelloGView Answer on Stackoverflow
Solution 8 - JavascriptD KView Answer on Stackoverflow
Solution 9 - JavascriptNathanView Answer on Stackoverflow
Solution 10 - JavascriptP NelsonView Answer on Stackoverflow
Solution 11 - JavascriptJoshView Answer on Stackoverflow
Solution 12 - JavascriptSaiView Answer on Stackoverflow