[javascript] How to limit google autocomplete results to City and Country only

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>

This question is related to javascript autocomplete google-maps-api-3

The answer is


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.


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"}
     };

More information and options available at

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

Hope this might be useful to someone


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


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 ...

}

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..


_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var options = {_x000D_
        types: ['geocode'] //this should work !_x000D_
      };_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input, options);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

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


try this

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&region=in" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

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"


<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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to autocomplete

twitter bootstrap 3.0 typeahead ajax example How do I stop Notepad++ from showing autocomplete for all words in the file how to get value of selected item in autocomplete .autocomplete is not a function Error Angularjs autocomplete from $http autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete Disabling Chrome Autofill How to add Google Maps Autocomplete search box? Google Maps API - how to get latitude and longitude from Autocomplete without showing the map? twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Examples related to google-maps-api-3

Google Maps shows "For development purposes only" Googlemaps API Key for Localhost ERROR: Google Maps API error: MissingKeyMapError Google Maps API warning: NoApiKeys Google Maps JavaScript API RefererNotAllowedMapError This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console TypeError: window.initMap is not a function Google maps Marker Label with multiple characters Google Maps how to Show city or an Area outline How to use SVG markers in Google Maps API v3