Ad

Restricting Search Based On A Particular Country In The Google Maps Places API

- 1 answer

I am using the Google Maps' Places API for autocompletion of location as user types. But how can I restrict the suggestions to a particular country?

Here is my javascript:

function initAutocomplete() {

    // Create the search box and link it to the UI element.
    var input = document.getElementById('autocomplete-input');
    var searchBox = new google.maps.places.SearchBox(input);

    // [START region_getplaces]
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();
        if (places.length == 0) {
            return;
        }
    });
}
Ad

Answer

Fixed it by changing SearchBox to Autocomplete and passing an options with the requirements..Here is the code if someone needs.

function initAutocomplete() {

    // Create the search box and link it to the UI element.
    var input = document.getElementById('autocomplete-input');
    var options = {
        componentRestrictions: {country: 'fr'}
    };

    var searchBox = new google.maps.places.Autocomplete(input, options);

    // [START region_getplaces]
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();
        if (places.length == 0) {
            return;
        }
    });
}
Ad
source: stackoverflow.com
Ad