|
5 | 5 | */ |
6 | 6 |
|
7 | 7 | // [START maps_place_autocomplete_data_session] |
8 | | -let titleElement; |
9 | | -let resultsContainerElement; |
10 | | -let inputElement; |
11 | | - |
| 8 | +const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; |
| 9 | +let innerMap: google.maps.Map; |
| 10 | +let marker: google.maps.marker.AdvancedMarkerElement; |
| 11 | +let titleElement = document.querySelector('.title') as HTMLElement; |
| 12 | +let resultsContainerElement = document.querySelector('.results') as HTMLElement; |
| 13 | +let inputElement = document.querySelector('input') as HTMLInputElement; |
| 14 | +let tokenStatusElement = document.querySelector('.token-status') as HTMLElement; |
12 | 15 | let newestRequestId = 0; |
| 16 | +let tokenCount = 0; |
13 | 17 |
|
14 | | -// Add an initial request body. |
15 | | -const request = { |
| 18 | +// Create an initial request body. |
| 19 | +const request: google.maps.places.AutocompleteRequest = { |
16 | 20 | input: '', |
17 | | - locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78 }, |
18 | | - origin: { lat: 37.7893, lng: -122.4039 }, |
19 | | - includedPrimaryTypes: ['restaurant'], |
20 | | - language: 'en-US', |
21 | | - region: 'us', |
22 | | -}; |
23 | | - |
24 | | -function init() { |
25 | | - titleElement = document.getElementById('title'); |
26 | | - resultsContainerElement = document.getElementById('results'); |
27 | | - inputElement = document.querySelector('input'); |
| 21 | + includedPrimaryTypes: [ |
| 22 | + 'restaurant', |
| 23 | + 'cafe', |
| 24 | + 'museum', |
| 25 | + 'park', |
| 26 | + 'botanical_garden', |
| 27 | + ], |
| 28 | +} |
| 29 | + |
| 30 | +async function init() { |
| 31 | + await google.maps.importLibrary('maps'); |
| 32 | + innerMap = mapElement.innerMap; |
| 33 | + innerMap.setOptions({ |
| 34 | + mapTypeControl: false, |
| 35 | + }); |
| 36 | + |
| 37 | + // Update request center and bounds when the map bounds change. |
| 38 | + google.maps.event.addListener(innerMap, 'bounds_changed', async () => { |
| 39 | + request.locationRestriction = innerMap.getBounds(); |
| 40 | + request.origin = innerMap.getCenter(); |
| 41 | + }); |
| 42 | + |
28 | 43 | inputElement.addEventListener('input', makeAutocompleteRequest); |
29 | | - refreshToken(request); |
30 | 44 | } |
31 | 45 |
|
32 | 46 | async function makeAutocompleteRequest(inputEvent) { |
33 | | - // Reset elements and exit if an empty string is received. |
34 | | - if (inputEvent.target.value == '') { |
35 | | - titleElement.innerText = ''; |
| 47 | + // To avoid race conditions, store the request ID and compare after the request. |
| 48 | + const requestId = ++newestRequestId; |
| 49 | + |
| 50 | + const { AutocompleteSuggestion } = (await google.maps.importLibrary( |
| 51 | + 'places' |
| 52 | + )) as google.maps.PlacesLibrary; |
| 53 | + |
| 54 | + if (!inputEvent.target?.value) { |
| 55 | + titleElement.textContent = ''; |
36 | 56 | resultsContainerElement.replaceChildren(); |
37 | 57 | return; |
38 | 58 | } |
39 | 59 |
|
40 | 60 | // Add the latest char sequence to the request. |
41 | | - request.input = inputEvent.target.value; |
42 | | - |
43 | | - // To avoid race conditions, store the request ID and compare after the request. |
44 | | - const requestId = ++newestRequestId; |
| 61 | + request.input = (inputEvent.target as HTMLInputElement).value; |
45 | 62 |
|
46 | 63 | // Fetch autocomplete suggestions and show them in a list. |
47 | | - // @ts-ignore |
48 | | - const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request); |
| 64 | + const { suggestions } = |
| 65 | + await AutocompleteSuggestion.fetchAutocompleteSuggestions(request); |
49 | 66 |
|
50 | 67 | // If the request has been superseded by a newer request, do not render the output. |
51 | 68 | if (requestId !== newestRequestId) return; |
52 | 69 |
|
53 | | - titleElement.innerText = `Query predictions for "${request.input}"`; |
| 70 | + titleElement.innerText = `Place predictions for "${request.input}"`; |
54 | 71 |
|
55 | 72 | // Clear the list first. |
56 | 73 | resultsContainerElement.replaceChildren(); |
57 | 74 |
|
58 | 75 | for (const suggestion of suggestions) { |
59 | 76 | const placePrediction = suggestion.placePrediction; |
60 | 77 |
|
| 78 | + if (!placePrediction) { |
| 79 | + continue; |
| 80 | + } |
| 81 | + |
61 | 82 | // Create a link for the place, add an event handler to fetch the place. |
62 | | - const a = document.createElement('a'); |
63 | | - a.addEventListener('click', () => { |
64 | | - onPlaceSelected(placePrediction!.toPlace()); |
| 83 | + // We are using a button element to take advantage of its a11y capabilities. |
| 84 | + const placeButton = document.createElement('button'); |
| 85 | + placeButton.addEventListener('click', () => { |
| 86 | + onPlaceSelected(placePrediction.toPlace()); |
65 | 87 | }); |
66 | | - a.innerText = placePrediction!.text.toString(); |
| 88 | + placeButton.textContent = placePrediction.text.toString(); |
| 89 | + placeButton.classList.add('place-button'); |
67 | 90 |
|
68 | 91 | // Create a new list item element. |
69 | 92 | const li = document.createElement('li'); |
70 | | - li.appendChild(a); |
| 93 | + li.appendChild(placeButton); |
71 | 94 | resultsContainerElement.appendChild(li); |
72 | 95 | } |
73 | 96 | } |
74 | 97 |
|
75 | 98 | // Event handler for clicking on a suggested place. |
76 | | -async function onPlaceSelected(place) { |
| 99 | +async function onPlaceSelected(place: google.maps.places.Place) { |
| 100 | + const { AdvancedMarkerElement } = (await google.maps.importLibrary( |
| 101 | + 'marker' |
| 102 | + )) as google.maps.MarkerLibrary; |
| 103 | + |
77 | 104 | await place.fetchFields({ |
78 | | - fields: ['displayName', 'formattedAddress'], |
| 105 | + fields: ['displayName', 'formattedAddress', 'location'], |
79 | 106 | }); |
80 | | - const placeText = document.createTextNode(`${place.displayName}: ${place.formattedAddress}`); |
81 | | - resultsContainerElement.replaceChildren(placeText); |
82 | | - titleElement.innerText = 'Selected Place:'; |
| 107 | + |
| 108 | + resultsContainerElement.textContent = `${place.displayName}: ${place.formattedAddress}`; |
| 109 | + titleElement.textContent = 'Selected Place:'; |
83 | 110 | inputElement.value = ''; |
84 | | - refreshToken(request); |
| 111 | + |
| 112 | + await refreshToken(); |
| 113 | + |
| 114 | + // Remove the previous marker, if it exists. |
| 115 | + if (marker) { |
| 116 | + marker.remove(); |
| 117 | + } |
| 118 | + |
| 119 | + // Create a new marker. |
| 120 | + marker = new AdvancedMarkerElement({ |
| 121 | + map: innerMap, |
| 122 | + position: place.location, |
| 123 | + title: place.displayName, |
| 124 | + }) |
| 125 | + |
| 126 | + // Center the map on the selected place. |
| 127 | + if (place.location) { |
| 128 | + innerMap.setCenter(place.location); |
| 129 | + innerMap.setZoom(15); |
| 130 | + } |
85 | 131 | } |
86 | 132 |
|
87 | 133 | // Helper function to refresh the session token. |
88 | | -function refreshToken(request) { |
| 134 | +async function refreshToken() { |
| 135 | + const { AutocompleteSessionToken } = (await google.maps.importLibrary( |
| 136 | + 'places' |
| 137 | + )) as google.maps.PlacesLibrary; |
| 138 | + |
| 139 | + // Increment the token counter. |
| 140 | + tokenCount++; |
| 141 | + |
89 | 142 | // Create a new session token and add it to the request. |
90 | | - request.sessionToken = new google.maps.places.AutocompleteSessionToken(); |
| 143 | + request.sessionToken = new AutocompleteSessionToken(); |
| 144 | + tokenStatusElement.textContent = `Session token count: ${tokenCount}`; |
91 | 145 | } |
92 | 146 |
|
93 | | -declare global { |
94 | | - interface Window { |
95 | | - init: () => void; |
96 | | - } |
97 | | - } |
98 | | - window.init = init; |
| 147 | +init(); |
99 | 148 | // [END maps_place_autocomplete_data_session] |
100 | | -void 0; // No-op to preserve the last region tag comment. |
101 | | -export { }; |
|
0 commit comments