Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict google places to specific city

I am currently able to restrict places to only one country, but I also want to restrict on a specific city also. Any ideas how to achieve that? This is my current code:

var autocomplete,
                    options = {
                        types: ['geocode'],
                        componentRestrictions: {country: 'est'}
                    };
                autocomplete = new google.maps.places.Autocomplete(input, options);
                google.maps.event.addListener(autocomplete, 'place_changed', function () {
                    var place = autocomplete.getPlace().formatted_address;
                    $(input).attr('value',place);
                });
like image 260
fishera Avatar asked Oct 19 '15 12:10

fishera


2 Answers

As Luke said the places autocomplete allows you to use componentRestrictions to filter by country only.

But you can use a little trick with a search request string. Just add prefix with city name in request.

var prefix = 'Kyiv, ';

$(input).on('input',function(){
    var str = input.value;
    if(str.indexOf(prefix) == 0) {
        // string already started with prefix
        return;
    } else {
        if (prefix.indexOf(str) >= 0) {
            // string is part of prefix
            input.value = prefix;
        } else {
            input.value = prefix+str;
        }
    }
});

http://jsfiddle.net/24p1et98/

like image 60
Alexey Muravyov Avatar answered Sep 25 '22 02:09

Alexey Muravyov


Places Autocomplete currently allows you to use componentRestrictions to filter by country. What I would do in your situation is to use the options argument to filter by the bounds that define the city in question:

var cityBounds = new google.maps.LatLngBounds(
  new google.maps.LatLng(25.341233, 68.289986),
  new google.maps.LatLng(25.450715, 68.428345));

var options = {
  bounds: cityBounds,
  types: ['geocode'],
  componentRestrictions: {country: 'est'}
};
like image 30
luke_mclachlan Avatar answered Sep 24 '22 02:09

luke_mclachlan