Google Place Autocomplete

Google places javascript

Add google maps places javascript by adding the following script to your webpage, be sure to fill in your API key.

To get your API key head over to console.developers.google.com and create a new API key for your project. Don't forget to restrict the use of the API key!

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete&language=nl&output=json&key=YOUR_API_KEY" async defer></script>

As you can see we specified a few things here.
##Language
We want our results returned in a certain language, in this case dutch. For this we add the language=nl to our query parameters.

Output

With the parameter output we can specify in what format we want to receive our data, json or xml. (output=json)

Callback

Here we specify which function should be executed after the javascript is loaded. In this case we speficied that the function "initAutocomplete" needs to be called. (callback=initAutocomplete)

Creating a autocomplete field

Create an input field of type text and give it an id so we can identify it.

<input type="text" id="address">

By using the javascript library we loaded earlier we are going to create and configure our autocomplete.

<script type="text/javascript">
  function initAutocomplete() {
    var address = document.getElementById('address');
    var autocomplete = new google.maps.places.Autocomplete(address);
  }
</script>

Getting the selected place

To get the place that our user has selected in the dropdown we can use the function "getPlace" on our autocompletefield. But first we need to know when our user has selected a place, for this we will add a listener.

autocomplete.addListener('place_changed', function() {
  var place = autocomplete.getPlace();
});

Options

To let autocomplete know what suggestions it should return, we can configure various options.

Types

An array of types specifies an explicit type or a type collection, as listed in the supported types below. If nothing is specified, all types are returned. In general only a single type is allowed.

  • geocode instructs the Places service to return only geocoding results, rather than business results.
  • address instructs the Places service to return only geocoding results with a precise address.
  • establishment instructs the Places service to return only business results.
  • the (regions) type collection instructs the Places service to return any result matching the following types:
    • locality
    • sublocality
    • postal_code
    • country
    • administrative_area1
    • administrative_area2
  • the (cities) type collection instructs the Places service to return results that match either locality or administrative_area3.

In the example below we only want to return establishments.

function initAutocomplete() {
  var address = document.getElementById('address');
  var options = {
  	types: ['establishment'],
  };

  var autocomplete = new google.maps.places.Autocomplete(address, options);
}

Restrict the search to a specific country or multiple countries

Use the componentRestrictions option to restrict the autocomplete search to a particular country. The following code restricts the results to places within France and Germany.

function initAutocomplete() {
  var address = document.getElementById('address');
  var options = {
    componentRestrictions: {country: ['fr', 'de']}
  };

  var autocomplete = new google.maps.places.Autocomplete(address, options);
}

Getting latitude and longitude

Wen the user has selected a place we can get the latitude and longitude by calling lat() and lng() on the place object. If you need latitude and logitude saved to use on your backend you can write these values to a hidden field.

<input type="hidden" id="lat" value="">
<input type="hidden" id="lng" value="">

<script type="text/javascript">
  function initAutocomplete() {
    var address = document.getElementById('address');
    var autocomplete = new google.maps.places.Autocomplete(address);

    autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      var latitude = place.geometry.location.lat();
      var longitude = place.geometry.location.lng();
      document.getElementById('lat').value = latitude;
      document.getElementById('lng').value = longitude;
    });
  }
</script>

Searching on postalcode or city

function initAutocomplete() {
  var example = document.getElementById('example');
  var options = {
  types: ['(regions)'],
  	componentRestrictions: {country: ['be']}
  };

  var autocomplete = new google.maps.places.Autocomplete(example, options);
}

Autofill address fields

var autocomplete = null;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_2: 'long_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  var address = document.getElementById('address');
  var options = {
    types: ['address'],
    componentRestrictions: {country: ['be']}
  };

  autocomplete = new google.maps.places.Autocomplete(address, options);
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

For more information head to https://developers.google.com/places/web-service/autocomplete