-
Notifications
You must be signed in to change notification settings - Fork 821
/
index.ts
337 lines (305 loc) · 9.97 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START maps_places_autocomplete_hotelsearch]
// This example uses the autocomplete feature of the Google Places API.
// It allows the user to find all hotels in a given place, within a given
// country. It then displays markers for all the hotels returned,
// with on-click details for each hotel.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
let map: google.maps.Map;
let places: google.maps.places.PlacesService;
let infoWindow: google.maps.InfoWindow;
let markers: google.maps.Marker[] = [];
let autocomplete: google.maps.places.Autocomplete;
const countryRestrict = { country: "us" };
const MARKER_PATH =
"https://developers.google.com/maps/documentation/javascript/images/marker_green";
const hostnameRegexp = new RegExp("^https?://.+?/");
const countries: Record<
string,
{ center: google.maps.LatLngLiteral; zoom: number }
> = {
au: {
center: { lat: -25.3, lng: 133.8 },
zoom: 4,
},
br: {
center: { lat: -14.2, lng: -51.9 },
zoom: 3,
},
ca: {
center: { lat: 62, lng: -110.0 },
zoom: 3,
},
fr: {
center: { lat: 46.2, lng: 2.2 },
zoom: 5,
},
de: {
center: { lat: 51.2, lng: 10.4 },
zoom: 5,
},
mx: {
center: { lat: 23.6, lng: -102.5 },
zoom: 4,
},
nz: {
center: { lat: -40.9, lng: 174.9 },
zoom: 5,
},
it: {
center: { lat: 41.9, lng: 12.6 },
zoom: 5,
},
za: {
center: { lat: -30.6, lng: 22.9 },
zoom: 5,
},
es: {
center: { lat: 40.5, lng: -3.7 },
zoom: 5,
},
pt: {
center: { lat: 39.4, lng: -8.2 },
zoom: 6,
},
us: {
center: { lat: 37.1, lng: -95.7 },
zoom: 3,
},
uk: {
center: { lat: 54.8, lng: -4.6 },
zoom: 5,
},
};
function initMap(): void {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
zoom: countries["us"].zoom,
center: countries["us"].center,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false,
});
infoWindow = new google.maps.InfoWindow({
content: document.getElementById("info-content") as HTMLElement,
});
// Create the autocomplete object and associate it with the UI input control.
// Restrict the search to the default country, and to place type "cities".
autocomplete = new google.maps.places.Autocomplete(
document.getElementById("autocomplete") as HTMLInputElement,
{
types: ["(cities)"],
componentRestrictions: countryRestrict,
}
);
places = new google.maps.places.PlacesService(map);
autocomplete.addListener("place_changed", onPlaceChanged);
// Add a DOM event listener to react when the user selects a country.
(document.getElementById("country") as HTMLSelectElement).addEventListener(
"change",
setAutocompleteCountry
);
}
// When the user selects a city, get the place details for the city and
// zoom the map in on the city.
function onPlaceChanged() {
const place = autocomplete.getPlace();
if (place.geometry && place.geometry.location) {
map.panTo(place.geometry.location);
map.setZoom(15);
search();
} else {
(document.getElementById("autocomplete") as HTMLInputElement).placeholder =
"Enter a city";
}
}
// Search for hotels in the selected city, within the viewport of the map.
function search() {
const search = {
bounds: map.getBounds() as google.maps.LatLngBounds,
types: ["lodging"],
};
places.nearbySearch(
search,
(
results: google.maps.places.PlaceResult[] | null,
status: google.maps.places.PlacesServiceStatus,
pagination: google.maps.places.PlaceSearchPagination | null
) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
clearResults();
clearMarkers();
// Create a marker for each hotel found, and
// assign a letter of the alphabetic to each marker icon.
for (let i = 0; i < results.length; i++) {
const markerLetter = String.fromCharCode(
"A".charCodeAt(0) + (i % 26)
);
const markerIcon = MARKER_PATH + markerLetter + ".png";
// Use marker animation to drop the icons incrementally on the map.
markers[i] = new google.maps.Marker({
position: (results[i].geometry as google.maps.places.PlaceGeometry)
.location,
animation: google.maps.Animation.DROP,
icon: markerIcon,
});
// If the user clicks a hotel marker, show the details of that hotel
// in an info window.
// @ts-ignore TODO(jpoehnelt) refactor to avoid storing on marker
markers[i].placeResult = results[i];
google.maps.event.addListener(markers[i], "click", showInfoWindow);
setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
}
);
}
function clearMarkers() {
for (let i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
}
}
markers = [];
}
// Set the country restriction based on user input.
// Also center and zoom the map on the given country.
function setAutocompleteCountry() {
const country = (document.getElementById("country") as HTMLInputElement)
.value;
if (country == "all") {
autocomplete.setComponentRestrictions({ country: [] });
map.setCenter({ lat: 15, lng: 0 });
map.setZoom(2);
} else {
autocomplete.setComponentRestrictions({ country: country });
map.setCenter(countries[country].center);
map.setZoom(countries[country].zoom);
}
clearResults();
clearMarkers();
}
function dropMarker(i) {
return function () {
markers[i].setMap(map);
};
}
function addResult(result, i) {
const results = document.getElementById("results") as HTMLElement;
const markerLetter = String.fromCharCode("A".charCodeAt(0) + (i % 26));
const markerIcon = MARKER_PATH + markerLetter + ".png";
const tr = document.createElement("tr");
tr.style.backgroundColor = i % 2 === 0 ? "#F0F0F0" : "#FFFFFF";
tr.onclick = function () {
google.maps.event.trigger(markers[i], "click");
};
const iconTd = document.createElement("td");
const nameTd = document.createElement("td");
const icon = document.createElement("img");
icon.src = markerIcon;
icon.setAttribute("class", "placeIcon");
icon.setAttribute("className", "placeIcon");
const name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
const results = document.getElementById("results") as HTMLElement;
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
// Get the place details for a hotel. Show the information in an info window,
// anchored on the marker for the hotel that the user selected.
function showInfoWindow() {
// @ts-ignore
const marker = this;
places.getDetails(
{ placeId: marker.placeResult.place_id },
(place, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
}
);
}
// Load the place information into the HTML elements used by the info window.
function buildIWContent(place) {
(document.getElementById("iw-icon") as HTMLElement).innerHTML =
'<img class="hotelIcon" ' + 'src="' + place.icon + '"/>';
(document.getElementById("iw-url") as HTMLElement).innerHTML =
'<b><a href="' + place.url + '">' + place.name + "</a></b>";
(document.getElementById("iw-address") as HTMLElement).textContent =
place.vicinity;
if (place.formatted_phone_number) {
(document.getElementById("iw-phone-row") as HTMLElement).style.display = "";
(document.getElementById("iw-phone") as HTMLElement).textContent =
place.formatted_phone_number;
} else {
(document.getElementById("iw-phone-row") as HTMLElement).style.display =
"none";
}
// Assign a five-star rating to the hotel, using a black star ('✭')
// to indicate the rating the hotel has earned, and a white star ('✩')
// for the rating points not achieved.
if (place.rating) {
let ratingHtml = "";
for (let i = 0; i < 5; i++) {
if (place.rating < i + 0.5) {
ratingHtml += "✩";
} else {
ratingHtml += "✭";
}
(document.getElementById("iw-rating-row") as HTMLElement).style.display =
"";
(document.getElementById(
"iw-rating"
) as HTMLElement).innerHTML = ratingHtml;
}
} else {
(document.getElementById("iw-rating-row") as HTMLElement).style.display =
"none";
}
// The regexp isolates the first part of the URL (domain plus subdomain)
// to give a short URL for displaying in the info window.
if (place.website) {
let fullUrl = place.website;
let website = String(hostnameRegexp.exec(place.website));
if (!website) {
website = "http://" + place.website + "/";
fullUrl = website;
}
(document.getElementById("iw-website-row") as HTMLElement).style.display =
"";
(document.getElementById(
"iw-website"
) as HTMLElement).textContent = website;
} else {
(document.getElementById("iw-website-row") as HTMLElement).style.display =
"none";
}
}
// [END maps_places_autocomplete_hotelsearch]
export { initMap };