javascript - 将谷歌地图自动完成预测返回给调用它的方法

标签 javascript google-maps-api-3

我有一个 javascript 方法addressAutocomplete,每当输入字段发生更改时就会调用该方法。在其中,我调用谷歌地图方法来根据当前输入进行预测。

我的问题是我希望我的 addressAutocomplete 方法返回预测,但我找不到实现此目的的方法。最好的方法是什么?

我的代码(返回不起作用)

var addressAutocomplete = function(input) {
  var service = new google.maps.places.AutocompleteService();
  return service.getQueryPredictions({ input: input }, predictionsCallback);
};

function predictionsCallback(predictions, status) {
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    alert(status);
    return;
  }

  return predictions;
}

最佳答案

您当前得到未定义,对吗?问题是您试图从异步操作返回值,这是行不通的。在 getQueryPredictions 调用回调函数之前,您无法访问预测,并且您无法从回调函数返回值。 service.getQueryPredictions 不返回值,它只是在异步操作完成时调用回调函数。

如果没有更多上下文(例如调用或注册 addressAutocomplete 的位置),我不确定是否可以为您提供进一步帮助。您需要的是使用连续传递样式或可能使用 Promise。以下是您可能需要执行的操作的草图:

var addressAutocomplete = function(input) {
  var service = new google.maps.places.AutocompleteService();

  //you can't return this line because it's an async function
  service.getQueryPredictions({ input: input }, function (predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
      alert(status);
    }
    //again, we can't return a value here, but we can pass it to another function!
    // this is not exactly how you should do it, just an example
    // Only stringifying it here for example, since I don't know the shape of the predictions object
    $('.autocomplete-results').text(JSON.stringify(predictions));
  });
};

编辑:只需将文本添加到 DOM 中。在这里,我使用 jquery 获取想要更新的元素,然后将其文本设置为字符串化预测对象。我不知道预测是什么样的,但您可能想要定义一个辅助函数来解析和格式化文本,然后更新 DOM。

关于javascript - 将谷歌地图自动完成预测返回给调用它的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35924033/

相关文章:

javascript - 动态使用第一帧作为 HTML5 视频中的海报?

javascript - Google Maps JS api v3 延迟地一一删除标记

google-maps - 谷歌地图 V3 路线目的地标记编辑

google-maps - 我可以将 Google Street View API 用于我自己的图像吗?

javascript - 如何使用 BotKit 从 Slack API 获取用户列表?

javascript - onmouseover onmouseout 图像变化液体效果

javascript - 如何将 dropzone.js 框放入 html 文件中的现有表单中?

JavaScript DOM 编码 - 'undefined' 错误

javascript - Google map 关闭街景 (JQuery)

javascript - 地理编码限制问题