Creating markers with info windows using Google Maps Javascript API v3

Not too much has changed from V2 to V3, but one major frustration was when using the 'click' event on a marker to open an info window, it didn't close when clicking another marker like it did on V2, as such you could potentially have a screen filled with lots of info windows.

This code could most probably be done a lot better, but my Javascript is lacking to say the least:

  1. var locations = new Array(),
  2. info = new Array(),
  3. content = new Array(),
  4. curr_infw; // We create a variable where we can store the most recently opened info window
  5.  
  6. // Loop through an array to add the data to our arrays
  7. // locations.push(new google.maps.LatLng(item.geo.coordinates[0],item.geo.coordinates[1]));
  8. // title.push(item.title);
  9. // content.push(item.content);
  10.  
  11. function initialize() {
  12. var latlng = new google.maps.LatLng(55.033983,-4.01001);
  13. var myOptions = {
  14. zoom: 6,
  15. center: latlng,
  16. mapTypeId: google.maps.MapTypeId.ROADMAP
  17. };
  18. var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  19. for(i=0;i<locations.length;i++) {
  20. markers[i] = createMarker(locations[i], tweet_info[i], tweet_content[i], map);
  21. }
  22. }
  23.  
  24. function createMarker(point, title, content, map) {
  25. var marker = new google.maps.Marker({
  26. position: point,
  27. map: map,
  28. title: title
  29. });
  30. var infowindow = new google.maps.InfoWindow({
  31. content: content
  32. });
  33. google.maps.event.addListener(marker, 'click', function() {
  34. if(curr_infw) { curr_infw.close();} // We check to see if there is an info window stored in curr_infw, if there is, we use .close() to hide the window
  35. curr_infw = infowindow; // Now we put our new info window in to the curr_infw variable
  36. infowindow.open(map, marker); // Now we open the window
  37. });
  38. return marker;
  39. };