Search code examples
javascriptgoogle-mapsextjs3

click and closeclick event on google maps


I want to open two infowindows on the same marker. On 'click' event first infowindow should close (which I am showing already on map) and open the second infowindow. On closing the second infowindow, I'd like to open the first window.

Here is my code:

var infowindow = new google.maps.InfoWindow({
            content: content,
            marker:marker,
            maxWidth: 300,
            image:image,
            id:vehicleNo
        });         
var openinfowindow = new google.maps.InfoWindow({
            content: contentone,
            marker:marker,
            maxWidth: 300,
            image:image,
            id:vehicleNo
        }); 
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){         
                return function() {                             
                    openinfowindow.close();                 
                    infowindow.setContent(content);
                    infowindow.open(map,marker);
            };              
        })(marker,content,infowindow)); 

    google.maps.event.addListener(infowindow,'closeclick',function(){
            openinfowindow.setContent(contentone);
            openinfowindow.open(map,marker);                                
    });

Solution

  • As the only difference between the infowindows is the desired content, you may use a single infowindow and simply toggle the content:

        var infowindow = new google.maps.InfoWindow({
            contents:[content,contentOne],
            marker:marker,
            maxWidth: 300,
            image:image,
            id:vehicleNo
        });         
    
        google.maps.event.addListener(marker,'click', (function(marker,
                                                                contents,
                                                                infowindow){         
          return function() {                                       
                    infowindow.contents=[contents[0],contents[1]];
                    infowindow.setContent(contents[0]);
                    infowindow.open(map,marker);
          };              
        })(marker,infowindow.contents,infowindow)); 
    
        google.maps.event.addListener(infowindow,'closeclick',function(){
            var that=this;
            that.contents.reverse();
            that.setContent(this.contents[0]);
            setTimeout(function(){
              that.open(map,marker);},
              100);                                
        });
    

    http://jsfiddle.net/doktormolle/affgpsvt/