Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
95 lines (78 loc) · 2.76 KB
/
Copy pathindex.ts
File metadata and controls
95 lines (78 loc) · 2.76 KB
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
/**
* @license
* Copyright 2026 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// [START maps_geocoding_simple]
let geocoder: google.maps.Geocoder;
let mapElement: google.maps.MapElement;
let innerMap: google.maps.Map;
let marker: google.maps.marker.AdvancedMarkerElement;
let responseDiv: HTMLElement;
let responsePre: HTMLPreElement;
async function init() {
// Request the needed libraries.
const [{ Geocoder }, { AdvancedMarkerElement }, { ControlPosition }] =
await Promise.all([
google.maps.importLibrary('geocoding'),
google.maps.importLibrary('marker'),
google.maps.importLibrary('core'),
google.maps.importLibrary('maps'),
]);
// Get the gmp-map element.
mapElement = document.querySelector('gmp-map')!;
// Get the inner map.
innerMap = mapElement.innerMap;
// Set map options.
innerMap.setOptions({
mapTypeControl: false,
fullscreenControl: false,
cameraControlOptions: {
position: ControlPosition.INLINE_START_BLOCK_END,
},
draggableCursor: 'crosshair',
});
geocoder = new Geocoder();
const inputText = document.getElementById('address') as HTMLInputElement;
const submitButton = document.getElementById('submit') as HTMLInputElement;
const clearButton = document.getElementById('clear') as HTMLInputElement;
responseDiv = document.getElementById('response-container')!;
responsePre = document.getElementById('response') as HTMLPreElement;
marker = new AdvancedMarkerElement();
innerMap.addListener('click', (e: google.maps.MapMouseEvent) => {
void geocode({ location: e.latLng });
});
submitButton.addEventListener('click', () => {
void geocode({ address: inputText.value });
});
clearButton.addEventListener('click', () => {
clear();
});
clear();
}
function clear() {
marker.map = null;
responseDiv.style.display = 'none';
}
// [START maps_geocoding_simple_request]
async function geocode(request: google.maps.GeocoderRequest) {
clear();
const { LatLng } = await google.maps.importLibrary('core');
try {
const response = await geocoder.geocode(request);
const { results } = response;
innerMap.setCenter(results[0].geometry.location);
marker.position = new LatLng(results[0].geometry.location);
mapElement.append(marker);
responseDiv.style.display = 'block';
responsePre.innerText = JSON.stringify(response, null, 2);
return results;
} catch (e) {
alert(
'Geocode was not successful for the following reason: ' + String(e)
);
}
}
// [END maps_geocoding_simple_request]
void init();
// [END maps_geocoding_simple]