javascript - 为什么这个变量未定义或未返回?

标签 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, 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);
});

在您的代码中,当您返回时,您实际上是从 function(results, status){..} 函数返回,而不是 stringToLatLng 函数,正如注释中所述,它是一个异步调用,因此您必须使用回调.

关于javascript - 为什么这个变量未定义或未返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12467690/

相关文章:

android - 如何通过公交获得覆盖距离

javascript - 如何将表单信息传递到单独页面上的谷歌地图中?

javascript - 我如何获得具有当前索引和最大项目的 n-2 和 n+3 元素?

javascript - 一个接一个地淡入div

javascript - 从 TinyMCE 的对话框中获取输入字段值

javascript 在与数字与非数字进行比较时返回 NaN

javascript - 如何在云函数中使用 indexOn 从实时数据库中检索数据

javascript - 如何使用 gmap3 清除特定标记

google-maps - 自定义 html 为谷歌地图制作标记

google-maps - 谷歌地图具有多个字符的标记标签