使用 Google 的 Javascript API 的未定义问题
Undefined Issue using Google's Javascript API
我在使用 google 地理位置 api 时一直被一个问题困扰了好几天。这就是我一直在尝试的 -
function codeAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address": address}, function(results, status) {
if (status == "OK") {
return results[0].geometry.location;
} else {
return null;
}
});
}
function generateJSON(origin, destination) {
var origin_loc = codeAddress(origin);
var dest_loc = codeAddress(destination);
....
}
"origin_loc" 变量返回时未分配,我无法通过调试器找出原因。当我将 results[0] 记录到控制台时,它可以正常返回该对象。
有人知道为什么会这样吗?
谢谢
这最终对我有用 -
function codeAddresses(addresses, callback) {
var coords = [];
for(var i = 0; i < addresses.length; i++) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address':addresses[i]}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
coords.push(results[0].geometry.location);
if(coords.length == addresses.length) {
callback(coords);
}
}
else {
throw('No results found: ' + status);
}
});
}
}
function generateJSON(origin, destination) {
var addresses = [origin, destination];
codeAddresses(addresses, function(coords) {
var json = { ..... }
....
});
}
感谢@yuriy636 的帮助!
我在使用 google 地理位置 api 时一直被一个问题困扰了好几天。这就是我一直在尝试的 -
function codeAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address": address}, function(results, status) {
if (status == "OK") {
return results[0].geometry.location;
} else {
return null;
}
});
}
function generateJSON(origin, destination) {
var origin_loc = codeAddress(origin);
var dest_loc = codeAddress(destination);
....
}
"origin_loc" 变量返回时未分配,我无法通过调试器找出原因。当我将 results[0] 记录到控制台时,它可以正常返回该对象。
有人知道为什么会这样吗?
谢谢
这最终对我有用 -
function codeAddresses(addresses, callback) {
var coords = [];
for(var i = 0; i < addresses.length; i++) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address':addresses[i]}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
coords.push(results[0].geometry.location);
if(coords.length == addresses.length) {
callback(coords);
}
}
else {
throw('No results found: ' + status);
}
});
}
}
function generateJSON(origin, destination) {
var addresses = [origin, destination];
codeAddresses(addresses, function(coords) {
var json = { ..... }
....
});
}
感谢@yuriy636 的帮助!