231

I am using google autocomplete places javascript to return suggested results for my searchbox , what I need is to only show the city and the country related to the characters entered but google api will give a lot of general places results which I dont need , so how to limit the result to show only city and the country .

I am using the following Example:

<html>
<head>
<style type="text/css">
   body {
         font-family: sans-serif;
         font-size: 14px;
   }
</style>

<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places" type="text/javascript"></script>
<script type="text/javascript">
   function initialize() {
      var input = document.getElementById('searchTextField');
      var autocomplete = new google.maps.places.Autocomplete(input);
   }
   google.maps.event.addDomListener(window, 'load', initialize);
</script>

</head>
<body>
   <div>
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">
   </div>
</body>
</html>
John Conde
  • 217,595
  • 99
  • 455
  • 496
JohnTaa
  • 2,722
  • 2
  • 15
  • 15

11 Answers11

436

You can try the country restriction

function initialize() {

 var options = {
  types: ['(cities)'],
  componentRestrictions: {country: "us"}
 };

 var input = document.getElementById('searchTextField');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}

More info:

ISO 3166-1 alpha-2 can be used to restrict results to specific groups. Currently, you can use componentRestrictions to filter by country.

The country must be passed as as a two character, ISO 3166-1 Alpha-2 compatible country code.


Officially assigned country codes
Francisco Presencia
  • 8,732
  • 6
  • 46
  • 90
