places-autocomplete-addressform

Sample code supporting Google Maps Platform JavaScript API documentation. author(s): Geo Developer IX Documentation Team

HTML

<!doctype html>
<!--
 @license
 Copyright 2025 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->

<html>
  <head>
    <title>Place Autocomplete Address Form</title>

    <link
      href="https://fonts.googleapis.com/css?family=Roboto:400,500"
      rel="stylesheet" />

    <script>
      // prettier-ignore
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
            });
    </script>
  </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">
      <p class="title">Sample address form for North America</p>
      <p class="note"><em>* = required field</em></p>
      <label class="full-field">
        <span class="form-label">Deliver to*</span>
        <gmp-place-autocomplete
          included-primary-types="street_address"
          included-region-codes="US"></gmp-place-autocomplete>
      </label>
      <label class="full-field">
        <span class="form-label">Street address*</span>
        <input id="address1" name="address1" />
      </label>
      <label class="full-field">
    ...

CSS

/**
 * @license
 * Copyright 2025 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Roboto', sans-serif;
  font-size: 18px;
  color: rgb(104, 104, 104);
  overflow: hidden;
}

form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  max-width: 400px;
  padding: 20px;
  margin: 5px;
  border: 2px solid #adacac;
  border-radius: 5px;
}

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

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

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

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

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

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

.address-row {
  display: flex;
  width: 95%;
  gap: 1.5em; /* Add space between the two fields */
  padding-bottom: 0;
}

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

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

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

JavaScript

'use strict';
/**
 * @license
 * Copyright 2025 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

// 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.

let placeAutocomplete;
let address1Field;
let address2Field;
let postalField;

async function init() {
  await google.maps.importLibrary('places');

  placeAutocomplete = document.querySelector('gmp-place-autocomplete');
  address1Field = document.querySelector('#address1');
  address2Field = document.querySelector('#address2');
  postalField = document.querySelector('#postcode');
  const saveButton = document.querySelector('.my-button');

  placeAutocomplete.focus();

  // Handle user selection on the autocomplete widget.
  placeAutocomplete.addEventListener('gmp-select', ({ placePrediction }) => {
    void fillInAddress(placePrediction);
  });

  saveButton.addEventListener('click', () => {
    // Display a message when the Save button is clicked.
    alert('In a real application, this would save the address details.');
  });
}

async function fillInAddress(placePrediction) {
  // The placePrediction object does not have all the details needed
  // for the form, so we'll call fetchFields to get the place details.
  const place = placePrediction.toPlace();
  await place.fetchFields({ fields: ['addressComponents'] });

  let address1 = '';
  let address2 = '';
  let postcode = '';

  if (!place.addressComponents) {
    return;
  }

  // Populate form fields with address component data.
  // The field is only updated if the types array includes
  // the specified type-value.
  for (const component of place.addressComponents) {
    if (component.types.includes('street_address')) {
      address1 = `${component.longText} ${address1}`;
    }

    if...