【问题标题】:Why Google place AutocompleteService callback not getting executed?为什么 Google 不执行 AutocompleteService 回调?
【发布时间】:2016-12-28 15:10:15
【问题描述】:

我有以下AutocompleteService() 的代码:

var strAddr = '';
if (address.value != "") {
    var service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions({ input: address.value }, function (predictions, status) {
        console.log('1');
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            console.log('Original Response: ' + predictions[0].structured_formatting.secondary_text);
            strAddr = predictions[0].structured_formatting.secondary_text;
        }
    });
    console.log('strAddr: ' + strAddr);
    console.log('2');
}

console.log('3');

我在控制台中收到如下响应:

  • strAddr:
  • 2
  • 3
  • 1
  • 原始响应://在此处获取匹配的地址

但应该是:

  • 1
  • 原始响应://此处匹配地址>
  • strAddr: //这里匹配的地址
  • 2
  • 3

为什么回调没有按预期顺序执行?

【问题讨论】:

    标签: google-maps google-maps-api-3 google-places-api


    【解决方案1】:

    getQueryPredictions 函数是异步的(它可能通过 AJAX 发生)。所以你不能保证它会在它之后的代码之前完成。

    例如调用 getQueryPredictions 可能需要 0.5 秒。因此,当这发生时,这两行将能够立即执行:

    console.log('strAddr: ' + strAddr);
    console.log('2');
    

    您不能依赖 strAddr 在等待 getQueryPredictions 响应的回调函数之外发生的任何代码中可用。

    【讨论】:

      【解决方案2】:

      不保证你会得到这个

      • 1
      • 原始响应://此处匹配地址>
      • strAddr: //这里匹配的地址
      • 2
      • 3

      因为这( new google.maps.places.AutocompleteService(); )是异步调用,您的回调可以按任何顺序调用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        • 1970-01-01
        • 2021-05-22
        • 2017-10-09
        • 2021-01-06
        相关资源
        最近更新 更多