[Tips & Scripts] Google Address Autocomplete

  • 13 October 2016
  • 36 replies
  • 1048 views

Userlevel 7
  • Former Unbouncer
  • 126 replies

You know that wonderful feeling when the Internet does the work for you? Like when you’re typing in an address, and before you’ve even finished, the internet has basically read your mind and completed the whole address for you in a dropdown menu? Ah… so satisfying.

That little piece of Internet magic is Google Address Autocomplete, and we’d like to show you how you can implement this in your Unbounce landing pages.

Autocomplete is a feature of the Places library in the Google Maps JavaScript API. You can use autocomplete to give your landing page the type-ahead-search behavior of the Google Maps search field. When a user starts typing an address, autocomplete will fill in the rest. See Google Address Autocomplete in action!


How to Install in Unbounce

Click Here for Instructions

🚨
This is not an official Unbounce feature. This functionality is based entirely on third party code, and has only been tested in limited applications. Since this isn’t a supported Unbounce feature, our support team will be unable to assist if things go awry. So if you are not comfortable with HTML, Javascript and CSS, please consider consulting an experienced developer.


Instructions

Step 1. Generate a Google developer Javascript API key here.

a. Create a New Project

b. Configure Key Permissions. In the example below, all pages on the domain ‘www.example.com’ will be able to use this API key. It is important that this is configured correctly or requests from your domain may be rejected by Google.

c. Copy your generated API Key

Step 2. Copy this script and place it in the Javascripts section of your landing page with placement ‘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>

**Step 3. ** Find the code ‘YOUR_API_KEY’ value in near the bottom of your code snippet and replace it with your new Google developer Javascript API key.

Step 4. Set up your Unbounce form with the following field IDs:
-autocomplete (this is your address field)
-street_number (Autofilled field. Can be hidden)
-route (Autofilled field. Can be hidden)
-locality (Autofilled field. Can be hidden)
-administrative_area_level_1 (Autofilled field. Can be hidden)
-postal_code (Autofilled field. Can be hidden)
-country (Autofilled field. Can be hidden)

Step 5. Save and publish your landing page.

Step 6. Celebrate


Testing

Now let’s test this puppy out! Like any other feature that you implement onto your page, you’ll want to see what effect it has on your conversion rates. We recommend running an A/B test and segmenting a small portion of traffic towards the page, just to be safe. Documentation on A/B testing can be found here.

Conclusion

Now that we’ve given you the tools, you’re officially one step closer to being a marketing extraordinaire (if you weren’t already). Once you’ve implemented this feature on your own pages, let us know what kind of impact this has on your conversions, or if you have any suggestions related to the Google Address Autocomplete feature, we want to hear ‘em!

Did you find this tip useful? Did you test this on your landing page? Let us know in the comments below!


Can’t see the instructions? Log in or Join the Community to get access immediately. 🚀


Want to take your Unbounce landing pages + Convertables™ to the next level?
:spinbounce: Check out the Ultimate List of Unbounce Tips, Scripts & Hacks


36 replies

YES!! Finally, some auto-complete magic. Love it @Noah! 🙌

Userlevel 7
Badge +4

Thanks @Noah! <3 this

@Noah what do I have to modify to restrict the results to only one country? 🙏 Thank you

Userlevel 7

@maurexyz this involves making a small change to the code. You will need to find the spot where the ‘autocomplete’ object is being created (should be around line 64-67). It should look like this:

autocomplete = new google.maps.places.Autocomplete(
 /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
 {types: ['geocode']});

Once you’ve found this, you will then need to add your country restriction. For example, if you were restricting the autocomplete function to France, you would need to add:

componentRestrictions: {country: 'fr'}

Update ‘fr’ with the country code of your choosing. Once this is added, the final code will look like:

autocomplete = new google.maps.places.Autocomplete(
 /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
 {types: ['geocode'], componentRestrictions: {country: 'fr'}});

