我正在尝试创建一个函数,该函数利用Google Javascript V3的地理编码功能,并返回一个带有经度和纬度的数组。由于某些原因,没有使用函数填充返回数组。谢谢你的帮助!
代码:
function getCoords(address) {
var latLng = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng.push(results[0].geometry.location.lat());
latLng.push(results[0].geometry.location.lng());
return latLng;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var test_arr;
test_arr = getLatLng('New York');
alert(test_arr[0] + ',' + test_arr[1]) // I'm getting a test_arr is undefined here.
阅读关于在Javascript中使用回调函数的信息。这篇文章可能会有所帮助。
正如Jon所指出的,可以通过将回调函数传递到getCoords方法中来解决这个问题。这是一种等待谷歌回复的方式。您定义了一个函数,该函数将在地理编码完成时调用。您将调用所提供的函数,而不是返回数据,而是将数据作为参数。
类似这样的东西:
function getCoords(address, callback) {
var latLng = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng.push(results[0].geometry.location.lat());
latLng.push(results[0].geometry.location.lng());
callback(latLng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
getCoords('New York', function(latLng) {
var test_arr;
test_arr = latLng;
alert(test_arr[0] + ',' + test_arr[1])
// Continue the rest of your program's execution in here
});
@Matt Ball应该已经发布了答案。:)test_arr未定义的原因是,您在返回结果之前立即对其进行评估。
如果你做了setTimeout(这是不应该做的),你会注意到数组最终会有一些东西
setTimeout(function(){
alert(test_arr) // has stuff...
}, 5000);
相反,您可以将一个匿名函数作为回调传递给getCoords。一旦坐标可用,就会执行此函数。
function getCoords(address, callback) {
...
var lng = results[0].geometry.location.lng();
var lat = results[0].geometry.location.lat();
callback([lat, lng]);
...
}
getCoords("New York", function(coords) {
alert(coords); // works
});