Transistioning InfoWindows from Google Maps API v2 to v3

I have been making google map mashups since 2007. In that time I’ve seen the Google Maps API change for the better. I have a few projects that are using version 2 of the API. I knew Google was deprecating support for this older API and it was time to upgrade. Most of my maps contain many markers each with their own InfoWindow. The first change I noticed transitioning to v3 is that multiple InfoWindows can stay open at the same time. Using my old v2 code caused a problem. If someone clicked on a marker, I wanted the old InfoWindow to automatically close.

My mashups contain large sets of markers so I needed some way to cleanly make this happen. What I didn’t want to do was loop through every single marker (to close them all programmatically) each time a user clicked a new marker. I found some code that does just this. Take a look at CodeFx, here is their solution that I used.

 infos = [];

function closeInfos(){
   if(infos.length > 0){
      /* detach the info-window from the marker */
      infos[0].set("marker",null);
      /* and close it */
      infos[0].close();
      /* blank the array */
      infos.length = 0;
   }
}
var title = 'This is the text for the markers tooltip on mouseover.';
var html = '<div>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;
});

Leave a Reply

Your email address will not be published. Required fields are marked *