Google Maps with Multiple Markers and InfoWindow

Google Maps API provides Marker and InfoWindow to build interactive maps. This demo shows how to build a map with multiple markers with one infowindow.

In the HTML page, add a div holding the map.

<div id="map-canvas"></div>

In JavaScript, we first have a list of locations for markers, and then initialize a map with markers and one infowindow.

var LocationData = [
	[49.2812668, -123.1035942, "26 E Hastings St, Vancouver" ], 
	[49.2814064, -123.1025187, "71 E Hastings St, Vancouver" ], 
	[49.2812336, -123.1020622, "122 E Hastings St, Vancouver" ], 
	[49.2813564, -123.1012253, "138 E Hastings St, Vancouver" ], 
	[49.2811625, -123.0985032, "242 E Hastings St, Vancouver" ]
];

function initialize()
{
	var map = 
	    new google.maps.Map(document.getElementById('map-canvas'));
	var bounds = new google.maps.LatLngBounds();
	var infowindow = new google.maps.InfoWindow();
	
	for (var i in LocationData)
	{
		var p = LocationData[i];
		var latlng = new google.maps.LatLng(p[0], p[1]);
		bounds.extend(latlng);
		
		var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			title: p[2]
		});
	
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.setContent(this.title);
			infowindow.open(map, this);
		});
	}
	
	map.fitBounds(bounds);
}

google.maps.event.addDomListener(window, 'load', initialize);

Note that, the following code is wrong for adding listeners to markers. The variable used in the event-handler function will change as the loop goes. Using this, when the handler runs, it will refer to the right marker which trigers the event.

google.maps.event.addListener(marker, 'click', function() {
	infowindow.setContent(p[2]);
	infowindow.open(map, marker);
});

An alternative solution is to use closure to match handlers with the right markers.

google.maps.event.addListener(marker, 'click', (function(mm, tt) {
	return function() {
		infowindow.setContent(tt);
		infowindow.open(map, mm);
	}
})(marker, p[2]));

The drawback of this code is that, it creates many handlers (function objects), one for each maker. The previous code has only one handler, which works for all markers.

The following is the result.

View this demo in full screen.

Related Posts

Comments

comments