Improve Relevance with Geolocation Biasing

This example demonstrates how to use the browser's Geolocation API to bias search results towards the user's current location. By making searches location-aware, you can provide a more intuitive and faster experience. Click the "Use My Location" button to see how the setRequestParams() method makes it possible.

Enter an address or use your location to see biased results.

powered by
powered by Google

Step-by-Step Implementation

Follow these steps to integrate geolocation biasing into your application:

  1. Request User's Location: Use the navigator.geolocation.getCurrentPosition() method to ask for the user's current coordinates. It's crucial to handle both success and error cases to manage user permissions gracefully.
  2. Update Autocomplete with Location: On success, call the setRequestParams() method on your PlacesAutocomplete instance. Pass an object with an origin property containing the user's latitude and longitude. This tells the API to prioritize results closer to the user.
  3. Provide User Feedback: Keep the user informed about the process. Update the UI to show the status, such as "Getting your location...", "Location found!", or any error messages. This creates a transparent and user-friendly experience.
<script>
import { PlacesAutocomplete } from 'places-autocomplete-js';

document.addEventListener('DOMContentLoaded', () => {
  try {

    // Initialize the PlacesAutocomplete instance
    const autocomplete = new PlacesAutocomplete({
      containerId: 'autocomplete-container',
      googleMapsApiKey: 'YOUR_GOOGLE_MAPS_API_KEY', // Replace with your actual key
      onResponse: (placeDetails) => {
          console.log(placeDetails); // Log the selected place details
      },
      onError: (error) => {
          console.error('Autocomplete Error:', error.message || error);
      },
      requestParams: {
          region: 'GB', // Example region
          includedRegionCodes: ['GB'], // Example countries
      },
      options: {
          placeholder: 'Start typing your address...',
          clear_input:false // Retain input value after selection
      }
    });

  } catch (error) {
    console.error("Failed to initialize PlacesAutocomplete:", error.message);
  }

  // Get the select element and add an event listener for changes
  const el = document.getElementById("country-select");
  el.addEventListener("click", useCurrentLocation);

  function useCurrentLocation() {
      if (navigator.geolocation) {
          status = 'Getting your location...';
          navigator.geolocation.getCurrentPosition((position) => {
              const { latitude, longitude } = position.coords;
              status = "Location found! Biasing results around your position.";
              autocomplete.setRequestParams({
                  origin: {
                      lat: latitude,
                      lng: longitude
                  },
                  // You might also want to set the region based on the user's location
                  // This would require a reverse geocoding step, which is beyond this example
              });
          }, (error) => {
              status = "Error getting location: " + error.message;
              console.error(error);
          });
      } else {
          status = "Geolocation is not supported by this browser.";
      }
  });



</script>

...
<button onclick="useCurrentLocation()">Use My Location</button>
<div id="autocomplete-container"></div>
...