Does your application include an address form, such as the shipping address for an online order, a credit card billing address, or a ridesharing booking form? Autocomplete can help users supply the details.
The Place Autocomplete Address Form sample captures selected address components from the Google Places database, and uses them to populate an address form.
Since this sample only requires a place address in a structured format, the
sample code uses just one place data field: address_components
. The requested
place data fields affect the
cost of each request. You can specify
which place data fields to return by calling
Autocomplete.setFields()
,
and specifying one or more
place data fields.
The address components in this sample are based on a typical address format.
Note that you might need to use a different set of components to align with the
postal address formats used in some regions. For example, the sample code
selects the locality
component, which often represents the city part of the
address. Examples of how components can differ include:
- In the UK and in Sweden, the component to display the city is
postal_town
. - In Japan, components differ across prefectures.
- Brooklyn and other parts of New York City do not include the city as part of
the address. Instead, they use
sublocality_level_1
.
When the user selects an address from the pick list, your application can populate the address form.
For more information, see Places Autocomplete widget.
TypeScript
// 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: google.maps.places.Autocomplete; let address1Field: HTMLInputElement; let address2Field: HTMLInputElement; let postalField: HTMLInputElement; function initAutocomplete() { address1Field = document.querySelector("#ship-address") as HTMLInputElement; address2Field = document.querySelector("#address2") as HTMLInputElement; postalField = document.querySelector("#postcode") as HTMLInputElement; // 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 as google.maps.GeocoderAddressComponent[]) { // @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") as HTMLInputElement).value = component.long_name; break; case "administrative_area_level_1": { (document.querySelector("#state") as HTMLInputElement).value = component.short_name; break; } case "country": (document.querySelector("#country") as HTMLInputElement).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(); } declare global { interface Window { initAutocomplete: () => void; } } window.initAutocomplete = initAutocomplete;
JavaScript
// 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;
CSS
/* * 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%; 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; } .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; margin-inline-start: 0; } .slim-field-right { flex: 1 150px; margin: 15px; margin-inline-end: 0; } .my-button { background-color: #000; border-radius: 6px; color: #fff; margin: 10px; cursor: pointer; padding: 6px 24px; text-decoration: none; } .my-button:hover { background-color: #666; } .my-button:active { position: relative; top: 1px; }
HTML
<html> <head> <title>Place Autocomplete Address Form</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,500" rel="stylesheet" /> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></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"> <!-- Avoid the word "address" in id, name, or label text to avoid browser autofill from conflicting with Place Autocomplete. Star or comment bug https://crbug.com/587466 to request Chromium to honor autocomplete="off" attribute. --> <span class="form-label">Deliver to*</span> <input id="ship-address" name="ship-address" required autocomplete="off" /> </label> <label class="full-field"> <span class="form-label">Apartment, unit, suite, or floor #</span> <input id="address2" name="address2" /> </label> <label class="full-field"> <span class="form-label">City*</span> <input id="locality" name="locality" required /> </label> <label class="slim-field-start"> <span class="form-label">State/Province*</span> <input id="state" name="state" required /> </label> <label class="slim-field-end" for="postal_code"> <span class="form-label">Postal code*</span> <input id="postcode" name="postcode" required /> </label> <label class="full-field"> <span class="form-label">Country/Region*</span> <input id="country" name="country" required /> </label> <button type="button" class="my-button">Save address</button> <!-- Reset button provided for development testing convenience. Not recommended for user-facing forms due to risk of mis-click when aiming for Submit button. --> <input type="reset" value="Clear form" /> </form> <!-- The `defer` attribute causes the script 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. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initAutocomplete&libraries=places&v=weekly" defer ></script> </body> </html>
Try Sample
Clone Sample
Git and Node.js are required to run this sample locally. Follow these instructions to install Node.js and NPM. The following commands clone, install dependencies and start the sample application.
git clone -b sample-places-autocomplete-addressform https://github.com/googlemaps/js-samples.git
cd js-samples
npm i
npm start
Other samples can be tried by switching to any branch beginning with sample-SAMPLE_NAME
.
git checkout sample-SAMPLE_NAME
npm i
npm start