Basic Place Autocomplete Element

Select platform: Android iOS JavaScript

The BasicPlaceAutocompleteElement creates a text input field, supplies place predictions in a UI pick list, and returns a place ID for the selected place.

In contrast to the PlaceAutocompleteElement, the simplified Basic Place Autocomplete element clears the input field when a user selects a place prediction, and it also returns a Place object that contains only the place ID, rather than a PlacePrediction object. Use this Place ID with a Places UI Kit Details element to get additional place details.

Prerequisites

To use the Basic Place Autocomplete element, you must enable "Places UI Kit" on your Google Cloud project. See Get started for details.

Add a Basic Place Autocomplete element

The Basic Place Autocomplete element creates a text input field, supplies place predictions in a UI pick list, and returns a place ID in response to a user selection using the gmp-select event. This section shows you how to add a Basic Autocomplete element to a web page or map.

Add a Basic Autocomplete element to a web page

To add the BasicAutocomplete element to a web page, create a new google.maps.places.BasicPlaceAutocompleteElement, and append it to the page as shown in the following example:

// Request needed libraries.
const {BasicPlaceAutocompleteElement} = await google.maps.importLibrary('places');
// Create the input HTML element, and append it.
const placeAutocomplete = new BasicPlaceAutocompleteElement();
document.body.appendChild(placeAutocomplete);

Add a Basic Autocomplete element to a map

To add a Basic Autocomplete element to a map, create a new BasicPlaceAutocompleteElement instance, append it to a div, and push it onto the map as a custom control, as shown in the following example:

  const placeAutocomplete = new google.maps.places.BasicPlaceAutocompleteElement();
  placeAutocomplete.id = 'place-autocomplete-input';
  placeAutocomplete.locationBias = center;
  const card = document.getElementById('place-autocomplete-card');
  card.appendChild(placeAutocomplete);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

Constrain Autocomplete predictions

By default, Basic Place Autocomplete presents all place types, biased for predictions near the user's location. Set BasicPlaceAutocompleteElementOptions to present more relevant predictions, by restricting or biasing results.

Restricting results causes the Basic Autocomplete element to ignore any results that are outside the restriction area. A common practice is to restrict results to the map bounds. Biasing results makes the BasicAutocomplete element show results within the specified area, but some matches may be outside of that area.

If you don't supply any bounds or a map viewport, the API will attempt to detect the user's location from their IP address, and will bias the results to that location. Set bounds whenever possible. Otherwise, different users may receive different predictions. Also, to generally improve predictions it is important to provide a sensible viewport, such as one that you set by panning or zooming on the map, or a developer-set viewport based on device location and radius. When a radius is not available, 5km is considered a sensible default for the Basic Place Autocomplete element. Don't set a viewport with zero radius (a single point), a viewport that is only a few meters across (less than 100m.), or a viewport that spans the globe.

Restrict place search by country

To restrict place search to one or more specific countries, use the includedRegionCodes property to specify the country code(s) as shown in the following snippet:

const pac = new google.maps.places.BasicPlaceAutocompleteElement({
  includedRegionCodes: ['us', 'au'],
});

Restrict place search to map bounds

To restrict place search to a map's bounds, use the locationRestrictions property to add the bounds, as shown in the following snippet:

const pac = new google.maps.places.BasicPlaceAutocompleteElement({
  locationRestriction: map.getBounds(),
});

When restricting to map bounds, be sure to add a listener to update the bounds when they change:

map.addListener('bounds_changed', () => {
  autocomplete.locationRestriction = map.getBounds();
});

To remove the locationRestriction, set it to null.

Bias place search results

Bias place search results to a circle area by using the locationBias property, and passing a radius, as shown here:

const autocomplete = new google.maps.places.BasicPlaceAutocompleteElement({
  locationBias: {radius: 100, center: {lat: 50.064192, lng: -130.605469}},
});

To remove the locationBias, set it to null.

Restrict place search results to certain types

Restrict place search results to certain types of places by using the includedPrimaryTypes property, and specifying one or more types, as shown here:

const autocomplete = new google.maps.places.BasicPlaceAutocompleteElement({
  includedPrimaryTypes: ['establishment'],
});

For a complete list of supported types, see Place type tables A and B.

Configure the Place Request element

Add a listener to update the Place Request element when the user selects a prediction:

