Places UI Kit: A ready-to-use library that provides room for customization and low-code development. Try it out, and share your input on your UI Kit experience.

Place Autocomplete Data Sessions

  • This example demonstrates using the Place Autocomplete data to provide a list of place predictions based on user input.

  • When a prediction is selected, further details about the place are displayed, including its name and address.

  • This sample utilizes an AutocompleteSessionToken to manage the autocomplete session for optimized results.

  • The example is implemented using both TypeScript and JavaScript, providing flexibility for developers.

This example takes user input and displays a list of place predictions. When a selection is made place details are retrieved, a marker is displayed, and the session is concluded.

The following concepts are demonstrated:

  • Calling fetchAutocompleteSuggestions()
  • Using session tokens to group a user query with the final Place Details request. based on user queries and showing a list of predicted places in response.
  • Retrieving place details for the selected place and displaying a marker.
  • Using control slotting to nest UI elements in the gmp-map element.

Read the documentation.

[フレーム]

TypeScript

constmapElement=document.querySelector('gmp-map')asgoogle.maps.MapElement;
letinnerMap:google.maps.Map;
letmarker:google.maps.marker.AdvancedMarkerElement;
lettitleElement=document.querySelector('.title')asHTMLElement;
letresultsContainerElement=document.querySelector('.results')asHTMLElement;
letinputElement=document.querySelector('input')asHTMLInputElement;
lettokenStatusElement=document.querySelector('.token-status')asHTMLElement;
letnewestRequestId=0;
lettokenCount=0;
// Create an initial request body.
constrequest:google.maps.places.AutocompleteRequest={
input:'',
includedPrimaryTypes:[
'restaurant',
'cafe',
'museum',
'park',
'botanical_garden',
],
};
asyncfunctioninit(){
awaitgoogle.maps.importLibrary('maps');
innerMap=mapElement.innerMap;
innerMap.setOptions({
mapTypeControl:false,
});
// Update request center and bounds when the map bounds change.
google.maps.event.addListener(innerMap,'bounds_changed',async()=>{
request.locationRestriction=innerMap.getBounds();
request.origin=innerMap.getCenter();
});
inputElement.addEventListener('input',makeAutocompleteRequest);
}
asyncfunctionmakeAutocompleteRequest(inputEvent){
// To avoid race conditions, store the request ID and compare after the request.
constrequestId=++newestRequestId;
const{AutocompleteSuggestion}=(awaitgoogle.maps.importLibrary(
'places'
))asgoogle.maps.PlacesLibrary;
if(!inputEvent.target?.value){
titleElement.textContent='';
resultsContainerElement.replaceChildren();
return;
}
// Add the latest char sequence to the request.
request.input=(inputEvent.targetasHTMLInputElement).value;
// Fetch autocomplete suggestions and show them in a list.
const{suggestions}=
awaitAutocompleteSuggestion.fetchAutocompleteSuggestions(request);
// If the request has been superseded by a newer request, do not render the output.
if(requestId!==newestRequestId)return;
titleElement.innerText=`Place predictions for "${request.input}"`;
// Clear the list first.
resultsContainerElement.replaceChildren();
for(constsuggestionofsuggestions){
constplacePrediction=suggestion.placePrediction;
if(!placePrediction){
continue;
}
// Create a link for the place, add an event handler to fetch the place.
// We are using a button element to take advantage of its a11y capabilities.
constplaceButton=document.createElement('button');
placeButton.addEventListener('click',()=>{
onPlaceSelected(placePrediction.toPlace());
});
placeButton.textContent=placePrediction.text.toString();
placeButton.classList.add('place-button');
// Create a new list item element.
constli=document.createElement('li');
li.appendChild(placeButton);
resultsContainerElement.appendChild(li);
}
}
// Event handler for clicking on a suggested place.
asyncfunctiononPlaceSelected(place:google.maps.places.Place){
const{AdvancedMarkerElement}=(awaitgoogle.maps.importLibrary(
'marker'
))asgoogle.maps.MarkerLibrary;
awaitplace.fetchFields({
fields:['displayName','formattedAddress','location'],
});
resultsContainerElement.textContent=`${place.displayName}: ${place.formattedAddress}`;
titleElement.textContent='Selected Place:';
inputElement.value='';
awaitrefreshToken();
// Remove the previous marker, if it exists.
if(marker){
marker.remove();
}
// Create a new marker.
marker=newAdvancedMarkerElement({
map:innerMap,
position:place.location,
title:place.displayName,
});
// Center the map on the selected place.
if(place.location){
innerMap.setCenter(place.location);
innerMap.setZoom(15);
}
}
// Helper function to refresh the session token.
asyncfunctionrefreshToken(){
const{AutocompleteSessionToken}=(awaitgoogle.maps.importLibrary(
'places'
))asgoogle.maps.PlacesLibrary;
// Increment the token counter.
tokenCount++;
// Create a new session token and add it to the request.
request.sessionToken=newAutocompleteSessionToken();
tokenStatusElement.textContent=`Session token count: ${tokenCount}`;
}
init();

JavaScript

