Skip to content

Commit b2d8004

Browse files
authored
feat: Migrates Place AC Data Session example. (#249)
1 parent 2931173 commit b2d8004

File tree

7 files changed

+255
-0
lines changed

7 files changed

+255
-0
lines changed
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: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
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+
};
22+
23+
async function init() {
24+
token = new google.maps.places.AutocompleteSessionToken();
25+
26+
title = document.getElementById('title');
27+
results = document.getElementById('results');
28+
input = document.querySelector("input");
29+
input.addEventListener("input", makeAcRequest);
30+
request = refreshToken(request) as any;
31+
}
32+
33+
async function makeAcRequest(input) {
34+
// Reset elements and exit if an empty string is received.
35+
if (input.target.value == '') {
36+
title.innerText = '';
37+
results.replaceChildren();
38+
return;
39+
}
40+
41+
// Add the latest char sequence to the request.
42+
request.input = input.target.value;
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+
refreshToken(request);
80+
}
81+
82+
// Helper function to refresh the session token.
83+
async function refreshToken(request) {
84+
// Create a new session token and add it to the request.
85+
token = new google.maps.places.AutocompleteSessionToken();
86+
request.sessionToken = token;
87+
return request;
88+
}
89+
90+
declare global {
91+
interface Window {
92+
init: () => void;
93+
}
94+
}
95+
window.init = init;
96+
// [END maps_place_autocomplete_data_session]
97+
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=. && bash ../dist.sh place-autocomplete-data-session",
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)