Skip to content

Commit fb93e52

Browse files
committed
feat: Adds Place AC session example; adds fixes for b/395793115.
1 parent 04249d3 commit fb93e52

File tree

9 files changed

+334
-4
lines changed

9 files changed

+334
-4
lines changed

samples/new1.sh

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@
1212
# 3. ./new1.sh
1313

1414
# AUTHOR: Update these values!
15-
NAME="map-simple" # The name of the folder to create (for example "map-simple").
16-
REGION_TAG="maps_map_simple" # The region tag to use for the JSHTML (for example "maps_map_simple").
17-
TITLE="Simple map" # The title of the example.
18-
API_LOADER="api_loader_dynamic" # The type of loader to use (api_loader_dynamic or api_loader_default).
15+
NAME="place-autocomplete-data-session" # The name of the folder to create (for example "map-simple").
16+
REGION_TAG="maps_place_autocomplete_data_session" # The region tag to use for the JSHTML (for example "maps_map_simple").
17+
TITLE="Place Autocomplete Data API Session" # The title of the example.
18+
API_LOADER="api_loader_default" # The type of loader to use (api_loader_dynamic or api_loader_default).
1919

2020
# Path to the source folder for the repo archive; substitute with your own path.
2121
INPUT_DIR=/Users/wfrench/Downloads/js-samples-main
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Google Maps JavaScript Sample
2+
3+
This sample is generated from @googlemaps/js-samples located at
4+
https://github.com/googlemaps-samples/js-api-samples.
5+
6+
## Setup
7+
8+
### Before starting run:
9+
10+
`npm i`
11+
12+
### Run an example on a local web server
13+
14+
First `cd` to the folder for the sample to run, then:
15+
16+
`npm start`
17+
18+
### Build an individual example
19+
20+
From `samples/`:
21+
22+
`npm run build --workspace=sample-name/`
23+
24+
### Build all of the examples.
25+
26+
From `samples/`:
27+
28+
`npm run build-all`
29+
30+
## Feedback
31+
32+
For feedback related to this sample, please open a new issue on
33+
[GitHub](https://github.com/googlemaps-samples/js-api-samples/issues).
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<!doctype html>
2+
<!--
3+
@license
4+
Copyright 2019 Google LLC. All Rights Reserved.
5+
SPDX-License-Identifier: Apache-2.0
6+
-->
7+
<!-- [START maps_place_autocomplete_data_session] -->
8+
<html>
9+
<head>
10+
<title>Place Autocomplete Data API Session</title>
11+
12+
<link rel="stylesheet" type="text/css" href="./style.css" />
13+
<script type="module" src="./index.js"></script>
14+
</head>
15+
<body>
16+
<!-- // [START maps_place_autocomplete_data_session_html] -->
17+
<input id="input" type="text" placeholder="Search for a place..." />
18+
<div id="title"></div>
19+
<ul id="results"></ul>
20+
<img
21+
class="powered-by-google"
22+
src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png"
23+
alt="Powered by Google"
24+
/>
25+
<!-- // [END maps_place_autocomplete_data_session_html] -->
26+
27+
<!--
28+
The `defer` attribute causes the script to execute after the full HTML
29+
document has been parsed. For non-blocking uses, avoiding race conditions,
30+
and consistent behavior across browsers, consider loading using Promises. See
31+
https://developers.google.com/maps/documentation/javascript/load-maps-js-api
32+
for more information.
33+
-->
34+
<script
35+
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=init&libraries=places&v=weekly"
36+
defer
37+
></script>
38+
</body>
39+
</html>
40+
<!-- [END maps_place_autocomplete_data_session] -->
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* @license
3+
* Copyright 2024 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
// [START maps_place_autocomplete_data_session]
7+
let title;
8+
let results;
9+
let input;
10+
let token;
11+
// Add an initial request body.
12+
let request = {
13+
input: "",
14+
locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78 },
15+
origin: { lat: 37.7893, lng: -122.4039 },
16+
includedPrimaryTypes: ["restaurant"],
17+
language: "en-US",
18+
region: "us",
19+
sessionToken: null,
20+
};
21+
async function init() {
22+
title = document.getElementById('title');
23+
results = document.getElementById('results');
24+
input = document.querySelector("input");
25+
input.addEventListener("input", makeAcRequest);
26+
await refreshToken(); // Await the refreshToken call here.
27+
}
28+
async function makeAcRequest(input) {
29+
// Reset elements and exit if an empty string is received.
30+
if (input.target.value == '') {
31+
title.innerText = '';
32+
results.replaceChildren();
33+
return;
34+
}
35+
// Add the latest char sequence to the request.
36+
request.input = input.target.value;
37+
await refreshToken(); //refresh the token before each request.
38+
// Fetch autocomplete suggestions and show them in a list.
39+
// @ts-ignore
40+
const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);
41+
title.innerText = 'Query predictions for "' + request.input + '"';
42+
// Clear the list first.
43+
results.replaceChildren();
44+
for (const suggestion of suggestions) {
45+
const placePrediction = suggestion.placePrediction;
46+
// Create a link for the place, add an event handler to fetch the place.
47+
const a = document.createElement('a');
48+
a.addEventListener('click', () => {
49+
onPlaceSelected(placePrediction.toPlace());
50+
});
51+
a.innerText = placePrediction.text.toString();
52+
// Create a new list element.
53+
const li = document.createElement('li');
54+
li.appendChild(a);
55+
results.appendChild(li);
56+
}
57+
}
58+
// Event handler for clicking on a suggested place.
59+
async function onPlaceSelected(place) {
60+
await place.fetchFields({
61+
fields: ['displayName', 'formattedAddress'],
62+
});
63+
let placeText = document.createTextNode(place.displayName + ': ' + place.formattedAddress);
64+
results.replaceChildren(placeText);
65+
title.innerText = 'Selected Place:';
66+
input.value = '';
67+
await refreshToken();
68+
}
69+
// Helper function to refresh the session token.
70+
async function refreshToken() {
71+
// Create a new session token and add it to the request.
72+
token = new google.maps.places.AutocompleteSessionToken();
73+
request.sessionToken = token;
74+
}
75+
window.init = init;
76+
export {};
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/**
2+
* @license
3+
* Copyright 2024 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
// [START maps_place_autocomplete_data_session]
8+
let title;
9+
let results;
10+
let input;
11+
let token;
12+
13+
// Add an initial request body.
14+
let request = {
15+
input: "",
16+
locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78 },
17+
origin: { lat: 37.7893, lng: -122.4039 },
18+
includedPrimaryTypes: ["restaurant"],
19+
language: "en-US",
20+
region: "us",
21+
sessionToken: null,
22+
};
23+
24+
async function init() {
25+
title = document.getElementById('title');
26+
results = document.getElementById('results');
27+
input = document.querySelector("input");
28+
input.addEventListener("input", makeAcRequest);
29+
await refreshToken(); // Await the refreshToken call here.
30+
}
31+
32+
async function makeAcRequest(input) {
33+
// Reset elements and exit if an empty string is received.
34+
if (input.target.value == '') {
35+
title.innerText = '';
36+
results.replaceChildren();
37+
return;
38+
}
39+
40+
// Add the latest char sequence to the request.
41+
request.input = input.target.value;
42+
await refreshToken(); //refresh the token before each request.
43+
44+
// Fetch autocomplete suggestions and show them in a list.
45+
// @ts-ignore
46+
const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);
47+
48+
title.innerText = 'Query predictions for "' + request.input + '"';
49+
50+
// Clear the list first.
51+
results.replaceChildren();
52+
53+
for (const suggestion of suggestions) {
54+
const placePrediction = suggestion.placePrediction;
55+
56+
// Create a link for the place, add an event handler to fetch the place.
57+
const a = document.createElement('a');
58+
a.addEventListener('click', () => {
59+
onPlaceSelected(placePrediction!.toPlace());
60+
});
61+
a.innerText = placePrediction!.text.toString();
62+
63+
// Create a new list element.
64+
const li = document.createElement('li');
65+
li.appendChild(a);
66+
results.appendChild(li);
67+
}
68+
}
69+
70+
// Event handler for clicking on a suggested place.
71+
async function onPlaceSelected(place) {
72+
await place.fetchFields({
73+
fields: ['displayName', 'formattedAddress'],
74+
});
75+
let placeText = document.createTextNode(place.displayName + ': ' + place.formattedAddress);
76+
results.replaceChildren(placeText);
77+
title.innerText = 'Selected Place:';
78+
input.value = '';
79+
await refreshToken();
80+
}
81+
82+
// Helper function to refresh the session token.
83+
async function refreshToken() {
84+
// Create a new session token and add it to the request.
85+
token = new google.maps.places.AutocompleteSessionToken();
86+
request.sessionToken = token;
87+
}
88+
89+
declare global {
90+
interface Window {
91+
init: () => void;
92+
}
93+
}
94+
window.init = init;
95+
// [END maps_place_autocomplete_data_session]
96+
export { };
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "@js-api-samples/place-autocomplete-data-session",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"build": "tsc && bash ../jsfiddle.sh place-autocomplete-data-session && bash ../app.sh place-autocomplete-data-session && bash ../docs.sh place-autocomplete-data-session && npm run build:vite --workspace=.",
6+
"test": "tsc && npm run build:vite --workspace=.",
7+
"start": "tsc && vite build --base './' && vite",
8+
"build:vite": "vite build --base './'",
9+
"preview": "vite preview"
10+
},
11+
"dependencies": {
12+
13+
}
14+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
2+
{% spaceless %}{% include "maps/documentation/javascript/examples/full/_apikey.html" %}{% endspaceless %}<!DOCTYPE html>
3+
<html>
4+
<head>
5+
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
6+
<meta charset="utf-8">
7+
<title>Place Autocomplete Data API Session</title>
8+
<style>
9+
{% includecode content_path="maps/documentation/javascript/examples/samples/place-autocomplete-data-session/style.css" region_tag="maps_place_autocomplete_data_session" html_escape="False" %}
10+
</style>
11+
</head>
12+
<body>
13+
{% includecode content_path="maps/documentation/javascript/examples/samples/place-autocomplete-data-session/index.html" region_tag="maps_place_autocomplete_data_session_body" html_escape="False" %}
14+
{{ api_loader_default }}
15+
<script>
16+
{% includecode content_path="maps/documentation/javascript/examples/samples/place-autocomplete-data-session/index.js" region_tag="maps_place_autocomplete_data_session" html_escape="False" %}
17+
</script>
18+
</body>
19+
</html>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @license
3+
* Copyright 2019 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
/* [START maps_place_autocomplete_data_session] */
7+
/*
8+
* Always set the map height explicitly to define the size of the div element
9+
* that contains the map.
10+
*/
11+
#map {
12+
height: 100%;
13+
}
14+
15+
/*
16+
* Optional: Makes the sample page fill the window.
17+
*/
18+
html,
19+
body {
20+
height: 100%;
21+
margin: 0;
22+
padding: 0;
23+
}
24+
25+
a {
26+
cursor: pointer;
27+
text-decoration: underline;
28+
color: blue;
29+
}
30+
31+
input {
32+
width: 300px;
33+
}
34+
35+
/* [END maps_place_autocomplete_data_session] */
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"compilerOptions": {
3+
"module": "esnext",
4+
"target": "esnext",
5+
"strict": true,
6+
"noImplicitAny": false,
7+
"lib": [
8+
"es2015",
9+
"esnext",
10+
"es6",
11+
"dom",
12+
"dom.iterable"
13+
],
14+
"moduleResolution": "Node",
15+
"jsx": "preserve"
16+
}
17+
}

0 commit comments

Comments
 (0)