-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathindex.js
92 lines (82 loc) · 2.46 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
89
90
91
92
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// @ts-nocheck TODO remove when fixed
// [START maps_distance_matrix]
function initMap() {
const bounds = new google.maps.LatLngBounds();
const markersArray = [];
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 55.53, lng: 9.4 },
zoom: 10,
});
// initialize services
const geocoder = new google.maps.Geocoder();
const service = new google.maps.DistanceMatrixService();
// build request
const origin1 = { lat: 55.93, lng: -3.118 };
const origin2 = "Greenwich, England";
const destinationA = "Stockholm, Sweden";
const destinationB = { lat: 50.087, lng: 14.421 };
const request = {
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
};
// put request on page
document.getElementById("request").innerText = JSON.stringify(
request,
null,
2,
);
// get distance matrix response
service.getDistanceMatrix(request).then((response) => {
// put response
document.getElementById("response").innerText = JSON.stringify(
response,
null,
2,
);
// show on map
const originList = response.originAddresses;
const destinationList = response.destinationAddresses;
deleteMarkers(markersArray);
const showGeocodedAddressOnMap = (asDestination) => {
const handler = ({ results }) => {
map.fitBounds(bounds.extend(results[0].geometry.location));
markersArray.push(
new google.maps.Marker({
map,
position: results[0].geometry.location,
label: asDestination ? "D" : "O",
}),
);
};
return handler;
};
for (let i = 0; i < originList.length; i++) {
const results = response.rows[i].elements;
geocoder
.geocode({ address: originList[i] })
.then(showGeocodedAddressOnMap(false));
for (let j = 0; j < results.length; j++) {
geocoder
.geocode({ address: destinationList[j] })
.then(showGeocodedAddressOnMap(true));
}
}
});
}
function deleteMarkers(markersArray) {
for (let i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
window.initMap = initMap;
// [END maps_distance_matrix]