使用typeahead.js的Google api自动填充预测不起作用

时间:2017-11-13 11:14:17

标签: javascript google-maps-api-3 typeahead.js

我想显示来自谷歌自动填充预测的提前建议。

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


          $('.delivery_areas').typeahead({
                highlight: true,
                minLength: 3,  

            },{

                name: 'predictions',
                limit: 6,
                async: true,
                source: function(q, sync,async) {
                    matches = [];
                    service.getPlacePredictions({
                        input: q
                    }, function(predictions, status) {
                        if (status == google.maps.places.PlacesServiceStatus.OK) {
                            predictions.forEach(function(prediction) {
                                matches.push(prediction.description);
                            });
                        }
                    });
                  //console.log(matches) display a list of suggestions from google
                  async(matches);
                 //cb(matches) also wont work  
                }
            });

不知何故,它不适用于来自自动完成API的结果。 我尝试了同步和异步回调。

注意:Typeahead可以正常使用示例数据源,API端也没有问题。结果即将发布并存储在匹配数组中。

1 个答案:

答案 0 :(得分:0)

回调不在正确的地方

$('.delivery_areas').typeahead({
                highlight: true,
                minLength: 3,  

            },{

                name: 'predictions',
                limit: 6,
                async: true,
                source: function(q, sync,async) {
                    matches = [];
                    service.getPlacePredictions({
                        input: q
                    }, function(predictions, status) {
                        if (status == google.maps.places.PlacesServiceStatus.OK) {
                            predictions.forEach(function(prediction) {
                                matches.push(prediction.description);
                            });
                         async(matches);
                        }
                    });

                }
            });