Posts Tagged ‘InfoWindow’

Google Maps API V3 – Multiple InfoWindows

Monday, January 31st, 2011

Multiple InfoWindows definitely work a bit different with the V3 API.

While porting an outdated script to the V3 API, I’ve soon found out, that …
one can attach HTML as the marker’s content and retrieve it from there again.

The following JavaScript example explains the method which I developed in detail.
Another advance: there’s always at most only one InfoWindow open at a time,
e.g. the user would close one info-window when opening another (which is another quite common issue with the V3 API). I’d also suggest to bind the map on-click event to close it, which is ordinary the expected behavior.

This array should to be defined globally (outside any function);
Hmm, in this example even a single var would be enough to hold the reference:

infos = [];

This code creates the markers, info-windows and the event listeners (should run inside a loop):

var title = 'This is the text for the markers tooltip on mouseover.';
var html = '<div class="info">This HTML will be attached to the marker.</div>';

var marker = new google.maps.Marker({
   title:title,
   content:html,
   map:map,
   draggable:false,
   position:point
});

google.maps.event.addListener(marker, 'click', function() {

   /* close the previous info-window */
   closeInfos();

   /* the marker's content gets attached to the info-window: */
   var info = new google.maps.InfoWindow({content: this.content});

   /* trigger the infobox's open function */
   info.open(map,this);

   /* keep the handle, in order to close it on next click event */
   infos[0]=info;

});

/* ... or one may optionally bind the map on-click event as well */
google.maps.event.addListener(map, 'click', function() {
   closeInfos();
});

This utility function closes any previously opened InfoWindow
and removes the reference between the InfoWindow and it’s marker:

function closeInfos(){

   if(infos.length > 0){

      /* detach the info-window from the marker ... undocumented in the API docs */
      infos[0].set("marker", null);

      /* and close it */
      infos[0].close();

      /* blank the array */
      infos.length = 0;
   }
}

Since the code is always storing a handle to the last opened info-window
at the same index position – the last opened info-window can be closed instantly!!

Like this it is much quicker – compared to the method of looping an array of info-windows,
which turned out to be way too slow … especially when handling large amounts of info-windows.