Francois
  • 10,465
  • 4
  • 53
  • 64
  • Do you know if there are any usage limit on auto complete queries if I am not loading any maps? I know there is a 25,000 usage limit if I load maps – Mithil Mar 29 '13 at 21:53
  • This awsome examples. How to prepare all results to format like this: city, region, country? – kicaj Jul 09 '13 at 17:30
  • is there a way where i don't have to limit the country? – Anidhya Ahuja Mar 31 '14 at 09:20
  • try removing the restriction from the options. – Francois Mar 31 '14 at 09:21
  • 5
    It's August 2014. Is it already possible to show only countries and cities? For e.g. when I type Mil, the result is Milan, Bergamo, Italy. I need only Milan, Italy. Adding all countries one by one is not an option. – erdomester Aug 06 '14 at 00:08
  • Hi @erdomester hope this post gives some insight. https://code.google.com/p/gmaps-api-issues/issues/detail?id=4233 – Francois Sep 07 '14 at 11:24
  • 2
    Is it possible to specify more than one country? – bart Jul 16 '15 at 17:57
  • Thanks for the `types: ['(cities)']` Was looking for this! – Nagendra Rao Aug 07 '15 at 15:51
  • 2
    @bart apparently it is not possible. Please star [this issue](https://goo.gl/iijOcl) if you want that feature. – dlsso Sep 02 '15 at 15:29
  • @bart : Having the same problem for multiple countries, stared the issue that google doesn't seem to take much care of. – COil Dec 01 '15 at 16:58
  • works great, but is there any way (don't want to go too much off topic) to make the search less strict ? I mostly work with french cities and if accents or hyphens do not match exactly the name of the city you are looking for it won't get any result – Rayjax Dec 15 '15 at 22:55
  • @Francois, using google map API can we add multiple cities in single textbox? Example I want to add multiple locations for "Preferred Location" for Job etc. – Nikhil sHETH May 26 '16 at 12:46
  • 1
    if we use types: ['(cities)'] then it will not allowed us to search by zip code here. – Mohneesh Agrawal Aug 29 '16 at 06:30
  • adding type cities doen't allow to search location by zipcode. – Mohneesh Agrawal Sep 06 '16 at 11:00
  • apparently it allows restricting by more than one country by now: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-multiple-countries – seBaka28 Sep 24 '18 at 12:28
  • Also, using types: ['(regions)'] instead of '(cities)' allows searching for postal code as well – seBaka28 Sep 24 '18 at 12:35
  • I want to allow to choose city, bar, restaurant, hotels, airports and other small locations but NOT STATE NAME and COUNTRY NAME in google autocomplete, how can i do, please share any suggestion, thanks a lot :) – Kamlesh Dec 20 '19 at 11:08
  • "Currently, you can use componentRestrictions to filter by up to 5 countries" https://developers.google.com/maps/documentation/javascript/places-autocomplete – Ben Racicot Apr 09 '20 at 22:38
  • Does it matter if the function is called ```initialize```? When does this get called in the page? – default123 Sep 15 '20 at 00:00
  • Guys...is it possible to restrict the length of the formatted address? I want it not greater than 50 characters. – jay rangras Nov 12 '21 at 06:17
29

<html>
<head>
<style type="text/css">
   body {
         font-family: sans-serif;
         font-size: 14px;
   }
</style>

<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
<script type="text/javascript">
   function initialize() {
      var input = document.getElementById('searchTextField');
      var options = {
        types: ['geocode'] //this should work !
      };
      var autocomplete = new google.maps.places.Autocomplete(input, options);
   }
   google.maps.event.addDomListener(window, 'load', initialize);
</script>

</head>
<body>
   <div>
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">
   </div>
</body>
</html>
var options = {
  types: ['geocode'] //this should work !
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

reference to other types: http://code.google.com/apis/maps/documentation/places/supported_types.html#table2

unloco
  • 6,928
  • 2
  • 47
  • 58
  • 1
    check this code right from google. they made a filtering example http://code.google.com/apis/maps/documentation/javascript/places.html#adding_autocomplete – unloco Nov 26 '11 at 22:37
  • autocomplete object will not accept two variables, only one variable can be accepted which is 'geocode'. I don't know how to solve this problem . Google documentation list a lot of type but none can be accepted. – JohnTaa Nov 27 '11 at 11:51
  • 1
    would the same parameters work for `AutocompleteService`? – Steven Aguilar Mar 27 '19 at 19:24
24

The answer given by Francois results in listing all the cities from a country. But if the requirement is to list all the regions (cities + states + other regions etc) in a country or the establishments in the country, you can filter results accordingly by changing types.

List only cities in the country

 var options = {
  types: ['(cities)'],
  componentRestrictions: {country: "us"}
 };

List all cities, states and regions in the country

 var options = {
  types: ['(regions)'],
  componentRestrictions: {country: "us"}
 };

List all establishments — such as restaurants, stores, and offices in the country

  var options = {
      types: ['establishment'],
      componentRestrictions: {country: "us"}
     };

Also, you can add multiple types to the result filter like this:

List all the establishments equal to schools and drugstores, and places of type neighborhoods, locality, and sublocality

  var options = {
      types: ['school','drugstore','neighborhood', 'locality', 'sublocality'],
      componentRestrictions: {country: "us"}
     };

Note: See the available types and note that you can combine only the items at table 1 and table 2, and up to 5 items. Table 3 don't allow to combine.

More information and options available at

https://developers.google.com/maps/documentation/javascript/places-autocomplete

Hope this might be useful to someone

Kiran Muralee
  • 2,068
  • 2
  • 18
  • 25
15

try this

<html>
<head>
<style type="text/css">
   body {
         font-family: sans-serif;
         font-size: 14px;
   }
</style>

<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&region=in" type="text/javascript"></script>
<script type="text/javascript">
   function initialize() {
      var input = document.getElementById('searchTextField');
      var autocomplete = new google.maps.places.Autocomplete(input);
   }
   google.maps.event.addDomListener(window, 'load', initialize);
</script>

</head>
<body>
   <div>
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">
   </div>
</body>
</html>

http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"

Change this to: "region=in" (in=india)

"http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&region=in" type="text/javascript"

unloco
  • 6,928
  • 2
  • 47
  • 58
Ravindra
  • 309
  • 3
  • 11
14

Basically same as the accepted answer, but updated with new type and multiple country restrictions:

function initialize() {

 var options = {
  types: ['(regions)'],
  componentRestrictions: {country: ["us", "de"]}
 };

 var input = document.getElementById('searchTextField');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}

Using '(regions)' instead of '(cities)' allows to search by postal code as well as city name.

See official documentation, Table 3: https://developers.google.com/places/supported_types

seBaka28
  • 932
  • 1
  • 7
  • 16
9

I've been playing around with the Google Autocomplete API for a bit and here's the best solution I could find for limiting your results to only countries:

var autocomplete = new google.maps.places.Autocomplete(input, options);
var result = autocomplete.getPlace();
console.log(result); // take a look at this result object
console.log(result.address_components); // a result has multiple address components

for(var i = 0; i < result.address_components.length; i += 1) {
  var addressObj = result.address_components[i];
  for(var j = 0; j < addressObj.types.length; j += 1) {
    if (addressObj.types[j] === 'country') {
      console.log(addressObj.types[j]); // confirm that this is 'country'
      console.log(addressObj.long_name); // confirm that this is the country name
    }
  }
}

If you look at the result object that's returned, you'll see that there's an address_components array which will contain several objects representing different parts of an address. Within each of these objects, it will contain a 'types' array and within this 'types' array, you'll see the different labels associated with an address, including one for country.

wmock
  • 5,382
  • 4
  • 40
  • 62
  • Is there a way to restrict to only certain states in the US, or even exclude particular states? – Martin Erlic Mar 09 '16 at 01:58
  • @santafebound I'm trying to do the same thing (for a specific state in Australia). From the documentation it looks like the answer is 'No[t yet]', but I'm hoping to find a way to intercept the `response` object and restrict it by other keys in the data. – GT. Feb 05 '17 at 21:53
7

For country you can use this:

components=country:pak

https://maps.googleapis.com/maps/api/place/autocomplete/json?&input=${text-to-search}&key=${API_KEY}&language=en&components=country:pak
6

I found a solution for myself

var acService = new google.maps.places.AutocompleteService();
var autocompleteItems = [];

acService.getPlacePredictions({
    types: ['(regions)']
}, function(predictions) {
    predictions.forEach(function(prediction) {
        if (prediction.types.some(function(x) {
                return x === "country" || x === "administrative_area1" || x === "locality";
            })) {
            if (prediction.terms.length < 3) {
                autocompleteItems.push(prediction);
            }
        }
    });
});

this solution only show city and country..

Cenk YAGMUR
  • 3,154
  • 2
  • 26
  • 42
4

Also you will need to zoom and center the map due to your country restrictions!

Just use zoom and center parameters! ;)

function initialize() {
  var myOptions = {
    zoom: countries['us'].zoom,
    center: countries['us'].center,
    mapTypeControl: false,
    panControl: false,
    zoomControl: false,
    streetViewControl: false
  };

  ... all other code ...

}
Kir Mazur
  • 997
  • 2
  • 13
  • 27
2
<html>
  <head>
    <title>Example Using Google Complete API</title>   
  </head>
  <body>

<form>
   <input id="geocomplete" type="text" placeholder="Type an address/location"/>
    </form>
   <script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

  <script src="http://ubilabs.github.io/geocomplete/jquery.geocomplete.js"></script>
  <script>
   $(function(){        
    $("#geocomplete").geocomplete();                           
   });
  </script>
 </body>
</html>

For more information visit this link

ddb
  • 2,423
  • 7
  • 28
  • 38
Hina Vaja
  • 314
  • 1
  • 5
  • 15
0

For cities you can try this

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=new delhi&types=locality&key=Your_API_Key

Response

 {
    "predictions": [
        {
            "description": "New Delhi, Delhi, India",
            "matched_substrings": [
                {
                    "length": 9,
                    "offset": 0
                }
            ],
            "place_id": "ChIJLbZ-NFv9DDkRzk0gTkm3wlI",
            "reference": "ChIJLbZ-NFv9DDkRzk0gTkm3wlI",
            "structured_formatting": {
                "main_text": "New Delhi",
                "main_text_matched_substrings": [
                    {
                        "length": 9,
                        "offset": 0
                    }
                ],
                "secondary_text": "Delhi, India"
            },
            "terms": [
                {
                    "offset": 0,
                    "value": "New Delhi"
                },
                {
                    "offset": 11,
                    "value": "Delhi"
                },
                {
                    "offset": 18,
                    "value": "India"
                }
            ],
            "types": [
                "locality",
                "political",
                "geocode"
            ]
        },
        {
            "description": "New Delhi, Madhya Pradesh, India",
            "matched_substrings": [
                {
                    "length": 9,
                    "offset": 0
                }
            ],
            "place_id": "ChIJF6eOnlmqhTkR2f8IfiLL4bs",
            "reference": "ChIJF6eOnlmqhTkR2f8IfiLL4bs",
            "structured_formatting": {
                "main_text": "New Delhi",
                "main_text_matched_substrings": [
                    {
                        "length": 9,
                        "offset": 0
                    }
                ],
                "secondary_text": "Madhya Pradesh, India"
            },
            "terms": [
                {
                    "offset": 0,
                    "value": "New Delhi"
                },
                {
                    "offset": 11,
                    "value": "Madhya Pradesh"
                },
                {
                    "offset": 27,
                    "value": "India"
                }
            ],
            "types": [
                "locality",
                "political",
                "geocode"
            ]
        },
        {
            "description": "Delhi, NY, USA",
            "matched_substrings": [
                {
                    "length": 5,
                    "offset": 0
                }
            ],
            "place_id": "ChIJVS4Od-R43IkRReeLGEBFcv8",
            "reference": "ChIJVS4Od-R43IkRReeLGEBFcv8",
            "structured_formatting": {
                "main_text": "Delhi",
                "main_text_matched_substrings": [
                    {
                        "length": 5,
                        "offset": 0
                    }
                ],
                "secondary_text": "NY, USA"
            },
            "terms": [
                {
                    "offset": 0,
                    "value": "Delhi"
                },
                {
                    "offset": 7,
                    "value": "NY"
                },
                {
                    "offset": 11,
                    "value": "USA"
                }
            ],
            "types": [
                "locality",
                "political",
                "geocode"
            ]
        }
    ],
    "status": "OK"
}
Deepak Yadav
  • 227
  • 3
  • 4