Google Places AutocompleteService按国家/地区进行过滤

jez*_*nag 16 google-places-api

我正在设置一个自定义自动填充字段,我在其中显示Google地方信息中的位置以及数据库中与搜索查询匹配的事件.出于这个原因,我正在使用Google地方信息自动填充服务来获取查询预测,而不是将地方自动填充功能直接插入到我的文本字段中.

问题是我无法弄清楚如何使用自动完成服务按国家/地区过滤地方自动填充建议.

我试过了:

var service = new google.maps.places.AutocompleteService(null, {
        types: ['cities'],
        componentRestrictions: {country: "au"}
    });
Run Code Online (Sandbox Code Playgroud)

但它仍然显示德国和法国的自动完成选项:(

有什么建议?

Rob*_*odd 43

您需要在调用服务时传递限制,而不是在创建服务时传递限制.这里:

//create service
service = new google.maps.places.AutocompleteService();

//perform request. limit results to Australia
var request = {
    input: 'Brisbane',
    componentRestrictions: {country: 'au'},
};
service.getPlacePredictions(request, callback);
Run Code Online (Sandbox Code Playgroud)

  • 这是行不通的!你确定吗? (2认同)

Sau*_*abh 8

您可以使用AutocompletionRequest指定类型和componentRestrictions .这是一个例子 -

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

    service.getPlacePredictions({ input: query, types: ['geocode'], 
                                componentRestrictions:{ country: 'us' } },
            function (predictions, status) {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                    var results = document.getElementById('results');
                    for (var i = 0, prediction; prediction = predictions[i]; i++) {
                        results.innerHTML += '<li>' + prediction.description + '</li>';
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)