Enhance Search with Distance from Origin

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
powered by Google

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:

  1. 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.
  2. Enable Distance Display: In the options object, set distance: true. This tells the component to calculate and show the distance for each suggestion.
  3. 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 = 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>
...