如何从AutocompleteService.GetPredictions API调用访问回调

时间:2018-01-17 09:14:45

标签: javascript google-maps

使用Google Maps AutocompleteService,有没有办法获得getpredictions调用的回调函数。

const options = {
  types: ['geocode'],
  componentRestrictions: {country: 'us'},
  placeIdOnly: true
};
const autocomplete = new google.maps.places.Autocomplete(autocompleteInput, options);
autocomplete.addListener('place_changed', () => {
  this.locselected(auto_complete.getPlace());
});

目前它会提取类似this query的内容并自动将其提供给自动完成组件,这就是我想拦截的内容。

3 个答案:

答案 0 :(得分:2)

创建一个promise并获取api里面的promise参数函数和api调用的响应解析这个promise的函数,这样你就可以对这个api进行回调。

答案 1 :(得分:0)

随着es6承诺的出现,您可以避免回调的麻烦。现在您可以使用XMLHttpRequest apiPromise api来获取数据并解决它。

new Promise ((resolve,reject)=>{

    var http = new XMLHttpRequest()

    http.open('GET','your_autocoplet_api_url_here',true)

    http.onreadystatechange = function(){

        if(http.readyState == 4 && http.status == 200){

            var result = http.response

            resolve(result) // when you resolve it it will go to the chainable 'then' method

        }
    }

    http.send()

}).then(result=>console.log(result)) // here you will receive the  resolved data, i mean the result from api call in result parameter of 'then' method

答案 2 :(得分:0)

听起来我需要的是使用AutocompleteService并调用getPlacePredictionsgetQueryPredictions,这样可以更精确地查询预测API并直接进行回调。< / p>

通过这种方式,您必须手动将结果放入自动完成组件中,甚至可能自己构建组件,但它可以让您在用于任何事情之前获得预测结果。