constmapElement=document.querySelector('gmp-map');
letinnerMap;
letmarker;
lettitleElement=document.querySelector('.title');
letresultsContainerElement=document.querySelector('.results');
letinputElement=document.querySelector('input');
lettokenStatusElement=document.querySelector('.token-status');
letnewestRequestId=0;
lettokenCount=0;
// Create an initial request body.
constrequest={
input:'',
includedPrimaryTypes:[
'restaurant',
'cafe',
'museum',
'park',
'botanical_garden',
],
};
asyncfunctioninit(){
awaitgoogle.maps.importLibrary('maps');
innerMap=mapElement.innerMap;
innerMap.setOptions({
mapTypeControl:false,
});
// Update request center and bounds when the map bounds change.
google.maps.event.addListener(innerMap,'bounds_changed',async()=>{
request.locationRestriction=innerMap.getBounds();
request.origin=innerMap.getCenter();
});
inputElement.addEventListener('input',makeAutocompleteRequest);
}
asyncfunctionmakeAutocompleteRequest(inputEvent){
// To avoid race conditions, store the request ID and compare after the request.
constrequestId=++newestRequestId;
const{AutocompleteSuggestion}=(awaitgoogle.maps.importLibrary('places'));
if(!inputEvent.target?.value){
titleElement.textContent='';
resultsContainerElement.replaceChildren();
return;
}
// Add the latest char sequence to the request.
request.input=inputEvent.target.value;
// Fetch autocomplete suggestions and show them in a list.
const{suggestions}=awaitAutocompleteSuggestion.fetchAutocompleteSuggestions(request);
// If the request has been superseded by a newer request, do not render the output.
if(requestId!==newestRequestId)
return;
titleElement.innerText=`Place predictions for "${request.input}"`;
// Clear the list first.
resultsContainerElement.replaceChildren();
for(constsuggestionofsuggestions){
constplacePrediction=suggestion.placePrediction;
if(!placePrediction){
continue;
}
// Create a link for the place, add an event handler to fetch the place.
// We are using a button element to take advantage of its a11y capabilities.
constplaceButton=document.createElement('button');
placeButton.addEventListener('click',()=>{
onPlaceSelected(placePrediction.toPlace());
});
placeButton.textContent=placePrediction.text.toString();
placeButton.classList.add('place-button');
// Create a new list item element.
constli=document.createElement('li');
li.appendChild(placeButton);
resultsContainerElement.appendChild(li);
}
}
// Event handler for clicking on a suggested place.
asyncfunctiononPlaceSelected(place){
const{AdvancedMarkerElement}=(awaitgoogle.maps.importLibrary('marker'));
awaitplace.fetchFields({
fields:['displayName','formattedAddress','location'],
});
resultsContainerElement.textContent=`${place.displayName}: ${place.formattedAddress}`;
titleElement.textContent='Selected Place:';
inputElement.value='';
awaitrefreshToken();
// Remove the previous marker, if it exists.
if(marker){
marker.remove();
}
// Create a new marker.
marker=newAdvancedMarkerElement({
map:innerMap,
position:place.location,
title:place.displayName,
});
// Center the map on the selected place.
if(place.location){
innerMap.setCenter(place.location);
innerMap.setZoom(15);
}
}
// Helper function to refresh the session token.
asyncfunctionrefreshToken(){
const{AutocompleteSessionToken}=(awaitgoogle.maps.importLibrary('places'));
// Increment the token counter.
tokenCount++;
// Create a new session token and add it to the request.
request.sessionToken=newAutocompleteSessionToken();
tokenStatusElement.textContent=`Session token count: ${tokenCount}`;
}
init();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
gmp-map{
height:100%;
}
/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body{
height:100%;
margin:0;
padding:0;
}
.place-button{
height:3rem;
width:100%;
background-color:transparent;
text-align:left;
border:none;
cursor:pointer;
}
.place-button:focus-visible{
outline:2pxsolid#0056b3;
border-radius:2px;
}
.input{
width:300px;
font-size:small;
margin-bottom:1rem;
}
/* Styles for the floating panel */
.controls{
background-color:#fff;
border-radius:8px;
box-shadow:02px6pxrgba(0,0,0,0.3);
font-family:sans-serif;
font-size:small;
margin:12px;
padding:1rem;
}
.title{
font-weight:bold;
margin-top:1rem;
margin-bottom:0.5rem;
}
.results{
list-style-type:none;
margin:0;
padding:0;
}
.resultsli:not(:last-child){
border-bottom:1pxsolid#ddd;
}
.resultsli:hover{
background-color:#eee;
}

HTML

<html>
 <head>
 <title>Place Autocomplete Data API Session</title>
 <link rel="stylesheet" type="text/css" href="./style.css" />
 <script type="module" src="./index.js"></script>
 <!-- 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>
 </head>
 <body>
 <gmp-map center="37.7893, -122.4039" zoom="12" map-id="DEMO_MAP_ID">
 <div class="controls" slot="control-inline-start-block-start">
 <input
 type="text"
 class="input"
 placeholder="Search for a place..."
 autocomplete="off" /><!-- Turn off the input's own autocomplete (not supported by all browsers).-->
 <div class="token-status"></div>
 <div class="title"></div>
 <ol class="results"></ol>
 </div>
 </gmp-map>
 </body>
</html>

Try Sample

Clone Sample

Git and Node.js are required to run this sample locally. Follow these instructions to install Node.js and NPM. The following commands clone, install dependencies and start the sample application.

gitclonehttps://github.com/googlemaps-samples/js-api-samples.git
cdsamples/place-autocomplete-data-session
npmi
npmstart

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年11月21日 UTC.