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:

  1. Set options.distance = true.
  2. Optionally, set options.distance_units to 'miles' (defaults to 'km').
  3. 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
powered by Google

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