Places (New) Autocomplete - JavaScript Library

A flexible and customisable vanilla JavaScript library leveraging the Google Maps Places (New) Autocomplete API . This library provides a user-friendly way to search for and retrieve detailed address information in any web application.

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.

You can find the full documentation about this library in the GitHub page .

Example

This example demonstrates how to integrate the Places (New) Autocomplete component into your application and retrieve the details of a selected place.

powered by
powered by Google

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
    // autocomplete.setFetchFields(['types']); // Update fields to fetch
    // autocomplete.getFetchFields(); // Get current fetch fields
    // autocomplete.setRequestParams({origin: { lat: 48.8566, lng: 2.3522 }}); // Set new request parameters
    // autocomplete.getRequestParams(); // Get current request parameters
    // autocomplete.setOptions({ placeholder: 'Search for a place...' }); // Update options
    // autocomplete.getOptions(); // Get current options

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

</script>

...
<div id="autocomplete-container"></div>
...