I tried to add multiple markers and infowindow to a google map using javascript. Below is the code:
This works:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [ '1961 East Mall Vancouver BC',
'2366 Main Mall Vancouver BC', '2053 Main Mall, Vancouver, BC ' ];
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 14,
center : new google.maps.LatLng(49.26526, -123.250541),
mapTypeId : google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker;
var i;
$(document).ready(function() {
initialize();
});
function initialize(){
setMarkers(map,locations);
}
function setMarkers(map, address) {
for ( var i = 0; i < address.length; i++) {
setMarker(map, address[i])
}
}
function setMarker(map, address) {
geocoder = new google.maps.Geocoder();
geocoder
.geocode(
{
'address' : address
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker(
{
position : results[0].geometry.location,
map : map
});
google.maps.event.addListener(marker,
"click", function() {
infowindow.setContent(address);
infowindow.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: "
+ status);
}
});
}
</script>
</body>
</html>
Thanks to Google Map multiple infowindow does not work
The geocoder is asynchronous, you need to add the infowindow inside the geocoder call back. Where you have it currently it runs before any of the markers are defined. I would think you would get a javascript error.