相关疑难解决方法(0)

如何从Google Maps JavaScript地理编码器回调中返回变量?

我正在使用谷歌地图API,每当我从codeLatLng函数返回变量到初始化函数时,它声称未定义.如果我从codeLatLng打印变量,它显示正常.

  var geocoder;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var addr = codeLatLng();
    document.write(addr);

  }

  function codeLatLng() {
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
                return results[1].formatted_address;
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }
Run Code Online (Sandbox Code Playgroud)

打印出undefined

如果我做:

  var geocoder;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var …
Run Code Online (Sandbox Code Playgroud)

javascript google-maps asynchronous

28
推荐指数
2
解决办法
4万
查看次数

从Javascript中的嵌套函数返回值

考虑这段代码(缩短)

function getSecret() {
    db.transaction(
        function (transaction) {
            transaction.executeSql(
                'SELECT * FROM table LIMIT 1;',
                null,
                function(transaction, result) {
                    var row = result.rows.item(0);
                    var secret = row.secret;
                    return secret;
                }, errorHandler
            );
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

如何将secret的值返回给main函数?我已经从Javascript中的嵌套函数中读取了这个答案的返回值

并试过这个

function getSecret() {
    db.transaction(
        function doSql(transaction) {
            transaction.executeSql(
                'SELECT * FROM table LIMIT 1;',
                null,
                function(transaction, result) {
                    var row = result.rows.item(0);
                    var secret = row.secret;
                    return secret;
                }, errorHandler
            );
        }
    )
    return doSql;
}
Run Code Online (Sandbox Code Playgroud)

但是这没用.

谢谢!

javascript

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

javascript ×2

asynchronous ×1

google-maps ×1