Google Places AutocompleteService filtering by cou

2020-07-02 11:54发布

I'm setting up a custom autocomplete field where I show locations from Google Places and events from my database that match the search query. For this reason, I'm using the Google Places Autocomplete Service to get the query predictions rather than plugging in the Places Autocomplete directly into my textfield.

The problem is I can't figure out how to filter Places Autocomplete suggestions by country using the AutoComplete service.

I've tried:

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

but it still shows autocomplete options from Germany and France:(

Any suggestions?

5条回答
▲ chillily
2楼-- · 2020-07-02 12:11

Use this working Code

var input = document.getElementById("query_value");
var autocomplete = new google.maps.places.Autocomplete(input, {
  componentRestrictions: { country: "IN" },
  place_id: "YOUR_PLACE_ID"
});
google.maps.event.addListener(autocomplete, "place_changed", function() {
  var place = autocomplete.getPlace();
});


https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&language=en&key=YOUR_KEY
查看更多
放我归山
3楼-- · 2020-07-02 12:23

As outlined in the documentation reference, the Places Library AutocompleteService does not support AutocompleteOptions. If you think that this would be a valuable feature, please file a Places API - Feature Request.

查看更多
放荡不羁爱自由
4楼-- · 2020-07-02 12:24

You need to pass the restrictions when you call the service, not when you create it. Here:

//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);
查看更多
我想做一个坏孩纸
5楼-- · 2020-07-02 12:31

You should use this code.

var options = {
    types: ['(cities)'],
    componentRestrictions: {country: ["in"]}
}
//Find From location    
var input= document.getElementById('input_box_city');
var fromAuto = new google.maps.places.Autocomplete(input, options);
查看更多
家丑人穷心不美
6楼-- · 2020-07-02 12:34

You can specify types, and componentRestrictions using AutocompletionRequest. Here is an example -

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>';
                    }
                }
            });
查看更多
登录 后发表回答