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
Formatted Address
Response JSON
Step-by-Step Implementation
Follow these steps to integrate geolocation biasing into your application:
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 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.
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 instanceconst autocomplete =newPlacesAutocomplete({containerId:'autocomplete-container',googleMapsApiKey:'YOUR_GOOGLE_MAPS_API_KEY',// Replace with your actual keyonResponse:(placeDetails)=>{
console.log(placeDetails);// Log the selected place details},onError:(error)=>{
console.error('Autocomplete Error:', error.message || error);},requestParams:{region:'GB',// Example regionincludedRegionCodes:['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 changesconst el = document.getElementById("country-select");
el.addEventListener("click", useCurrentLocation);functionuseCurrentLocation(){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>...