对不起,我知道这已被问过一千次了,但我已经阅读了回复,我仍然没有得到它。我是Javascript的新手(我昨天开始,实际上),我有以下问题:
我有一个异步函数,我需要返回的值,但当然是未定义的。我读过关于回调的内容,但我不确定它们是如何工作的。
该功能如下:
function getLatLong(address){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var returnedLatLng = [];
returnedLatLng["lat"] = results[0].geometry.location.lat();
returnedLatLng["lgn"] = results[0].geometry.location.lng();
locationTarget = new google.maps.LatLng(returnedLatLng.lat,returnedLatLng.lgn);
alert(locationTarget);
return locationTarget;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
我从initialize()函数调用此函数,我这样做:
var location = getLatLong(address);
好吧,我的问题是回调如何帮助我?如果可能的话......我应该使用什么代码?
非常感谢! (这是我在这里的第一个问题!)
答案 0 :(得分:0)
最基本的解决方案是全局定义您的位置并响应您已有的回调:
var location;
function getLatLong(address){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var returnedLatLng = [];
returnedLatLng["lat"] = results[0].geometry.location.lat();
returnedLatLng["lgn"] = results[0].geometry.location.lng();
locationTarget = new google.maps.LatLng(returnedLatLng.lat,returnedLatLng.lgn);
alert(locationTarget);
location = locationTarget;
// Additional logic you are using the location for
// After this point your location is defined.
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
getLatLong(address)
所以基本上你的逻辑需要不是基于对返回位置的方法的调用,而是基于调用geocode
函数回调之后发生的事情。
答案 1 :(得分:0)
试试这个:
var locationCallback = function(location){
// your fancy code here
};
function getLatLong(address){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var returnedLatLng = [];
returnedLatLng["lat"] = results[0].geometry.location.lat();
returnedLatLng["lgn"] = results[0].geometry.location.lng();
locationTarget = new google.maps.LatLng(returnedLatLng.lat,returnedLatLng.lgn);
alert(locationTarget);
//this is your callback
locationCallback(locationTarget);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
getLatLong(address)