How to Add Google Address Autocomplete to a Form

Follow

Google Address Autocomplete suggests full addresses as a visitor types and fills in the matching address fields on your form. This makes forms faster to complete and reduces address errors.

Address form with Street Address autocomplete field, Apartment/Suite, City, State, and ZIP inputs.

This is community code, not an official Unbounce feature. Unbounce Support can't troubleshoot custom code. Test it on a published page before relying on it, and work with a developer if you aren't comfortable editing HTML, JavaScript, and CSS.

Add address autocomplete to your form

  1. Create a Google JavaScript API key. See Get an API key in Google's documentation.

    1. Create a new project.
    Google Developers Console: Register app for Maps JavaScript API, with "Create a new project" dropdown selected.
    1. Set the key's permissions so your domain can use it. In this example, all pages on www.example.com can use the key. If this isn't set correctly, Google may reject requests from your pages.
    Google API Console "Create browser API key" panel with name field and HTTP referrers restriction field filled in.
    1. Copy the generated API key.
  2. In the JavaScripts section, add the following script with placement set to Before Body End Tag:
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <style>
      #locationField, #controls {
        position: relative;
        width: 480px;
      }
      #autocomplete {
        position: absolute;
        width: 99%;
      }
      #address {
        border: 1px solid #000090;
        background-color: #f0f0ff;
        width: 480px;
        padding-right: 2px;
      }
      #address td {
        font-size: 10pt;
      }
      .field {
        width: 99%;
      }
      .slimField {
        width: 80px;
      }
      .wideField {
        width: 200px;
      }
      #locationField {
        height: 20px;
        margin-bottom: 2px;
      }
    </style>
    <script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};
function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
      /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
      {types: ['geocode']});
  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}
// [START region_fillform]
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]];
      console.log(val);
      document.getElementById(addressType).value = val;
    }
  }
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
// [END region_geolocation]
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&libraries=places&callback=initAutocomplete"
        async defer></script>
<script>
  //Prevent enter key submissions in Autocomplete field
  document.querySelector('#autocomplete').addEventListener('keydown', function(e){
    if ( e.which == 13 ) return false;
    //or...
    if ( e.which == 13 ) e.preventDefault();
});
</script>
  1. Near the end of the script, replace YOUR_API_KEY with your API key.

    Code editor showing line 117 where YOUR_API_KEY placeholder is highlighted in Google Maps script tag.
  2. Set up your form with the following field IDs. Every field except autocomplete is filled in automatically and can be hidden.

    • autocomplete, the address field the visitor types in
    • street_number
    • route
    • locality
    • administrative_area_level_1
    • postal_code
    • country
    Form builder showing Address field settings with "autocomplete" as Field Name and ID, and Hide label checkbox checked.
  3. Save and republish the page.

Test the change

Run an A/B test with a small share of traffic to confirm the change doesn't lower your conversion rate. See How to Run an A/B Test.