-
Notifications
You must be signed in to change notification settings - Fork 823
/
index.js
65 lines (56 loc) · 2.02 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
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// [START maps_directions_waypoints]
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
center: { lat: 41.85, lng: -87.65 },
});
directionsRenderer.setMap(map);
document.getElementById("submit").addEventListener("click", () => {
calculateAndDisplayRoute(directionsService, directionsRenderer);
});
}
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
const waypts = [];
const checkboxArray = document.getElementById("waypoints");
for (let i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true,
});
}
}
directionsService
.route({
origin: document.getElementById("start").value,
destination: document.getElementById("end").value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING,
})
.then((response) => {
directionsRenderer.setDirections(response);
const route = response.routes[0];
const summaryPanel = document.getElementById("directions-panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (let i = 0; i < route.legs.length; i++) {
const routeSegment = i + 1;
summaryPanel.innerHTML +=
"<b>Route Segment: " + routeSegment + "</b><br>";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br><br>";
}
})
.catch((e) => window.alert("Directions request failed due to " + status));
}
window.initMap = initMap;
// [END maps_directions_waypoints]