我有一个 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/