-
Notifications
You must be signed in to change notification settings - Fork 822
/
index.js
88 lines (78 loc) · 2.39 KB
/
index.js
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
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// [START maps_place_autocomplete_map]
let map;
let marker;
let infoWindow;
async function initMap() {
// Request needed libraries.
//@ts-ignore
const [{ Map }, { AdvancedMarkerElement }] = await Promise.all([
google.maps.importLibrary("marker"),
google.maps.importLibrary("places"),
]);
// Initialize the map.
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 40.749933, lng: -73.98633 },
zoom: 13,
mapId: "4504f8b37365c3d0",
mapTypeControl: false,
});
// [START maps_place_autocomplete_map_add]
//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
//@ts-ignore
placeAutocomplete.id = "place-autocomplete-input";
const card = document.getElementById("place-autocomplete-card");
//@ts-ignore
card.appendChild(placeAutocomplete);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);
// [END maps_place_autocomplete_map_add]
// Create the marker and infowindow
marker = new google.maps.marker.AdvancedMarkerElement({
map,
});
infoWindow = new google.maps.InfoWindow({});
// [START maps_place_autocomplete_map_listener]
// Add the gmp-placeselect listener, and display the results on the map.
//@ts-ignore
placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
await place.fetchFields({
fields: ["displayName", "formattedAddress", "location"],
});
// If the place has a geometry, then present it on a map.
if (place.viewport) {
map.fitBounds(place.viewport);
} else {
map.setCenter(place.location);
map.setZoom(17);
}
let content =
'<div id="infowindow-content">' +
'<span id="place-displayname" class="title">' +
place.displayName +
"</span><br />" +
'<span id="place-address">' +
place.formattedAddress +
"</span>" +
"</div>";
updateInfoWindow(content, place.location);
marker.position = place.location;
});
// [END maps_place_autocomplete_map_listener]
}
// Helper function to create an info window.
function updateInfoWindow(content, center) {
infoWindow.setContent(content);
infoWindow.setPosition(center);
infoWindow.open({
map,
anchor: marker,
shouldFocus: false,
});
}
initMap();
// [END maps_place_autocomplete_map]