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:
var locations = new Array(), info = new Array(), content = new Array(), curr_infw; // We create a variable where we can store the most recently opened info window // Loop through an array to add the data to our arrays // locations.push(new google.maps.LatLng(item.geo.coordinates[0],item.geo.coordinates[1])); // title.push(item.title); // content.push(item.content); function initialize() { var latlng = new google.maps.LatLng(55.033983,-4.01001); var myOptions = { zoom: 6, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); for(i=0;i<locations.length;i++) { markers[i] = createMarker(locations[i], tweet_info[i], tweet_content[i], map); } } function createMarker(point, title, content, map) { var marker = new google.maps.Marker({ position: point, map: map, title: title }); var infowindow = new google.maps.InfoWindow({ content: content }); google.maps.event.addListener(marker, 'click', function() { 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 curr_infw = infowindow; // Now we put our new info window in to the curr_infw variable infowindow.open(map, marker); // Now we open the window }); return marker; };