我很难将变量传递给Google Maps API
我正在尝试根据以下数组中的内容创建带有自定义标题的标记
var addresses = [{"atitle":"ROUTE 114 LIQUORS","street":"175 ANDOVER STREET+01960 "},{"atitle":"DOWNTOWN WINE & SPIRITS","street":"225 ELM STREET (DAVIS SQU+02143 "},{"atitle":"WEGMANS-NORTHBOROUGH","street":"9102 SHOPS WAY+01532 "},{"atitle":"POWERS LIQUORS","street":"23 WOOD STREET+01851 "}];
var x;
for ( x = 0; x < addresses.length; x++) {
var reTitle = addresses[x].atitle;
reTitle = reTitle.replace(/&#(\d+);/g, function (m, n) { return String.fromCharCode(n); });
alert(reTitle);//this works fine.
jQuery.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x].street+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var aTitle = reTitle;
new google.maps.Marker({
position: latlng,
map: map,
title: aTitle
});
});
}
标记很好。标题不会出现。
答案 0 :(得分:0)
JQuery.getJSON是异步的。循环完成后,x = addresses.length
(不是地址数组的有效条目)。此时所有回调函数都执行,地址[x] .title未定义。
这个问题通常通过函数关闭来解决。