There is something wrong with my for loop or array but I don't know where.
Uncaught TypeError: Cannot read property '0' of undefined
How does the loop should be to work properly?
http://jsfiddle.net/hugpablo/uLza5va6/1/
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple addresses
var addresses = [
["First Place", "Colonia providencia, Guadalajara, Jalisco, México"],
["Second Place", "Colonia Ayuntamiento, Guadalajara, Jalisco, Mexico"],
["Third Place", "Colonia Moderna, Guadalajara, Jalisco, Mexico"],
["Fourth Place", "Colonia Santa Edwiges, Jalisco, Mexico"]
];
var geocoder = new google.maps.Geocoder();
// Loop through our array of addresses & place each one on the map
for(var i = 0; i < addresses.length; i++ ) {
geocoder.geocode( { "address": addresses[i][1] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
var location = results[0].geometry.location;
var lat = location.lat();
var lng = location.lng();
var position = new google.maps.LatLng(lat, lng);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: addresses[i][0],
icon: icon
});
};
});
// Automatically center the map fitting all addresses on the screen
map.fitBounds(bounds);
};
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(5);
google.maps.event.removeListener(boundsListener);
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…