Stay organized with collections
Save and categorize content based on your preferences.
This example takes user input and displays a list of place predictions. When a
selection is made place details are retrieved and the session is concluded.
lettitleElement;letresultsContainerElement;letinputElement;letnewestRequestId=0;// Add an initial request body.constrequest={input:'',locationRestriction:{west:-122.44,north:37.8,east:-122.39,south:37.78},origin:{lat:37.7893,lng:-122.4039},includedPrimaryTypes:['restaurant'],language:'en-US',region:'us',};functioninit(){titleElement=document.getElementById('title');resultsContainerElement=document.getElementById('results');inputElement=document.querySelector('input');inputElement.addEventListener('input',makeAutocompleteRequest);refreshToken(request);}asyncfunctionmakeAutocompleteRequest(inputEvent){// Reset elements and exit if an empty string is received.if(inputEvent.target.value==''){titleElement.innerText='';resultsContainerElement.replaceChildren();return;}// Add the latest char sequence to the request.request.input=inputEvent.target.value;// To avoid race conditions, store the request ID and compare after the request.constrequestId=++newestRequestId;// Fetch autocomplete suggestions and show them in a list.// @ts-ignoreconst{suggestions}=awaitgoogle.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);// If the request has been superseded by a newer request, do not render the output.if(requestId!==newestRequestId)return;titleElement.innerText=`Query predictions for "${request.input}"`;// Clear the list first.resultsContainerElement.replaceChildren();for(constsuggestionofsuggestions){constplacePrediction=suggestion.placePrediction;// Create a link for the place, add an event handler to fetch the place.consta=document.createElement('a');a.addEventListener('click',()=>{onPlaceSelected(placePrediction!.toPlace());});a.innerText=placePrediction!.text.toString();// Create a new list item element.constli=document.createElement('li');li.appendChild(a);resultsContainerElement.appendChild(li);}}// Event handler for clicking on a suggested place.asyncfunctiononPlaceSelected(place){awaitplace.fetchFields({fields:['displayName','formattedAddress'],});constplaceText=document.createTextNode(`${place.displayName}: ${place.formattedAddress}`);resultsContainerElement.replaceChildren(placeText);titleElement.innerText='Selected Place:';inputElement.value='';refreshToken(request);}// Helper function to refresh the session token.functionrefreshToken(request){// Create a new session token and add it to the request.request.sessionToken=newgoogle.maps.places.AutocompleteSessionToken();}declareglobal{interfaceWindow{init:()=>void;}}window.init=init;
lettitleElement;letresultsContainerElement;letinputElement;letnewestRequestId=0;// Add an initial request body.constrequest={input:'',locationRestriction:{west:-122.44,north:37.8,east:-122.39,south:37.78},origin:{lat:37.7893,lng:-122.4039},includedPrimaryTypes:['restaurant'],language:'en-US',region:'us',};functioninit(){titleElement=document.getElementById('title');resultsContainerElement=document.getElementById('results');inputElement=document.querySelector('input');inputElement.addEventListener('input',makeAutocompleteRequest);refreshToken(request);}asyncfunctionmakeAutocompleteRequest(inputEvent){// Reset elements and exit if an empty string is received.if(inputEvent.target.value==''){titleElement.innerText='';resultsContainerElement.replaceChildren();return;}// Add the latest char sequence to the request.request.input=inputEvent.target.value;// To avoid race conditions, store the request ID and compare after the request.constrequestId=++newestRequestId;// Fetch autocomplete suggestions and show them in a list.// @ts-ignoreconst{suggestions}=awaitgoogle.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);// If the request has been superseded by a newer request, do not render the output.if(requestId!==newestRequestId)return;titleElement.innerText=`Query predictions for "${request.input}"`;// Clear the list first.resultsContainerElement.replaceChildren();for(constsuggestionofsuggestions){constplacePrediction=suggestion.placePrediction;// Create a link for the place, add an event handler to fetch the place.consta=document.createElement('a');a.addEventListener('click',()=>{onPlaceSelected(placePrediction.toPlace());});a.innerText=placePrediction.text.toString();// Create a new list item element.constli=document.createElement('li');li.appendChild(a);resultsContainerElement.appendChild(li);}}// Event handler for clicking on a suggested place.asyncfunctiononPlaceSelected(place){awaitplace.fetchFields({fields:['displayName','formattedAddress'],});constplaceText=document.createTextNode(`${place.displayName}: ${place.formattedAddress}`);resultsContainerElement.replaceChildren(placeText);titleElement.innerText='Selected Place:';inputElement.value='';refreshToken(request);}// Helper function to refresh the session token.functionrefreshToken(request){// Create a new session token and add it to the request.request.sessionToken=newgoogle.maps.places.AutocompleteSessionToken();}window.init=init;
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */#map{height:100%;}/* * Optional: Makes the sample page fill the window. */html,body{height:100%;margin:0;padding:0;}a{cursor:pointer;text-decoration:underline;color:blue;}input{width:300px;}
<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>
</head>
<body>
<input id="input" type="text" placeholder="Search for a place..." />
<div id="title"></div>
<ul id="results"></ul>
<img
class="powered-by-google"
src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png"
alt="Powered by Google"
/>
<!--
The `defer` attribute causes the script to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises. See
https://developers.google.com/maps/documentation/javascript/load-maps-js-api
for more information.
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8&callback=init&libraries=places&v=weekly"
defer
></script>
</body>
</html>
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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-20 UTC."],[[["\u003cp\u003eThis example demonstrates using the Place Autocomplete data to provide a list of place predictions based on user input.\u003c/p\u003e\n"],["\u003cp\u003eWhen a prediction is selected, further details about the place are displayed, including its name and address.\u003c/p\u003e\n"],["\u003cp\u003eThis sample utilizes an AutocompleteSessionToken to manage the autocomplete session for optimized results.\u003c/p\u003e\n"],["\u003cp\u003eThe example is implemented using both TypeScript and JavaScript, providing flexibility for developers.\u003c/p\u003e\n"]]],[],null,["This example takes user input and displays a list of place predictions. When a\nselection is made place details are retrieved and the session is concluded.\n\nRead the\n[documentation](/maps/documentation/javascript/place-autocomplete-data). \n\nTypeScript \n\n```typescript\nlet titleElement;\nlet resultsContainerElement;\nlet inputElement;\n\nlet newestRequestId = 0;\n\n// Add an initial request body.\nconst request = {\n input: '',\n locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78 },\n origin: { lat: 37.7893, lng: -122.4039 },\n includedPrimaryTypes: ['restaurant'],\n language: 'en-US',\n region: 'us',\n};\n\nfunction init() {\n titleElement = document.getElementById('title');\n resultsContainerElement = document.getElementById('results');\n inputElement = document.querySelector('input');\n inputElement.addEventListener('input', makeAutocompleteRequest);\n refreshToken(request);\n}\n\nasync function makeAutocompleteRequest(inputEvent) {\n // Reset elements and exit if an empty string is received.\n if (inputEvent.target.value == '') {\n titleElement.innerText = '';\n resultsContainerElement.replaceChildren();\n return;\n }\n\n // Add the latest char sequence to the request.\n request.input = inputEvent.target.value;\n\n // To avoid race conditions, store the request ID and compare after the request.\n const requestId = ++newestRequestId;\n\n // Fetch autocomplete suggestions and show them in a list.\n // @ts-ignore\n const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);\n\n // If the request has been superseded by a newer request, do not render the output.\n if (requestId !== newestRequestId) return;\n\n titleElement.innerText = `Query predictions for \"${request.input}\"`;\n\n // Clear the list first.\n resultsContainerElement.replaceChildren();\n\n for (const suggestion of suggestions) {\n const placePrediction = suggestion.placePrediction;\n\n // Create a link for the place, add an event handler to fetch the place.\n const a = document.createElement('a');\n a.addEventListener('click', () =\u003e {\n onPlaceSelected(placePrediction!.toPlace());\n });\n a.innerText = placePrediction!.text.toString();\n\n // Create a new list item element.\n const li = document.createElement('li');\n li.appendChild(a);\n resultsContainerElement.appendChild(li);\n }\n}\n\n// Event handler for clicking on a suggested place.\nasync function onPlaceSelected(place) {\n await place.fetchFields({\n fields: ['displayName', 'formattedAddress'],\n });\n const placeText = document.createTextNode(`${place.displayName}: ${place.formattedAddress}`);\n resultsContainerElement.replaceChildren(placeText);\n titleElement.innerText = 'Selected Place:';\n inputElement.value = '';\n refreshToken(request);\n}\n\n// Helper function to refresh the session token.\nfunction refreshToken(request) {\n // Create a new session token and add it to the request.\n request.sessionToken = new google.maps.places.AutocompleteSessionToken();\n}\n\ndeclare global {\n interface Window {\n init: () =\u003e void;\n }\n }\n window.init = init;https://github.com/googlemaps-samples/js-api-samples/blob/eb299344a468a9a0aa2e81ca28e51bb5395341ee/samples/place-autocomplete-data-session/index.ts#L8-L98\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\nlet titleElement;\nlet resultsContainerElement;\nlet inputElement;\nlet newestRequestId = 0;\n// Add an initial request body.\nconst request = {\n input: '',\n locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78 },\n origin: { lat: 37.7893, lng: -122.4039 },\n includedPrimaryTypes: ['restaurant'],\n language: 'en-US',\n region: 'us',\n};\nfunction init() {\n titleElement = document.getElementById('title');\n resultsContainerElement = document.getElementById('results');\n inputElement = document.querySelector('input');\n inputElement.addEventListener('input', makeAutocompleteRequest);\n refreshToken(request);\n}\nasync function makeAutocompleteRequest(inputEvent) {\n // Reset elements and exit if an empty string is received.\n if (inputEvent.target.value == '') {\n titleElement.innerText = '';\n resultsContainerElement.replaceChildren();\n return;\n }\n // Add the latest char sequence to the request.\n request.input = inputEvent.target.value;\n // To avoid race conditions, store the request ID and compare after the request.\n const requestId = ++newestRequestId;\n // Fetch autocomplete suggestions and show them in a list.\n // @ts-ignore\n const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);\n // If the request has been superseded by a newer request, do not render the output.\n if (requestId !== newestRequestId)\n return;\n titleElement.innerText = `Query predictions for \"${request.input}\"`;\n // Clear the list first.\n resultsContainerElement.replaceChildren();\n for (const suggestion of suggestions) {\n const placePrediction = suggestion.placePrediction;\n // Create a link for the place, add an event handler to fetch the place.\n const a = document.createElement('a');\n a.addEventListener('click', () =\u003e {\n onPlaceSelected(placePrediction.toPlace());\n });\n a.innerText = placePrediction.text.toString();\n // Create a new list item element.\n const li = document.createElement('li');\n li.appendChild(a);\n resultsContainerElement.appendChild(li);\n }\n}\n// Event handler for clicking on a suggested place.\nasync function onPlaceSelected(place) {\n await place.fetchFields({\n fields: ['displayName', 'formattedAddress'],\n });\n const placeText = document.createTextNode(`${place.displayName}: ${place.formattedAddress}`);\n resultsContainerElement.replaceChildren(placeText);\n titleElement.innerText = 'Selected Place:';\n inputElement.value = '';\n refreshToken(request);\n}\n// Helper function to refresh the session token.\nfunction refreshToken(request) {\n // Create a new session token and add it to the request.\n request.sessionToken = new google.maps.places.AutocompleteSessionToken();\n}\nwindow.init = init;https://github.com/googlemaps-samples/js-api-samples/blob/eb299344a468a9a0aa2e81ca28e51bb5395341ee/dist/samples/place-autocomplete-data-session/docs/index.js#L7-L77\n```\n| **Note:** The JavaScript is compiled from the TypeScript snippet.\n\nCSS \n\n```css\n/* \n * Always set the map height explicitly to define the size of the div element\n * that contains the map. \n */\n#map {\n height: 100%;\n}\n\n/* \n * Optional: Makes the sample page fill the window. \n */\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\na {\n cursor: pointer;\n text-decoration: underline;\n color: blue;\n}\n\ninput {\n width: 300px;\n}\nhttps://github.com/googlemaps-samples/js-api-samples/blob/eb299344a468a9a0aa2e81ca28e51bb5395341ee/dist/samples/place-autocomplete-data-session/docs/style.css#L7-L34\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003ePlace Autocomplete Data API Session\u003c/title\u003e\n\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" /\u003e\n \u003cscript type=\"module\" src=\"./index.js\"\u003e\u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cinput id=\"input\" type=\"text\" placeholder=\"Search for a place...\" /\u003e\n \u003cdiv id=\"title\"\u003e\u003c/div\u003e\n \u003cul id=\"results\"\u003e\u003c/ul\u003e\n \u003cimg\n class=\"powered-by-google\"\n src=\"https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png\"\n alt=\"Powered by Google\"\n /\u003e\n\n \u003c!-- \n The `defer` attribute causes the script to execute after the full HTML\n document has been parsed. For non-blocking uses, avoiding race conditions,\n and consistent behavior across browsers, consider loading using Promises. See\n https://developers.google.com/maps/documentation/javascript/load-maps-js-api\n for more information.\n --\u003e\n \u003cscript\n src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8&callback=init&libraries=places&v=weekly\"\n defer\n \u003e\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps-samples/js-api-samples/blob/eb299344a468a9a0aa2e81ca28e51bb5395341ee/dist/samples/place-autocomplete-data-session/docs/index.html#L8-L39\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps-samples/js-api-samples/tree/main/dist/samples/place-autocomplete-data-session/jsfiddle)\n\nClone Sample\n\n\nGit and Node.js are required to run this sample locally. Follow these [instructions](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) to install Node.js and NPM. The following commands clone, install dependencies and start the sample application. \n\n git clone https://github.com/googlemaps-samples/js-api-samples.git\n cd samples/place-autocomplete-data-session\n npm i\n npm start"]]