// Event listener for when a place is selected from the autocomplete list.
placeAutocompleteElement.addEventListener('gmp-select', (event) => {
    // Reset marker and InfoWindow, and prepare the details element.
    placeDetailsParent.appendChild(placeDetailsElement);
    advancedMarkerElement.position = null;
    infoWindow.close();
    // Request details for the selected place.
    const placeDetailsRequest = placeDetailsElement.querySelector('gmp-place-details-place-request');
    placeDetailsRequest.place = event.place.id;
});

This example shows you how to add a Basic Autocomplete element to a Google map.

JavaScript

const placeAutocompleteElement = document.querySelector('gmp-basic-place-autocomplete');
const placeDetailsElement = document.querySelector('gmp-place-details-compact');
const placeDetailsParent = placeDetailsElement.parentElement;
const mapDiv = document.getElementById('map-container');
const center = { lat: 40.749933, lng: -73.98633 }; // New York City
async function initMap() {
    // Asynchronously load required libraries from the Google Maps JS API.
    await google.maps.importLibrary('places');
    const { AdvancedMarkerElement } = await google.maps.importLibrary('marker');
    const { Map, InfoWindow } = await google.maps.importLibrary('maps');
    // Set the initial location bias for the autocomplete element.
    placeAutocompleteElement.locationBias = center;
    // Create the map object with specified options.
    const map = new Map(mapDiv, {
        zoom: 12,
        center: center,
        mapId: 'DEMO_MAP_ID',
        clickableIcons: false,
        mapTypeControl: false,
        streetViewControl: false,
    });
    // Create an advanced marker to show the location of a selected place.
    const advancedMarkerElement = new AdvancedMarkerElement({
        map: map,
    });
    // Create an InfoWindow to hold the place details component.
    const infoWindow = new InfoWindow({
        minWidth: 360,
        disableAutoPan: true,
        closeButton: false,
        headerDisabled: true,
        pixelOffset: new google.maps.Size(0, -10),
    });
    // Event listener for when a place is selected from the autocomplete list.
    placeAutocompleteElement.addEventListener('gmp-select', (event) => {
        // Reset marker and InfoWindow, and prepare the details element.
        placeDetailsParent.appendChild(placeDetailsElement);
        advancedMarkerElement.position = null;
        infoWindow.close();
        // Request details for the selected place.
        const placeDetailsRequest = placeDetailsElement.querySelector('gmp-place-details-place-request');
        placeDetailsRequest.place = event.place.id;
    });
    // Event listener for when the place details have finished loading.
    placeDetailsElement.addEventListener('gmp-load', () => {
        const location = placeDetailsElement.place.location;
        // Position the marker and open the InfoWindow at the place's location.
        advancedMarkerElement.position = location;
        infoWindow.setContent(placeDetailsElement);
        infoWindow.open({
            map,
            anchor: advancedMarkerElement,
        });
        map.setCenter(location);
        placeDetailsElement.focus();
    });
    // Event listener to close the InfoWindow when the map is clicked.
    map.addListener('click', () => {
        infoWindow.close();
        advancedMarkerElement.position = null;
    });
    // Event listener for when the map finishes moving (panning or zooming).
    map.addListener('idle', () => {
        const newCenter = map.getCenter();
        // Update the autocomplete's location bias to a 10km radius around the new map center.
        placeAutocompleteElement.locationBias = new google.maps.Circle({
            center: {
                lat: newCenter.lat(),
                lng: newCenter.lng(),
            },
            radius: 10000, // 10km in meters
        });
    });
}
initMap();

CSS

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map-container {
  height: 100%;
}

gmp-basic-place-autocomplete {
  position: absolute;
  height: 50px;
  width: 500px;
  top: 10px;
  left: 10px;
  z-index: 1;
  box-shadow: 2px 2px 5px 0px rgba(0, 0, 0, 0. 2);
  color-scheme: light;
  border-radius: 10px;
}

gmp-place-details-compact {
  width: 360px;
  min-width: 300px;
  max-height: 300px;
  border: none;
  background-color: #ffffff;
  color-scheme: light;
}

HTML

<html>
  <head>
    <title>Basic Place Autocomplete map</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map-container"></div>
    <gmp-basic-place-autocomplete
      slot="control-inline-start-block-start"
    ></gmp-basic-place-autocomplete>
    <gmp-place-details-compact orientation="horizontal">
      <gmp-place-details-place-request></gmp-place-details-place-request>
      <gmp-place-standard-content></gmp-place-standard-content>
    </gmp-place-details-compact>

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script>
  </body>
</html>

Try Sample