I hope this helps!

Thanks Noah, you are my hero! I was half a day, literal, looking for this solution.

Userlevel 7

Haha! So glad I could help 😀

Noah this is a fantastic script, thank you.

Would like to now take it a step further now - perhaps this should be in a different thread but I am not sure. Once the user hits submit, I would like to pass the address information to the next page and on that page display a google maps street view of the address they had entered on the prior page.

For example check this page out - http://dallas.quickpropertyappraisal.com/. Enter an address and then the following page will have it appear on street view. Very cool.

Thoughts?

Thanks

@Noah this script is great and does exactly what we need it to do. We are finding that it doesn’t as intended on iOS mobile devices. When you enter the start of an address the mobile screen goes all white and the experience is lost.

Do you have an update that might fix this issue?

Thanks in advance…

ktk

Userlevel 7

Hey @Kelly_Konechny, I’m not able to reproduce this issue at the moment. I’ve followed up with you directly, so check your inbox!

I’m experiencing the same glitch it seems. Was there a resolution?

@Noah I’ve found the iOS white-out issue only happens when using it in a lightbox for me (so far). Can you help me investigate?

Hi @Noah is there a way to do this with two address fields on the page? I got it to work for the first but it says you can’t use the same id twice

http://affiliates.hopskipdrive.com/carpool-matching-1/

@Noah This works beautifully and captures nearly all of the information I need. However, it doesn’t include the postal code. Is there a way to modify the code to include that?

@Noah Thanks for this info! I installed per your instructions but for some reason the autocomplete is freezing when I start to type an address. See example here: http://unbouncepages.com/home-valuation-1121/

Anyone know what could be causing this and how to fix?

Thanks!

Userlevel 7
Badge +3

Hi @bpurcell30,

There is an error in the console you might want to take a look at.

Make sure you have the right API key.

Here is the relevant documentation: https://developers.google.com/maps/documentation/javascript/error-messages#api-not-activated-map-error

Best,
Hristian

Hi @Noah, awesome script! My address field is displayed on my form and working great. I’ve hidden the six other field IDs on my form but they don’t seem to auto-fill when someone completes the address field. Is there a way around this?

Hello!

We have this installed on a few landing pages, the problem we are having is the browsers autofill feature. If someone uses this, the data from the address autocomplete is not inputted correctly. Is anyone aware of a way around this by removing autofill.

Thanks very much.

@Noah I have set up this Google Autocomplete given these instructions.

Unfortunately I am getting an “Oops Something Went Wrong” Error message on the preview page of the lead form.

Is there an updated version of this process since 2016?

Or am I doing something wrong here? My Google API is setup properly and domain is verified on Google Console.

So I don’t know what is wrong. Please feel free to email me:
mdrnmediallc@gmail.com

Userlevel 5

Hey @mdrnmedia

Could you provide a link to the page you are using the script on?

I figured it out, thanks Kyle!

There is another simple way to get the auto complete as I have done for my website
http://unbouncepages.com/vizistata/

<script>
function activatePlacesSearch(){
var input = document.getElementById('ID');
var autocomplete = new google.maps.places.Autocomplete(input);
 }
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=activatePlacesSearch"></script>

Hey @Noah - the script os working well except for the field width, which I can get to match the other field’s widths in the desktop version, but then the Mobile version’s field width is about a third wider than the other fields. How do I get the field width of the ADDRESS field to “snap” to to the same width of the other fields, on both desktop and mobile? Thanks! Steven.

Ok, I’m 99% sure I’ve followed instructions properly but I’m getting an error on the form.

https://www.amplifyhomebuyers.com/

Anybody feeling kind hearted enough to help me out 🙏

Hey Matt

Can you explain what the problems are… What’s not working?

I’m getting an error saying “this page isn’t loading google maps correctly”

When you try and fill out the first field it shows that error. https://www.amplifyhomebuyers.com/

Reply