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
provide a more intuitive and efficient experience. Click the "Use My Location" button
to see the setRequestParams() method in action.
Enter an address or use your location to see biased results.
powered by
Step-by-Step Implementation
Follow these steps to integrate geolocation biasing into your application and create a more personalised search experience:
- 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. - Update Autocomplete with Location: On success, call the
setRequestParams()method on yourPlacesAutocompleteinstance. Pass an object with anoriginproperty containing the user's latitude and longitude. This tells the API to prioritise results closer to the user. - 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>
...