Display Distance from Origin
This example shows how to display the straight-line distance from a predefined origin to each suggested address.
To enable this feature:
- Set
options.distance = true
. - Optionally, set
options.distance_units
to'miles'
(defaults to'km'
). - Provide an origin (latitude/longitude) in the
requestParams
object.
The library automatically calculates and displays the distance for each suggestion. Note that this is a straight-line ("as the crow flies") distance, not a driving distance.
powered by

Implementation:
<script>
import { PlacesAutocomplete } from 'places-autocomplete-js';
document.addEventListener('DOMContentLoaded', () => {
try {
const autocomplete = new PlacesAutocomplete({
containerId: 'autocomplete-container',
googleMapsApiKey: 'YOUR_GOOGLE_MAPS_API_KEY', // Replace with your actual key
onResponse: (placeDetails) => {
console.log('Place Selected:', placeDetails);
},
onError: (error) => {
console.error('Autocomplete Error:', error.message || error);
},
options:{
placeholder: 'Search for places...',
distance: true, // Enable distance display
distance_units: 'miles' // Display distance in miles (can also be 'km')
},
requestParams: {
// Define the origin point for distance calculations
origin: {
lat: 37.7749, // Example: San Francisco, CA
lng: -122.4194
},
// Optional: Bias results towards a region, e.g., United States
region: 'US',
includedRegionCodes: ['US']
}
});
} catch (error) {
console.error("Failed to initialize PlacesAutocomplete:", error.message);
}
});
</script>
...
<div id="autocomplete-container"></div>
...