clara.vrx.palo-alto.ca.us
Articles | Design | EDITOR| Works | Bespoke web
Net files | Fonts | Ips | MAPS| Hints
INFOWINDOW
Open/Close Infowindow on Marker Click
Open/Close Infowindow on Marker Click

How to close and open InfoWindows on marker click using Google Maps JS API

When you click on a marker in Google Maps, it opens an infowindow. To close the infowindow, you must click on the "x" int he top right corner.

We find it a little too much work to move our mouse from the marker to the "x" button, especially if our infowindows are larger or different sizes.

To make it a faster experience for the user, we want to open and close infowindows by clicking on the map marker, while not needing to move our mouse to do it.

In the Android API the function hideInfoWindow() and showInfoWindow() close and open the infowindow, but in the JS API the same function does not exist, so we have written one.
We build a read state machine to determine if the window is open already or not, compare if marker clicked matches infowindow clicked by comparing Lat Lng coordinates, and then open/close.

marker.addListener('click', function() {

//start myfunction
function isInfoWindowOpen(infowindow){
var map = infowindow.getMap();
return (map !== null && typeof map !== "undefined");
}
var x = marker.getPosition();
var y = infowindow.getPosition();

// is address of clicked marker same as marker with infowindow open?
if ((x==y) && (isInfoWindowOpen(infowindow)==true)){
// Debugging: alert("true " + isInfoWindowOpen(infowindow));
infowindow.close();
return;
}
if ((x==y) && (isInfoWindowOpen(infowindow)==false)){
// Debugging: alert("false " + isInfoWindowOpen(infowindow));
infowindow.setContent(beach[4] + beach[0]); //replace beach[] with your own window content
infowindow.open(map, marker);
}
else if (x !== y){
// Debugging: alert(marker.getPosition()); alert(infowindow.getPosition());
infowindow.setContent(beach[4] + beach[0]); //replace beach[] with your own window content
infowindow.open(map, marker);
}
//end myfunction
});//end marker.addListener

Remember me, buy my shirts!
pop art
MBZ