Place Autocomplete Address Form

Sample code for Google Maps Platform JavaScript API author(s): Justin Poehnelt

by akmiecik

HTML

<!DOCTYPE html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <link
      href="https://fonts.googleapis.com/css?family=Roboto:400,500"
      rel="stylesheet"
    />

    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <!-- Note: The address components in this sample are based on North American address format. You might need to adjust them for the locations relevant to your app. For more information, see
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
    -->

    <form id="address-form" action="" method="get" autocomplete="off">
     

        <input
          id="ship-address"
          name="ship-address"
          required
          autocomplete="off"
        />
    </form>
    

    <!-- 
     The `defer` attribute causes the callback to execute after the full HTML
     document has been parsed. For non-blocking uses, avoiding race conditions,
     and consistent behavior across browsers, consider loading using Promises
     with https://www.npmjs.com/package/@googlemaps/js-api-loader.
    -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initAutocomplete&libraries=places&v=weekly"
      defer
    ></script>
  </body>
</html>

CSS

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  font-family: "Roboto", sans-serif;
  font-size: 18px;
  color: rgb(104, 104, 104);
}

form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  max-width: 400px;
  padding: 20px;
}

input {
  width: 100%;
  height: 1.2rem;
  margin-top: 0;
  padding: 0.5em;
  border: 0;
  border-bottom: 2px solid gray;
  font-family: "Roboto", sans-serif;
  font-size: 18px;
}

input:focus {
  border-bottom: 4px solid black;
}

input[type=reset] {
  width: auto;
  height: auto;
  border-bottom: 0;
  background-color: transparent;
  color: rgb(104, 104, 104);
  font-size: 14px;
}

.title {
  width: 100%;
  margin-block-end: 0;
  font-weight: 500;
}

.note {
  width: 100%;
  margin-block-start: 0;
  font-size: 12px;
}

.form-label {
  width: 100%;
  padding: 0.5em;
}

.full-field {
  flex: 400px;
  margin: 15px 0;
}

.slim-field-left {
  flex: 1 150px;
  margin: 15px 15px 15px 0px;
}

.slim-field-right {
  flex: 1 150px;
  margin: 15px 0px 15px 15px;
}

.my-button {
  background-color: #000;
  border-radius: 6px;
  color: #fff;
  margin: 10px;
  padding: 6px 24px;
  text-decoration: none;
}

.my-button:hover {
  background-color: #666;
}

.my-button:active {
  position: relative;
  top: 1px;
}

img.powered-by-google {
  margin: 0.5em;
}

JavaScript

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, {
    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 "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;