gpt4 book ai didi

javascript - 通过 jQuery UI 自动完成功能包装 Google Places 自动完成服务

转载 作者:行者123 更新时间:2023-12-02 07:38:52 24 4
gpt4 key购买 nike

我正在尝试使用 jQuery UI 自动完成功能来包装 Google 自动完成服务(因为我只想以 Google API 无法实现的方式限制 Google 返回的某些结果)。

假设我有这段代码:

$("#address").autocomplete({
source: function(request, response){
autoCompleteService = new google.maps.places.AutocompleteService();
autoCompleteService.getQueryPredictions({input: request.term }, autocompleteCallback);
//I should somewhere call the "response" object with desired suggestions as arguments
},
minLength: 5,
});

问题是 jQuery UI Autocomplete 强制我调用“响应”对象(它实际上是一个函数),其中包含我想作为参数显示给用户的建议。

但是,另一方面,Google API 强制我定义一个回调函数(在我的例子中为“autocompleteCallback”),它在完成后将请求的建议作为参数提供给该回调函数。

当然,我不能在'autocompleteCallback'函数中调用'response'对象,我也不能在这一行之后调用response对象:

autoCompleteService.getQueryPredictions({input: request.term }, autocompleteCallback);

因为 JS 是异步的,我不能确定我得到了一些东西,比方说:我使用的一个全局变量来传递结果。

解决方案是什么?是否有针对此类问题的著名 JS 设计模式?

最佳答案

先生,您是将这两个框架结合起来的天才!所以我将分享我的解决方案:

$("#search").autocomplete({
source: function (request, response) {
autoCompleteService.getQueryPredictions({ input: request.term }, function (predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
response($.map(predictions, function (prediction, i) {
return {
label: prediction.description,
value: prediction.description
}
}));
});
},
select: function (event, ui) {
var value = ui.item.value;
searchMap(value);
}
});

当然,我有一个实际函数可以执行正确的地点查找 (searchMap()),它接受一个术语。为了让 jQuery UI 自动完成具有适当的 autocompleteCallbackresponse 处理程序,唯一现实的方法是保持回调实现内联。如果您想在多个地方执行此操作,那就太糟糕了,但我还没有想到更好的方法。然而……

关于javascript - 通过 jQuery UI 自动完成功能包装 Google Places 自动完成服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com