-
Notifications
You must be signed in to change notification settings - Fork 8
/
google-map-api.html
587 lines (525 loc) · 18.2 KB
/
google-map-api.html
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
<!DOCTYPE html>
<html>
<head>
<title>Locator</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://ajax.googleapis.com/ajax/libs/handlebars/4.7.7/handlebars.min.js"></script>
<link
href="https://fonts.googleapis.com/css?family=Roboto"
rel="stylesheet"
/>
<script>
const CONFIGURATION = {
locations: [
{
title: "150 Henley Pl",
address1: "150 Henley Pl",
address2: "Weehawken, NJ 07086, USA",
coords: { lat: 40.76708828574744, lng: -74.01692098870426 },
placeId: "ChIJ05SPRTBYwokRTrbKgS5R3Yk",
},
],
mapOptions: {
center: { lat: 38.0, lng: -100.0 },
fullscreenControl: true,
mapTypeControl: false,
streetViewControl: false,
zoom: 4,
zoomControl: true,
maxZoom: 17,
},
mapsApiKey: "AIzaSyDHEGb8XzHTqWyHezNyXGFRRwVZbvQmd3E",
};
function initMap() {
new LocatorPlus(CONFIGURATION);
}
</script>
<script id="locator-result-items-tmpl" type="text/x-handlebars-template">
{{#each locations}}
<li class="location-result" data-location-index="{{index}}">
<button class="select-location">
<h2 class="name">{{title}}</h2>
</button>
<div class="address">{{address1}}<br />{{address2}}</div>
{{#if travelDistanceText}}
<div class="distance">{{travelDistanceText}}</div>
{{/if}}
</li>
{{/each}}
</script>
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-container {
width: 100%;
height: 100%;
position: relative;
font-family: "Roboto", sans-serif;
box-sizing: border-box;
}
#map-container button {
background: none;
color: inherit;
border: none;
padding: 0;
font: inherit;
font-size: inherit;
cursor: pointer;
}
#map {
position: absolute;
left: 22em;
top: 0;
right: 0;
bottom: 0;
}
#locations-panel {
position: absolute;
left: 0;
width: 22em;
top: 0;
bottom: 0;
overflow-y: auto;
background: white;
padding: 0.5em;
box-sizing: border-box;
}
@media only screen and (max-width: 876px) {
#map {
left: 0;
bottom: 50%;
}
#locations-panel {
top: 50%;
right: 0;
width: unset;
}
}
#locations-panel-list > header {
padding: 1.4em 1.4em 0 1.4em;
}
#locations-panel-list h1.search-title {
font-size: 1em;
font-weight: 500;
margin: 0;
}
#locations-panel-list h1.search-title > img {
vertical-align: bottom;
margin-top: -1em;
}
#locations-panel-list .search-input {
width: 100%;
margin-top: 0.8em;
position: relative;
}
#locations-panel-list .search-input input {
width: 100%;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 0.3em;
height: 2.2em;
box-sizing: border-box;
padding: 0 2.5em 0 1em;
font-size: 1em;
}
#locations-panel-list .search-input-overlay {
position: absolute;
}
#locations-panel-list .search-input-overlay.search {
right: 2px;
top: 2px;
bottom: 2px;
width: 2.4em;
}
#locations-panel-list .search-input-overlay.search button {
width: 100%;
height: 100%;
border-radius: 0.2em;
color: black;
background: transparent;
}
#locations-panel-list .search-input-overlay.search .icon {
margin-top: 0.05em;
vertical-align: top;
}
#locations-panel-list .section-name {
font-weight: 500;
font-size: 0.9em;
margin: 1.8em 0 1em 1.5em;
}
#locations-panel-list .location-result {
position: relative;
padding: 0.8em 3.5em 0.8em 1.4em;
border-bottom: 1px solid rgba(0, 0, 0, 0.12);
cursor: pointer;
}
#locations-panel-list .location-result:first-of-type {
border-top: 1px solid rgba(0, 0, 0, 0.12);
}
#locations-panel-list .location-result:last-of-type {
border-bottom: none;
}
#locations-panel-list .location-result.selected {
outline: 2px solid #4285f4;
}
#locations-panel-list button.select-location {
margin-bottom: 0.6em;
text-align: left;
}
#locations-panel-list .location-result h2.name {
font-size: 1em;
font-weight: 500;
margin: 0;
}
#locations-panel-list .location-result .address {
font-size: 0.9em;
margin-bottom: 0.5em;
}
#locations-panel-list .location-result .distance {
position: absolute;
top: 0.9em;
right: 0;
text-align: center;
font-size: 0.9em;
width: 5em;
}
#location-results-list {
list-style-type: none;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map-container">
<div id="locations-panel">
<div id="locations-panel-list">
<header>
<h1 class="search-title">
<img
src="https://fonts.gstatic.com/s/i/googlematerialicons/place/v15/24px.svg"
/>
Find a location near you
</h1>
<div class="search-input">
<input
id="location-search-input"
placeholder="Enter your address or zip code"
/>
<div
id="search-overlay-search"
class="search-input-overlay search"
>
<button id="location-search-button">
<img
class="icon"
src="https://fonts.gstatic.com/s/i/googlematerialicons/search/v11/24px.svg"
alt="Search"
/>
</button>
</div>
</div>
</header>
<div class="section-name" id="location-results-section-name">
All locations
</div>
<div class="results">
<ul id="location-results-list"></ul>
</div>
</div>
</div>
<div id="map"></div>
</div>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDHEGb8XzHTqWyHezNyXGFRRwVZbvQmd3E&callback=initMap&libraries=places,geometry&solution_channel=GMP_QB_locatorplus_v4_cABD"
async
defer
></script>
<script>
"use strict";
/**
* Defines an instance of the Locator+ solution, to be instantiated
* when the Maps library is loaded.
*/
function LocatorPlus(configuration) {
const locator = this;
locator.locations = configuration.locations || [];
locator.capabilities = configuration.capabilities || {};
const mapEl = document.getElementById("map");
const panelEl = document.getElementById("locations-panel");
locator.panelListEl = document.getElementById("locations-panel-list");
const sectionNameEl = document.getElementById(
"location-results-section-name"
);
const resultsContainerEl = document.getElementById(
"location-results-list"
);
const itemsTemplate = Handlebars.compile(
document.getElementById("locator-result-items-tmpl").innerHTML
);
locator.searchLocation = null;
locator.searchLocationMarker = null;
locator.selectedLocationIdx = null;
locator.userCountry = null;
// Initialize the map -------------------------------------------------------
locator.map = new google.maps.Map(mapEl, configuration.mapOptions);
// Store selection.
const selectResultItem = function (
locationIdx,
panToMarker,
scrollToResult
) {
locator.selectedLocationIdx = locationIdx;
for (let locationElem of resultsContainerEl.children) {
locationElem.classList.remove("selected");
if (getResultIndex(locationElem) === locator.selectedLocationIdx) {
locationElem.classList.add("selected");
if (scrollToResult) {
panelEl.scrollTop = locationElem.offsetTop;
}
}
}
if (panToMarker && locationIdx != null) {
locator.map.panTo(locator.locations[locationIdx].coords);
}
};
// Create a marker for each location.
const markers = locator.locations.map(function (location, index) {
const marker = new google.maps.Marker({
position: location.coords,
map: locator.map,
title: location.title,
});
marker.addListener("click", function () {
selectResultItem(index, false, true);
});
return marker;
});
// Fit map to marker bounds.
locator.updateBounds = function () {
const bounds = new google.maps.LatLngBounds();
if (locator.searchLocationMarker) {
bounds.extend(locator.searchLocationMarker.getPosition());
}
for (let i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
locator.map.fitBounds(bounds);
};
if (locator.locations.length) {
locator.updateBounds();
}
// Get the distance of a store location to the user's location,
// used in sorting the list.
const getLocationDistance = function (location) {
if (!locator.searchLocation) return null;
// Use travel distance if available (from Distance Matrix).
if (location.travelDistanceValue != null) {
return location.travelDistanceValue;
}
// Fall back to straight-line distance.
return google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(location.coords),
locator.searchLocation.location
);
};
// Render the results list --------------------------------------------------
const getResultIndex = function (elem) {
return parseInt(elem.getAttribute("data-location-index"));
};
locator.renderResultsList = function () {
let locations = locator.locations.slice();
for (let i = 0; i < locations.length; i++) {
locations[i].index = i;
}
if (locator.searchLocation) {
sectionNameEl.textContent =
"Nearest locations (" + locations.length + ")";
locations.sort(function (a, b) {
return getLocationDistance(a) - getLocationDistance(b);
});
} else {
sectionNameEl.textContent = `All locations (${locations.length})`;
}
const resultItemContext = { locations: locations };
resultsContainerEl.innerHTML = itemsTemplate(resultItemContext);
for (let item of resultsContainerEl.children) {
const resultIndex = getResultIndex(item);
if (resultIndex === locator.selectedLocationIdx) {
item.classList.add("selected");
}
const resultSelectionHandler = function () {
selectResultItem(resultIndex, true, false);
};
// Clicking anywhere on the item selects this location.
// Additionally, create a button element to make this behavior
// accessible under tab navigation.
item.addEventListener("click", resultSelectionHandler);
item
.querySelector(".select-location")
.addEventListener("click", function (e) {
resultSelectionHandler();
e.stopPropagation();
});
}
};
// Optional capability initialization --------------------------------------
initializeSearchInput(locator);
initializeDistanceMatrix(locator);
// Initial render of results -----------------------------------------------
locator.renderResultsList();
}
/** When the search input capability is enabled, initialize it. */
function initializeSearchInput(locator) {
const geocodeCache = new Map();
const geocoder = new google.maps.Geocoder();
const searchInputEl = document.getElementById("location-search-input");
const searchButtonEl = document.getElementById(
"location-search-button"
);
const updateSearchLocation = function (address, location) {
if (locator.searchLocationMarker) {
locator.searchLocationMarker.setMap(null);
}
if (!location) {
locator.searchLocation = null;
return;
}
locator.searchLocation = { address: address, location: location };
locator.searchLocationMarker = new google.maps.Marker({
position: location,
map: locator.map,
title: "My location",
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 12,
fillColor: "#3367D6",
fillOpacity: 0.5,
strokeOpacity: 0,
},
});
// Update the locator's idea of the user's country, used for units. Use
// `formatted_address` instead of the more structured `address_components`
// to avoid an additional billed call.
const addressParts = address.split(" ");
locator.userCountry = addressParts[addressParts.length - 1];
// Update map bounds to include the new location marker.
locator.updateBounds();
// Update the result list so we can sort it by proximity.
locator.renderResultsList();
locator.updateTravelTimes();
};
const geocodeSearch = function (query) {
if (!query) {
return;
}
const handleResult = function (geocodeResult) {
searchInputEl.value = geocodeResult.formatted_address;
updateSearchLocation(
geocodeResult.formatted_address,
geocodeResult.geometry.location
);
};
if (geocodeCache.has(query)) {
handleResult(geocodeCache.get(query));
return;
}
const request = { address: query, bounds: locator.map.getBounds() };
geocoder.geocode(request, function (results, status) {
if (status === "OK") {
if (results.length > 0) {
const result = results[0];
geocodeCache.set(query, result);
handleResult(result);
}
}
});
};
// Set up geocoding on the search input.
searchButtonEl.addEventListener("click", function () {
geocodeSearch(searchInputEl.value.trim());
});
// Initialize Autocomplete.
initializeSearchInputAutocomplete(
locator,
searchInputEl,
geocodeSearch,
updateSearchLocation
);
}
/** Add Autocomplete to the search input. */
function initializeSearchInputAutocomplete(
locator,
searchInputEl,
fallbackSearch,
searchLocationUpdater
) {
// Set up Autocomplete on the search input. Bias results to map viewport.
const autocomplete = new google.maps.places.Autocomplete(
searchInputEl,
{
types: ["geocode"],
fields: ["place_id", "formatted_address", "geometry.location"],
}
);
autocomplete.bindTo("bounds", locator.map);
autocomplete.addListener("place_changed", function () {
const placeResult = autocomplete.getPlace();
if (!placeResult.geometry) {
// Hitting 'Enter' without selecting a suggestion will result in a
// placeResult with only the text input value as the 'name' field.
fallbackSearch(placeResult.name);
return;
}
searchLocationUpdater(
placeResult.formatted_address,
placeResult.geometry.location
);
});
}
/** Initialize Distance Matrix for the locator. */
function initializeDistanceMatrix(locator) {
const distanceMatrixService = new google.maps.DistanceMatrixService();
// Annotate travel times to the selected location using Distance Matrix.
locator.updateTravelTimes = function () {
if (!locator.searchLocation) return;
const units =
locator.userCountry === "USA"
? google.maps.UnitSystem.IMPERIAL
: google.maps.UnitSystem.METRIC;
const request = {
origins: [locator.searchLocation.location],
destinations: locator.locations.map(function (x) {
return x.coords;
}),
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: units,
};
const callback = function (response, status) {
if (status === "OK") {
const distances = response.rows[0].elements;
for (let i = 0; i < distances.length; i++) {
const distResult = distances[i];
let travelDistanceText, travelDistanceValue;
if (distResult.status === "OK") {
travelDistanceText = distResult.distance.text;
travelDistanceValue = distResult.distance.value;
}
const location = locator.locations[i];
location.travelDistanceText = travelDistanceText;
location.travelDistanceValue = travelDistanceValue;
}
// Re-render the results list, in case the ordering has changed.
locator.renderResultsList();
}
};
distanceMatrixService.getDistanceMatrix(request, callback);
};
}
</script>
</body>
</html>