我一直在玩Google Maps JavaScript API v3并试图让它显示基于多维数组的图标。在for循环中使用多维数组设置google.maps.Marker图标
一切都很好,直到我尝试从for循环定义相对于'i'的图标时,我想我正在犯一个简单的错误。
下面显示的代码给出了错误:Uncaught TypeError: Cannot read property '2' of undefined
function initialize() {
var map;
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(53.382971,-1.4702737),
mapTypeId: 'roadmap',
panControl: false,
streetViewControl: false,
mapTypeControl: false,
zoomControl: false
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = [
["S1 4EJ", "Available", "/img/green-marker.png"],
["S1 4QW", "Available", "/img/green-marker.png"],
["S1 2HE", "Let Agreed", "/img/red-marker.png"]
];
for (var i = 0; i < addresses.length; i++) {
console.log(i);
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[i][0]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
console.log(i);
new google.maps.Marker({
position: latlng,
map: map,
icon: {
url: addresses[i][2],
size: new google.maps.Size(50, 50),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(25, 50)
}
});
});
}
};
google.maps.event.addDomListener(window, "load", initialize);
第二console.log(addresses[i][2]);
的$.getJSON
成功函数内所有输出为 '3'。
移动addresses[i][2]
外$.getJSON
功能,但仍里面的for循环输出它们都作为“我”的最后一个叫迭代,例如:
...
for (var i = 0; i < addresses.length; i++) {
console.log(i);
var image = addresses[i][2];
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[i][0]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
console.log(i);
new google.maps.Marker({
position: latlng,
map: map,
icon: {
url: image,
size: new google.maps.Size(50, 50),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(25, 50)
}
});
});
}
...
我要对这个错误的方式?
'$ .ajax'(或'$ .getJSON'等)是异步函数。这意味着您的for循环很可能会在您从任何ajax调用返回之前完成。 – MrUpsidown 2015-04-02 12:12:25