-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
461 lines (422 loc) · 18.5 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
var travelingAt = [];
var annualDriveTime = [];
var annualTransitTime = [];
var timeTravelArray = [];
var transitTravelArray = [];
var theInput = [];
var theInfo = [];
var notMetro = [];
var times = [];
var home;
var work;
var leaveHome;
var leaveWork;
var latLongHome;
var latLongWork;
var ride = [];
var drive = [];
var monetaryCost;
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat:34.0522,lng:-118.2437},
zoom: 10
});
new AutocompleteDirectionsHandler(map);
};
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.homePlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
//get user input
home = document.getElementById('home-input');
work = document.getElementById('work-input');
leaveHome = document.getElementById('leave-home');
leaveWork = document.getElementById('leave-work');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer({
//customize render so there's no line drawn and the icon is different
polylineOptions : {strokeColor:'rgba(0,0,0,0)'},
markerOptions: {
icon: 'img/red.png'
}
}),
this.directionsDisplay.setMap(map);
var homeAutocomplete = new google.maps.places.Autocomplete(
home, {placeIdOnly: true});
var workAutocomplete = new google.maps.places.Autocomplete(
work, {placeIdOnly: true});
this.setupPlaceChangedListener(homeAutocomplete, 'ORIG');
this.setupPlaceChangedListener(workAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(home);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(work);
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.homePlaceId = place.place_id;
} else {
me.workPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.homePlaceId || !this.workPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.homePlaceId},
destination: {'placeId': this.workPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
//get values from user input
homeAddress = home.value;
workAddress = work.value;
leaveHome = leaveHome.value;
leaveWork = leaveWork.value;
//set default times of day
if (leaveHome.length < 3) {
leaveHome = "08:00";
}
if (leaveWork.length < 3) {
leaveWork = "18:00";
};
function setTimes(time) {
//divide time input into hours and minutes
hours = time.slice(0,2);
minutes = time.slice(3,5);
//make date the following Wednesday from today
var nextWednesday = new Date();
nextWednesday.setDate(nextWednesday.getDate() + (9-nextWednesday.getDay())%7+1);
//Apply users departure time data to date
nextWednesday.setHours(hours, minutes);
travelingAt.push(nextWednesday);
if (travelingAt.length == 2) {
timeToWork = travelingAt[0];
timeToHome = travelingAt[1];
}
//adjust time data for 12 hour clock and add AM or PM
function timeChange (hrs) {
if (hrs[0] == 1) {
newHrs = hrs.slice(0,2);
newHrs = parseInt(newHrs);
newHrs = "0" + (newHrs - 12);
min = hrs.slice(2,5);
hrs = (newHrs + min) + " PM";
} else {
hrs = hrs + " AM";
}
times.push(hrs);
}
timeChange(leaveHome);
timeChange(leaveWork);
//set up values for display
if (times.length == 2) {
var x = "<p id='instructions' style='margin-bottom:2rem; margin-top:5rem;'>Your Routine</p><p id='resText'> Leave for work from <b>" + homeAddress.slice(0, -15) + "</b> at <b>" + times[0] + "</b></p>"
theInput.push(x);
var y = "<p id='resText'>Return home from <b>" + workAddress.slice(0, -15) + "</b> at <b>" + times[1] + "</b></p> <p id='instructions' style='margin-bottom:3rem; margin-top:7rem;'>Our Verdict</p>";
theInput.push(y);
}
}
setTimes(leaveHome);
setTimes(leaveWork);
function modes(theMode, time) {
//straight from the docs
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [homeAddress],
destinations: [workAddress],
travelMode: theMode,
transitOptions: {
modes: ['RAIL'],
departureTime: time
},
drivingOptions: {
trafficModel: 'pessimistic',
departureTime: time
},
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
console.log('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
//function to put time in hour and minute format
function convertTime (input) {
var r = "";
var d = "";
var h = "";
var m = "";
var days = parseInt(input/1140);
var hours = parseInt((input%1140)/60);
var minutes = input%60;
if(days!=0){d=days+' days ';}
if(hours!=0){h=hours+ ' hr '}
if(minutes!=0){m=minutes+ ' min'}
r = d + h + m;
return r;
}
for (var j = 0; j < results.length; j++) {
var theAddresses = originList[i].slice(0, -15) + ' to ' + destinationList[j].slice(0, -15);
if (theMode === "DRIVING") {
var distanceResult = results[j].distance.text;
//slice " mi" off the distance return value
var trimDistance = distanceResult.slice(0, -3);
var theDuration = results[j].duration_in_traffic.text;
//adjust travel time in traffic from seconds to minutes
var timeEachWay = (results[j].duration_in_traffic.value / 60).toFixed(0);
//push travel times each way into array
timeTravelArray.push(timeEachWay);
// calculate annual costs of driving using year average of 251 work days
// and $0.26 cents of wear, tear, and gas
var cost = (Number(trimDistance) * .26) * 502;
var lengthDrive = results[j].duration_in_traffic.value
//calculate annual drive time for each way of commute
var timeDrive = ((Math.round(lengthDrive*Math.pow(10,2))/Math.pow(10,2)) / 60).toFixed(0);
var annualHalfDriveTime = Number(timeDrive) * 251;
//push commute times to a variable
annualDriveTime.push(annualHalfDriveTime);
//Once both times are in the array, add commute times for total driving time
if (annualDriveTime.length == 2) {
totalAnnualCommuteTime = annualDriveTime[0] + annualDriveTime[1];
//use convertTime function, store in variables
var totalTravelTime = convertTime(totalAnnualCommuteTime);
var commuteToWork = convertTime(annualDriveTime[0]);
var commuteHome = convertTime(annualDriveTime[1]);
var timeToWork = convertTime(timeTravelArray[0]);
var timeToHome = convertTime(timeTravelArray[1]);
var theDistance = results[j].distance.text;
}
//Put costs in decimal format
monetaryCost = Math.round(cost*Math.pow(10,2))/Math.pow(10,2).toFixed(2)
//Put distance and times into one variable
var distanceAndTime = '<b>' + theDistance + '</b> each way.<br><br> Average time to work: <b>' + timeToWork + "</b> <br>Average time to home: <b>" + timeToHome + "</b>";
}
else if (theMode === "TRANSIT") {
//if there is no transit option:
if (results[0].status == "ZERO_RESULTS") {
var distanceAndTime = 0
}
// otherwise compute transit time
else {
var theDuration = results[j].duration.text;
var theDistance = results[j].distance.text;
//adjust travel time in traffic from seconds to minutes
var oneWayTravel = (results[j].duration.value / 60).toFixed(0);
//store adjusted
transitTravelArray.push(oneWayTravel);
//calculate annual travel time for each way of commute
var transitTimeOneWay = (Math.round(oneWayTravel*Math.pow(10,2))/Math.pow(10,2))
var annualTransitOneWay = Number(transitTimeOneWay) * 251;
var transitTimeOneWay = ((Number(results[j].duration.value) * 251) / 60).toFixed(0);
//push commute times to a variable
annualTransitTime.push(annualTransitOneWay);
}
//Once both times are in the array, add commute times for total transit time
if (annualTransitTime.length == 2) {
totalAnnualCommuteTime = annualTransitTime[0] + annualTransitTime[1];
//use convertTime function, store in variables
var totalTravelTime = convertTime(totalAnnualCommuteTime);
var commuteToWork = convertTime(annualTransitTime[0]);
var commuteHome = convertTime(annualTransitTime[1]);
var timeToWork = convertTime(transitTravelArray[0]);
var timeToHome = convertTime(transitTravelArray[1]);
}
var distanceAndTime = '<b>' + theDistance + '</b> each way.<br><br>Average time to work: <b>' + timeToWork + "</b> <br>Average time to home: <b>" + timeToHome + "</b>";
}
}
}
}
//set up data for display
if ((totalTravelTime && timeToHome) && (annualTransitTime.length == 2 || annualDriveTime.length == 2)) {
var a = ("<br>" + theMode + "<br><br> Approximately " + distanceAndTime);
theInfo.push(a);
var b = ("<br><br> <b>" + totalTravelTime + "<br></b> spent commuting.");
theInfo.push(b);
}
if (theInfo.length) {
var which = theInfo[0].slice(4,11);
if (!(results[0].status == "ZERO_RESULTS") && theInfo.length == 4 && which == "DRIVING") {
var dist = results[0].distance.text
var newDist = dist.slice(0,2);
var numDist = parseInt(newDist);
drive.push(theInfo[0]);
drive.push(theInfo[1]);
if (results[0].distance.value > 100 ) {
ride.push(theInfo[2]);
ride.push(theInfo[3]);
}
else {
ride = "Unfortunately, there seems to be no public transit options for your chosen route at this time. :(";
}
}
else if (theInfo.length == 4 && which == "TRANSIT"){
ride.push(theInfo[0]);
ride.push(theInfo[1]);
drive.push(theInfo[2]);
drive.push(theInfo[3]);
}
else if ((results[0].status == "ZERO_RESULTS") && which == "DRIVING") {
if (drive.length == 0) {
drive.push(theInfo[0]);
drive.push(theInfo[1]);
}
ride = "TRANSIT: There are no public transit options for your chosen route.";
}
document.getElementById('resultSection').innerHTML = '<h1 class="f2 mt4">Commute Summary</h1>'
document.getElementById('carLogo').innerHTML = "<img src='./img/car_logo.svg' alt='drive' class='clip-m' style ='margin: auto; height: 5rem; margin-left: 10%; margin-right: 15%'></img>"
document.getElementById('metroLogo').innerHTML = "<img src='./img/metro_logo.svg' alt='metro' class='clip-m' style ='margin: auto; height: 5rem; margin-left: 15%; margin-right: 10%'></img>"
document.getElementById('drivingInput').innerHTML = drive;
document.getElementById('transitInput').innerHTML = ride;
document.getElementById('drivingCost').innerHTML = "Annual Driving Cost: <b> $" + monetaryCost + "</b>"
document.getElementById('homeInput').innerHTML = theInput[0] + "<br>" + theInput[1];
document.getElementById('theButton').innerHTML = '<a onClick="window.location.reload()"; id="next-button"; class="scrollitem grow no-underline br-pill ba bw1 pv2 dib near-black" style="margin-top: 3em" href="#begin">Start Over</a>'
}
});
}
//get and show map with routes and directions
var theMap = google.maps;
//get map that shows Los Angeles
map = new theMap.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat:34.0522,lng:-118.2437},
zoom: 10
});
App = {
//set up how route lines and directions will be shown
map: map,
bounds : new theMap.LatLngBounds(),
directionsService : new theMap.DirectionsService(),
directionsDisplay1: new theMap.DirectionsRenderer({
map : map,
preserveViewport: true,
polylineOptions : {strokeColor:'red'},
markerOptions: {icon: 'img/red.png'},
}),
directionsDisplay2: new theMap.DirectionsRenderer({
map : map,
preserveViewport: true,
suppressMarkers : true,
polylineOptions : {strokeColor:'purple'},
}),
directionsDisplay3: new theMap.DirectionsRenderer({
map : map,
preserveViewport: true,
polylineOptions : {strokeColor:'green'},
markerOptions: {icon: 'img/red.png'},
}),
directionsDisplay4: new theMap.DirectionsRenderer({
map : map,
preserveViewport: true,
suppressMarkers : true,
polylineOptions : {strokeColor:'blue'},
})
},
driveOption = { origin : homeAddress,
destination : workAddress,
travelMode : theMap.TravelMode.DRIVING},
metroOption = { origin : homeAddress,
destination : workAddress,
travelMode : theMap.TravelMode.TRANSIT},
driveOption2 = { origin : workAddress,
destination : homeAddress,
travelMode : theMap.TravelMode.DRIVING},
metroOption2 = { origin : workAddress,
destination : homeAddress,
travelMode : theMap.TravelMode.TRANSIT};
//function to extract transit data from google map API JSON object and extract transit information
function nonMetro(result) {
if (!result.routes[0]) {
document.getElementById('walkingInput').innerHTML = " (And Google considers the distance too far to walk.)";
}
else {
var stepLength = result.routes[0].legs[0].steps.length;
for (i=0; i < stepLength; i++) {
// calculate annual cost of taking transit using year average of 251 work days
var travMode = JSON.stringify(result.routes[0].legs[0].steps[i].travel_mode);
var fares = (1.75 * 502).toFixed(2);
if (stepLength == 1 && travMode == '"WALKING"') {
document.getElementById('walkingInput').innerHTML = " Walking will be more efficient!";
}
else {
document.getElementById('transitCost').innerHTML = "Annual Transit Cost: <b>$" + fares + "</b>";
}
if (travMode && travMode == '"TRANSIT"') {
var carrier = JSON.stringify(result.routes[0].legs[0].steps[i].transit.line.agencies[0].name);
if (carrier != '"Metro - Los Angeles"') {
carrierName = carrier.slice(1, -1);
carrierName = " " + carrierName;
if (notMetro.indexOf(carrierName) === -1) {
notMetro.push(carrierName);
}
if (notMetro.length == 1) {
document.getElementById('transitFee').innerHTML = "Note: because the transit route includes" + notMetro + ", which is outside the Los Angeles Metro system, extra cost will be incurred."
}
else { document.getElementById('transitCost').innerHTML = "Annual Transit Cost: $" + fares;
multiNotMetro = notMetro.join(" and");
document.getElementById('transitFee').innerHTML = "Note: because the transit route includes" + multiNotMetro + ", which are outside the Los Angeles Metro system, extra cost will be incurred."
}
}
}
}
}
}
// display routes
App.directionsService.route(driveOption, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
App.directionsDisplay1.setDirections(result);
App.map.fitBounds(App.bounds.union(result.routes[0].bounds));
}
//get home and work latitude and longitude pairs if needed for use with another mapping or charting program
latLongHome = JSON.stringify(result.routes[0].legs[0].start_location);
latLongWork = JSON.stringify(result.routes[0].legs[0].end_location);
});
App.directionsService.route(driveOption2, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
App.directionsDisplay2.setDirections(result);
App.map.fitBounds(App.bounds.union(result.routes[0].bounds));
}
});
App.directionsService.route(metroOption, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
App.directionsDisplay3.setDirections(result);
App.map.fitBounds(App.bounds.union(result.routes[0].bounds));
}
nonMetro(result);
});
App.directionsService.route(metroOption2, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
App.directionsDisplay4.setDirections(result);
App.map.fitBounds(App.bounds.union(result.routes[0].bounds));
}
nonMetro(result);
});
modes('DRIVING', timeToWork)
modes('TRANSIT', timeToWork)
modes('DRIVING', timeToHome)
modes('TRANSIT', timeToHome)
};