Displaying Distance from a Fixed Origin

This example demonstrates how to display the distance from a predefined origin point to each suggested address.

To enable this feature:

  1. Set options.distance = true.
  2. Optionally, specify options.distance_units (defaults to 'km', can be 'miles').
  3. Provide an origin (latitude/longitude) in the requestParams object. The Google Places API will then calculate the distance in meters to each prediction.

The library will automatically format and display this distance alongside each suggestion. Note that this is a straight-line distance, not a driving distance.

powered by
powered by Google

Example Code:

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