Places (New) Autocomplete - JavaScript Library
A flexible and customisable vanilla JavaScript library leveraging the Google Maps Places (New) Autocomplete API
It handles API loading, session tokens for cost-effective usage, fetching suggestions with debouncing, keyboard navigation, highlighting matched text, and requesting place details, allowing you to focus on integrating the results into your application.
Example
This example demonstrates how to integrate the Places (New) Autocomplete component into your application and retrieve the details of a selected place.
Basic Usage
Replace '___YOUR_API_KEY___' with your actual Google Maps API Key.
Use the onResponse callback to handle the response.
<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);
// Example: document.getElementById('address-field').value = placeDetails.formattedAddress;
// Example: document.getElementById('place-name').textContent = placeDetails.displayName;
},
onError: (error) => {
console.error('Autocomplete Error:', error.message || error);
}
});
// Optional: You can interact with the instance later
// autocomplete.clear();
// autocomplete.destroy(); // To clean up
} catch (error) {
console.error("Failed to initialize PlacesAutocomplete:", error.message);
}
});
</script>
...
<div id="autocomplete-container"></div>
...