Auto populate address using Google Maps API

Hi,

I’ve encountered an issue in auto populating address fields in a form where user types it will automatically display addresses and when user selects an address it will auto populate in all fields including City, State and Post code. I need one additional field that is Suburbs(For a Australian website). This is the code I’ve tried. Anyone please shed some light to this?

Note: I got this from here https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/places-autocomplete-addressform#maps_places_autocomplete_addressform-javascript

 <form id="address-form" action="" method="get" autocomplete="off">
  <label class="full-field">
    <span class="form-label">Address*</span>
    <input id="ship-address" name="ship-address" required autocomplete="off" />
  </label>
  <label class="full-field">
    <span class="form-label">Suburb*</span>
    <input id="suburb" name="suburb" required />
  </label>
  <label class="full-field">
    <span class="form-label">City*</span>
    <input id="locality" name="locality" required />
  </label>
  <label class="slim-field-left">
    <span class="form-label">State*</span>
    <input id="state" name="state" required />
  </label>
  <label class="slim-field-right" for="postal_code">
    <span class="form-label">Postal code*</span>
    <input id="postcode" name="postcode" required />
  </label>
</form>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initAutocomplete&libraries=places&v=weekly" defer></script>
// This sample uses the Places Autocomplete widget to:
// 1. Help the user select a place
// 2. Retrieve the address components associated with that place
// 3. Populate the form fields with those address components.
// This sample requires the Places library, Maps JavaScript API.
// Include the libraries=places parameter when you first load the API.
// For example: <script
// src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
let autocomplete;
let address1Field;
let address2Field;
let postalField;

function initAutocomplete() {
  address1Field = document.querySelector("#ship-address");
  address2Field = document.querySelector("#address2");
  postalField = document.querySelector("#postcode");
  // Create the autocomplete object, restricting the search predictions to
  // addresses in the US and Canada.
  autocomplete = new google.maps.places.Autocomplete(address1Field, {
    componentRestrictions: { country: ["us", "ca"] },
    fields: ["address_components", "geometry"],
    types: ["address"],
  });
  address1Field.focus();
  // When the user selects an address from the drop-down, populate the
  // address fields in the form.
  autocomplete.addListener("place_changed", fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  const place = autocomplete.getPlace();
  let address1 = "";
  let postcode = "";

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  // place.address_components are google.maps.GeocoderAddressComponent objects
  // which are documented at http://goo.gle/3l5i5Mr
  for (const component of place.address_components) {
    // @ts-ignore remove once typings fixed
    const componentType = component.types[0];

    switch (componentType) {
      case "street_number": {
        address1 = `${component.long_name} ${address1}`;
        break;
      }

      case "route": {
        address1 += component.short_name;
        break;
      }

      case "postal_code": {
        postcode = `${component.long_name}${postcode}`;
        break;
      }

      case "postal_code_suffix": {
        postcode = `${postcode}-${component.long_name}`;
        break;
      }
      case "locality":
        document.querySelector("#locality").value = component.long_name;
        break;
      case "administrative_area_level_1": {
        document.querySelector("#state").value = component.short_name;
        break;
      }
      case "country":
        document.querySelector("#country").value = component.long_name;
        break;
    }
  }

  address1Field.value = address1;
  postalField.value = postcode;
  // After filling the form with address components from the Autocomplete
  // prediction, set cursor focus on the second address line to encourage
  // entry of subpremise information such as apartment, unit, or floor number.
  address2Field.focus();
}

window.initAutocomplete = initAutocomplete;

Well for starters, your code is limiting addresses to those in the US and Canada. So i dont imagine that’ll work particularly well with Australia.

Secondly, you’d need to know what component name they give to match the suburb - the state, for example, was called “administrative_area_level_1”, which is probably not grossly intuitive.

So fix the code so that it works for australia, then run it and breakpoint the code when it gets to the let address1 = ""; line, and see what the place.address_components array looks like in the console.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.