-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
68 lines (51 loc) · 2.38 KB
/
app.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
//javascript.js
//set map options
var myLatLng = { lat: 38.3460, lng: -0.4907 };
var mapOptions = {
center: myLatLng,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create map
var map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
//create a DirectionsService object to use the route method and get a result for our request
var directionsService = new google.maps.DirectionsService();
//create a DirectionsRenderer object which we will use to display the route
var directionsDisplay = new google.maps.DirectionsRenderer();
//bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);
//define calcRoute function
function calcRoute() {
//create request
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.TravelMode.DRIVING, //WALKING, BYCYCLING, TRANSIT
unitSystem: google.maps.UnitSystem.IMPERIAL
}
//pass the request to the route method
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Get distance and time
const output = document.querySelector('#output');
output.innerHTML = "<div class='alert-info'>From: " + document.getElementById("from").value + ".<br />To: " + document.getElementById("to").value + ".<br /> Driving distance <i class='fas fa-road'></i> : " + result.routes[0].legs[0].distance.text + ".<br />Duration <i class='fas fa-hourglass-start'></i> : " + result.routes[0].legs[0].duration.text + ".</div>";
//display route
directionsDisplay.setDirections(result);
} else {
//delete route from map
directionsDisplay.setDirections({ routes: [] });
//center map in London
map.setCenter(myLatLng);
//show error message
output.innerHTML = "<div class='alert-danger'><i class='fas fa-exclamation-triangle'></i> Could not retrieve driving distance.</div>";
}
});
}
//create autocomplete objects for all inputs
var options = {
types: ['(cities)']
}
var input1 = document.getElementById("from");
var autocomplete1 = new google.maps.places.Autocomplete(input1, options);
var input2 = document.getElementById("to");
var autocomplete2 = new google.maps.places.Autocomplete(input2, options);