-
Notifications
You must be signed in to change notification settings - Fork 822
/
index.js
73 lines (64 loc) · 1.8 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
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// [START maps_marker_remove]
// In the following example, markers appear when the user clicks on the map.
// The markers are stored in an array.
// The user can then click an option to hide, show or delete the markers.
let map;
let markers = [];
function initMap() {
const haightAshbury = { lat: 37.769, lng: -122.446 };
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: haightAshbury,
mapTypeId: "terrain",
});
// This event listener will call addMarker() when the map is clicked.
map.addListener("click", (event) => {
addMarker(event.latLng);
});
// add event listeners for the buttons
document
.getElementById("show-markers")
.addEventListener("click", showMarkers);
document
.getElementById("hide-markers")
.addEventListener("click", hideMarkers);
document
.getElementById("delete-markers")
.addEventListener("click", deleteMarkers);
// Adds a marker at the center of the map.
addMarker(haightAshbury);
}
// Adds a marker to the map and push to the array.
function addMarker(position) {
const marker = new google.maps.Marker({
position,
map,
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function hideMarkers() {
setMapOnAll(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
hideMarkers();
markers = [];
}
window.initMap = initMap;
// [END maps_marker_remove]