This example demonstrates how to integrate the Places Autocomplete component into a
typical checkout form. By autocompleting addresses, you can significantly speed up the
checkout process, reduce user input errors, and create a smoother, more professional
user experience.
powered by
Step-by-Step Implementation
Integrating address autocomplete into your checkout form is straightforward. The logic
centers on the onResponse callback, which fires after a user selects an address from the dropdown.
Here’s a breakdown of the process:
Initialise the Component: First, we create a new instance of PlacesAutocomplete, providing the containerId where the input field will be rendered and your googleMapsApiKey.
Handle the Response: The onResponse callback receives a placeDetails object from the Google Places API. This object contains a wealth of information, including
a structured addressComponents array.
Map Address Components: To make the data easy to work with, we use the reduce method to transform the addressComponents array into a simple key-value object. This mapping makes accessing specific address parts
(like postal_code or country) clean and predictable.
Populate Form Fields: With the mapped components, we can now directly populate the corresponding form fields.
The code populates street number, street name, city, county, postal code, and country, ready for submission. Adjust for your form structure as needed.
<script>import{ PlacesAutocomplete }from'places-autocomplete-js';
document.addEventListener('DOMContentLoaded',()=>{try{const autocomplete =newPlacesAutocomplete({containerId:'autocomplete-container',googleMapsApiKey:'YOUR_GOOGLE_MAPS_API_KEY',// Replace with your actual keyonResponse:(placeDetails)=>{// Helper to map address components for easy accessconst components = placeDetails.addressComponents.reduce((acc, component)=>{const type = component.types[0];
acc[type]= component.longText;return acc;},{});// Helper function to set input value if element existsconstsetInputValue=(id, value)=>{const element = document.getElementById(id);if(element){
element.value = value;}};// Reset and populate form fieldssetInputValue('address1', components.street_number || components.point_of_interest ||'');setInputValue('address2', components.route ||'');setInputValue('city', components.postal_town ||'');setInputValue('county', components.administrative_area_level_1 ||'');setInputValue('postcode', components.postal_code ||'');setInputValue('country', components.country ||'');},onError:(error)=>{
console.error('Autocomplete Error:', error.message || error);},requestParams:{region:'GB',// Example regionincludedRegionCodes:['GB']// Example countries},// UI Optionsoptions:{placeholder:'Start typing your address...',clear_input:false,// Retain input value after selection}});}catch(error){
console.error('Failed to initialise PlacesAutocomplete:', error.message);}});</script>...<div id="autocomplete-container"></div><div><label for="address1">Street Number:</label><input type="text" id="address1"></div><div><label for="address2">Street Name:</label><input type="text" id="address2"></div><div><label for="city">City:</label><input type="text" id="city"></div><div><label for="county">County:</label><input type="text" id="county"></div><div><label for="postcode">Postal Code:</label><input type="text" id="postcode"></div><div><label for="country">Country:</label><input type="text" id="country"></div>