This example demonstrates how to display the straight-line distance from a predefined
origin point to each suggested address. This feature is invaluable for applications
where proximity is a key factor, such as delivery services, store locators, or booking
systems. By showing users how far a location is, you provide critical context that helps
them make informed decisions.
The library automatically calculates and displays the "as the crow flies" distance for
each suggestion, giving users an immediate sense of proximity.
powered by
Formatted Address
Response JSON
Step-by-Step Implementation
Displaying the distance from an origin is configured through a few simple options. The
library handles the distance calculation and displays it next to each suggestion
automatically.
Here’s how to set it up:
Define the Origin Point: In the requestParams, specify an origin with lat and lng coordinates. This point serves as the reference for all distance calculations.
Enable Distance Display: In the options object, set distance: true. This tells the component to calculate and show the distance for each suggestion.
Set Distance Units (Optional): You can specify the units for the distance by setting distance_units. The accepted values are 'miles' or 'km' (kilometers). If omitted, it defaults to 'km'.
<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)=>{
console.log('Place Selected:', placeDetails);},onError:(error)=>{
console.error('Autocomplete Error:', error.message || error);},options:{placeholder:'Search for places...',distance:true,// Enable distance displaydistance_units:'miles'// Display distance in miles (can also be 'km')},requestParams:{// Define the origin point for distance calculationsorigin:{lat:37.7749,// Example: San Francisco, CAlng:-122.4194},// Optional: Bias results towards a region, e.g., United Statesregion:'US',includedRegionCodes:['US']}});}catch(error){
console.error("Failed to initialize PlacesAutocomplete:", error.message);}});</script>...<div id="autocomplete-container"></div>...