Posts Tagged ‘multiple InfoWindows’

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: