Javascript-从嵌套函数返回值

问题描述

我正在尝试通过lat和long值对地址进行反向地理编码,并显示在Bootstrap模态中,因此我想使用ReverseGeocode的结果更新变量“ startAddress 功能,但我一直无法。

这是模式功能

$(document).on("click",".modal-editRoute",function () {
    var getCoord = $(this).attr("data");
    var splitCoord = getCoord.split(",");
    var startAddress = getReverseGeocodingData(splitCoord[0],splitCoord[1]);
    console.log("1: "+ startAddress); // This is undefined
    $(".modal-body #startRoute").val(startAddress);
    $(".modal-body #endRoute").val('coming soon');
});

这是 getReverseGeocodingData 函数

function getReverseGeocodingData(lat,lng) {
    var latlng = new google.maps.LatLng(lat,lng);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'latLng': latlng },function (results,status) {
        if (status !== google.maps.GeocoderStatus.OK) {
            alert(status);
        }
        if (status == google.maps.GeocoderStatus.OK) {
            var result = (results[0].formatted_address);
        }
        console.log("2: "+result);
        return result;
    });
}

这是它在控制台日志显示的方式:

Printscreen

解决方法

您可以使用promises

function getReverseGeocodingData(lat,lng) {
    var latlng = new google.maps.LatLng(lat,lng);
    var geocoder = new google.maps.Geocoder();
    return new Promise((resolve,reject) => {
        geocoder.geocode({ 'latLng': latlng },function (results,status) {
            if (status !== google.maps.GeocoderStatus.OK) {
                alert(status);
            }
            if (status == google.maps.GeocoderStatus.OK) {
                var result = (results[0].formatted_address);
                startAddress = result;
            }
            console.log("2: "+startAddress); // This has the proper value
            resolve(startAddress);
        });
    });
}

$(document).on("click",".modal-editRoute",function () {
    var getCoord = $(this).attr("data");
    var splitCoord = getCoord.split(",");
    getReverseGeocodingData(splitCoord[0],splitCoord[1])
      .then((startAddress) => {
          console.log("1: "+ startAddress); // This is empty
          $(".modal-body #startRoute").val(startAddress);
          $(".modal-body #endRoute").val('coming soon');
      });
});

要了解有关承诺的更多信息,请阅读以下文章:Promise

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...