Javascript 为什么该变量未定义或未返回?
我有以下代码:Javascript 为什么该变量未定义或未返回?,javascript,google-maps-api-3,Javascript,Google Maps Api 3,我有以下代码: /* * converts a string to geolocation and returns it */ function stringToLatLng(string){ if(typeof string == "string"){ geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': string}, function(results, st
/*
* converts a string to geolocation and returns it
*/
function stringToLatLng(string){
if(typeof string == "string"){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': string}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("LatLng: "+results[0].geometry.location);
return results[0].geometry.location;
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
}
LatLng将正确的位置打印到控制台上,但当我写下以下内容时:
var pos = stringToLatLng('New York');
console.log(pos);
我得到
未定义的返回。为什么呢?谢谢诸如此类的东西:
function stringToLatLng(strloc, callback){
if(typeof string == "string"){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': strloc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback.call({}, results[0].geometry.location);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
}
stringToLatLng('New York', function(pos){
console.log(pos);
});
在代码中,当您返回时,实际上是从函数(results,status){..}函数返回,而不是stringToLatLng函数,如注释中所述,它是一个异步调用,因此必须使用回调
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
参考:
因为.geocode
是异步的,为什么这意味着在这种情况下?我的意思是LatLng被正确地打印到控制台上。。。那我怎么修呢?我是说,我怎么能“等待”直到结果准备好?您不需要等待-将所有与结果一起工作的代码放入回调,就像您已经使用console.log
我尝试过上述代码段一样,它正在返回值,它会显示在警报中,但是,当我尝试将其分配给某个变量或在函数外部发出该警报时,它再次为null…任何帮助plz…我得到的都是一个is null错误,这将在这种情况下导致一些问题…可能是因为您试图在stringToLatLng('New York',function(pos){console.log(pos);}之外使用该变量); 方法,确保您在警报后直接使用它。