gpt4 book ai didi

javascript - 从 google places 返回多种类型 autocompleteService.getPlacePredictions

转载 作者:行者123 更新时间:2023-11-29 16:13:32 26 4
gpt4 key购买 nike

我正在尝试为谷歌地点自动完成实现自定义 UI,因为预建的 UI 不允许我手动选择结果。在 getPlacePredictions 函数选项中不使用多种类型时,一切正常,但当我使用 ['(regions)', '(cities)'] 时,状态返回“无效请求”

我是做错了什么还是无法返回多种类型?

var _this = this;

this.input = $('#zipcode_autocomplete');

this.service = new google.maps.places.AutocompleteService();

this.input.on('input', function() {
return _this.service.getPlacePredictions({
input: _this.input.val(),
types: ['(regions)', '(cities)'],
componentRestrictions: {
country: 'us'
}
}, _this.callback);
});

this.callback = function(predictions, status) {
var i, prediction, _results;
console.log(predictions);
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
i = 0;
prediction = void 0;
this.results = $('ul.location_results').removeClass('hidden').html('');
_results = [];
while (prediction = predictions[i]) {
this.results.append("<li><span class='location-address'>" + prediction.terms[0].value + "</span><span class='location-state'>" + prediction.terms[prediction.terms.length - 2].value + "</span></li>");
_results.push(i++);
}
return _results;
};

最佳答案

根据 API 'In general only a single type is allowed' .

如果您要尝试分别获取这两种类型,您可以使用 deferred object管理流程,像这样:

// set a new promises array, set the types array
var promises = [], types = ['(regions)', '(cities)'];

// loop over the types and push the output of getPredications() for each one
// into the promises array
for (var i = 0, l = types.length; i < l; i++) {
promises.push(getPredictions(types[i]));
}

// when all promises have completed then do something
// This uses jQuery's when method which can take an array of
// promises when used with apply
$.when.apply(null, promises).then(runThisFunction);

function getPredictions(type) {

// Set up a new deferred object
var deferred = new $.Deferred();

// Call the asynchronous function to get the place predictions
this.service.getPlacePredictions({
input: _this.input.val(),
types: type,
componentRestrictions: {
country: 'us'
}
}, function (data) {

// Once the data has been returned perhaps do something with data
// but definitely resolve the deferred object.
deferred.resolve();
});

// return the promise
return deferred.promise();
}

关于javascript - 从 google places 返回多种类型 autocompleteService.getPlacePredictions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139700/

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