Google Maps : open InfoWindow on mouseover, close & reopen on click

Tsokoa picture Tsokoa · Oct 26, 2012 · Viewed 16.7k times · Source

I've a page with markers with InfoWindows that I opened on Click. I decided to rather open the InfoWindows on MouseOver which is working.

But I find that having to move the mouse to the cross of the InfoWindow to close it is a bit demanding for these lazy visitors of the internet. So I added a Close event on Click of the Marker which is also working.

What I can't figure out to work is to be able to re-open the InfoWindow on Marker Click instead of having to mouseout in order to be able to re-mouseover on the marker.

My code :

google.maps.event.addListener(CalMarker, 'mouseover', function() {
    infowindow.setContent(contentStringCal);
    infowindow.open(map,CalMarker);
});
google.maps.event.addListener(CalMarker, 'click', function() {
    infowindow.close(map,CalMarker);
});

Can anyone help me to reopen window by clicking on the marker ?

Thanks in advance

PS : can't manage to say "Hi" at the beggining of the post, that's weird.

Answer

Dr.Molle picture Dr.Molle · Oct 26, 2012

Try this:

google.maps.event.addListener(CalMarker, 'mouseover', function() {
    //open the infowindow when it's not open yet
    if(contentStringCal!=infowindow.getContent())
    {
      infowindow.setContent(contentStringCal);
      infowindow.open(map,CalMarker);
    }
});

google.maps.event.addListener(CalMarker, 'click', function() {
    //when the infowindow is open, close it an clear the contents
    if(contentStringCal==infowindow.getContent())
    {
      infowindow.close(map,CalMarker);
      infowindow.setContent('');
    }
    //otherwise trigger mouseover to open the infowindow
    else
    {
      google.maps.event.trigger(CalMarker, 'mouseover');
    }
});

//clear the contents of the infwindow on closeclick
google.maps.event.addListener(infowindow, 'closeclick', function() {
      infowindow.setContent('');
});

Demo: http://jsfiddle.net/doktormolle/JXqLa/