-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (74 loc) · 2.37 KB
/
index.js
File metadata and controls
74 lines (74 loc) · 2.37 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
"use strict";
/**
* @license
* Copyright 2026 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// [START maps_geocoding_simple]
let geocoder;
let mapElement;
let innerMap;
let marker;
let responseDiv;
let response;
async function initMap() {
// Request the needed libraries.
const [{ Map, InfoWindow }, { Geocoder }, { AdvancedMarkerElement }] = await Promise.all([
google.maps.importLibrary('maps'),
google.maps.importLibrary('geocoding'),
google.maps.importLibrary('marker'),
]);
// 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: google.maps.ControlPosition.INLINE_START_BLOCK_END,
},
draggableCursor: 'crosshair',
});
geocoder = new google.maps.Geocoder();
const inputText = document.getElementById('address');
const submitButton = document.getElementById('submit');
const clearButton = document.getElementById('clear');
responseDiv = document.getElementById('response-container');
response = document.getElementById('response');
marker = new google.maps.marker.AdvancedMarkerElement({});
innerMap.addListener('click', (e) => {
geocode({ location: e.latLng });
});
submitButton.addEventListener('click', () => geocode({ address: inputText.value }));
clearButton.addEventListener('click', () => {
clear();
});
clear();
}
async function clear() {
marker.setMap(null);
responseDiv.style.display = 'none';
}
// [START maps_geocoding_simple_request]
async function geocode(request) {
clear();
geocoder
.geocode(request)
.then((result) => {
const { results } = result;
innerMap.setCenter(results[0].geometry.location);
marker.position = new google.maps.LatLng(results[0].geometry.location);
mapElement.append(marker);
responseDiv.style.display = 'block';
response.innerText = JSON.stringify(result, null, 2);
return results;
})
.catch((e) => {
alert('Geocode was not successful for the following reason: ' + e);
});
}
// [END maps_geocoding_simple_request]
initMap();
// [END maps_geocoding_simple]