Basic Place Autocomplete Element

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.

Get place details

To get the place ID for the selected place, add a gmp-select listener to the PlaceAutocompleteElement, as shown in the following example:

// Add the gmp-select listener, and display the results.
  placeAutocomplete.addEventListener('gmp-select', async ({ place }) => {
      await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
      selectedPlaceTitle.textContent = 'Selected Place:';
      selectedPlaceInfo.textContent = JSON.stringify(place.toJSON(), /* replacer */ null, /* space */ 2);
  });
  

In the preceding example, the event listener returns an object of Place class. Call place.fetchFields() to get the Place Details data fields needed for your application.

The listener in the next example requests place information and displays it on a map.

  // Add the gmp-placeselect listener, and display the results on the map.
  //@ts-ignore
  placeAutocomplete.addEventListener('gmp-select', async ({ place }) => {
      await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
      // If the place has a geometry, then present it on a map.
      if (place.viewport) {
          map.fitBounds(place.viewport);
      }
      else {
          map.setCenter(place.location);
          map.setZoom(17);
      }
      let content = '<div id="infowindow-content">' +
          '<span id="place-displayname" class="title">' + place.displayName + '</span><br />' +
          '<span id="place-address">' + place.formattedAddress + '</span>' +
          '</div>';
      updateInfoWindow(content, place.location);
      marker.position = place.location;
  });
  

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

JavaScript

const mapContainer = document.getElementById("map-container");
const autocompleteElement = document.querySelector('gmp-basic-place-autocomplete');
const detailsElement = document.querySelector('gmp-place-details-compact');
const mapElement = document.querySelector('gmp-map');
const advancedMarkerElement = document.querySelector('gmp-advanced-marker');
let center = { lat: 40.749933, lng: -73.98633 }; // New York City
async function initMap() {
    //@ts-ignore
    const { BasicPlaceAutocompleteElement, PlaceDetailsElement } = await google.maps.importLibrary('places');
    //@ts-ignore
    const { AdvancedMarkerElement } = await google.maps.importLibrary('marker');
    //@ts-ignore
    const { LatLngBounds } = await google.maps.importLibrary('core');
    // Set the initial map location and autocomplete location bias
    mapElement.center = center;
    autocompleteElement.locationBias = center;
    // Get the underlying google.maps.Map object to add listeners
    const map = mapElement.innerMap;
    // Add the listener tochange locationBias to locationRestriction when the map moves
    map.addListener('bounds_changed', () => {
        autocompleteElement.locationBias = null;
        autocompleteElement.locationRestriction = map.getBounds();
        console.log("bias changed to restriction");
    });
    // Add the listener to update the Place Request element when the user selects a prediction
    autocompleteElement.addEventListener('gmp-select', async (event) => {
        const placeDetailsRequest = document.querySelector('gmp-place-details-place-request');
        placeDetailsRequest.place = event.place.id;
    });
    // Add the listener to update the marker when the Details element loads
    detailsElement.addEventListener('gmp-load', async () => {
        const location = detailsElement.place.location;
        detailsElement.style.display = "block";
        advancedMarkerElement.position = location;
        advancedMarkerElement.content = detailsElement;
        if (detailsElement.place.viewport) {
            map.fitBounds(detailsElement.place.viewport);
        }
        else {
            map.setCenter(location);
            map.setZoom(17);
        }
    });
}
initMap();

CSS

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

#map-container {
  display: flex;
  flex-direction: row;
  height: 100%;
}

#gmp-map {
  height: 100%;
}

gmp-basic-place-autocomplete {
  position: absolute;
  height: 50px;
  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;
  max-height: 300px;
  border: none;
  padding: 0;
  margin: 0;
  position: absolute;
  transform: translate(calc(-180px), calc(-215px)); 
  box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.2); 
  color-scheme: light;
}

/* This creates the pointer attached to the bottom of the element. */
gmp-place-details-compact::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 16px solid transparent;
  border-right: 16px solid transparent;
  border-top: 20px solid var(--gmp-mat-color-surface, light-dark(white, black));
}

HTML

<html>
  <head>
    <title>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">
      <gmp-basic-place-autocomplete></gmp-basic-place-autocomplete>
      <gmp-place-details-compact orientation="horizontal">
        <gmp-place-details-place-request></gmp-place-details-place-request>
        <gmp-place-all-content></gmp-place-all-content>
      </gmp-place-details-compact>
      <gmp-map zoom="14" map-id="DEMO_MAP_ID">
         <gmp-advanced-marker></gmp-advanced-marker> 
      </gmp-map>
    </div>

    <!-- 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