-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
714 lines (470 loc) · 22 KB
/
index.js
File metadata and controls
714 lines (470 loc) · 22 KB
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
'use strict';
//Global Variables
//Use in HTML Geolocation API
let x = document.getElementById("demo");
//ipgeolocation Astronomy API https://api.ipgeolocation.io/astronomy offers times based on time zones with latitude and longitude
const geoAstronomyAPIKey = "170fa59d1a2c41ecbd0058cee382b898";
const geoLocationAstronomyUrl = "https://api.ipgeolocation.io/astronomy";
//The Hiking Project https://www.hikingproject.com/data/get-trails
const apiHikingKey = "200636207-5a82966238be9f41a852d676740cfcdf";
const hikingProjectUrl = "https://www.hikingproject.com/data/get-trails";
//Location IQ API https://us1.locationiq.com/v1/search.php?key=YOUR_PRIVATE_TOKEN&q=SEARCH_STRING&format=json
const apiToken = "f4e25901c1a5fc";
const locationIqUrl = "https://us1.locationiq.com/v1/search.php";
const jsonFormat = "json";
//JSONP data inside function for Location IQ API
let call = function callbackGeoCode(data) {
console.log(data);
};
let latitude = null;
let longitude = null;
let cityName = null;
let userActivity = null;
let title = null;
let timeOrNote = null;
//HTML Geolocation API for getting coordinates of a user's location and return trails and sun times
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
};
};
function showPosition(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
$(".js-city-name").text(`Trails around your area`);
$(".js-city-to-do").empty();
findTrails(latitude, longitude);
findTodaySun(latitude, longitude);
};
//Used with HTML Geolocation API when a user wants to use their location to find trails and today's date
function findTodaySun(latitude, longitude) {
const params = {
apiKey: geoAstronomyAPIKey,
lat: latitude,
long: longitude
};
const sunQueryString = formatQuery(params);
const url = geoLocationAstronomyUrl + "?" + sunQueryString;
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => {
let sunRiseTime = responseJson.sunrise;
let newSunTime = removeLeadingZero(sunRiseTime);
let militaryTime = responseJson.sunset;
let newHour = militaryTimeConverter(militaryTime);
let today = responseJson.date;
formatDate(today);
$(".js-city-to-do").text(`Today is`)
$(".js-daytime").text(`${responseJson.day_length} hours`);
$(".js-sunrise").text(`${newSunTime} AM`);
$(".js-sunset").text(`${newHour} PM`);
})
.catch(error => {
return $(".js-error-message").text(`Cannot get sunrise or sunset times for your place. The server or connection might be down right now.`);
});
};
//using ipgeolocation Astronomy API to get sunrise, sunset, and day length times based on user date input
function findSunTimes(latitude, longitude, dateYearMonthDay) {
const params = {
apiKey: geoAstronomyAPIKey,
lat: latitude,
long: longitude,
date: dateYearMonthDay
};
const sunQueryString = formatQuery(params);
const url = geoLocationAstronomyUrl + "?" + sunQueryString;
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => {
let sunRiseTime = responseJson.sunrise;
let newSunTime = removeLeadingZero(sunRiseTime);
let militaryTime = responseJson.sunset;
let newHour = militaryTimeConverter(militaryTime);
$(".js-daytime").text(`${responseJson.day_length} hours`);
$(".js-sunrise").text(`${newSunTime} AM`);
$(".js-sunset").text(`${newHour} PM`);
})
.catch(error => {
return $(".js-error-message").text(`Cannot get sunrise or sunset times for your place. The server or connection might be down right now.`);
});
};
//clean up any leading zeros on the sunrise times, for example, 07:35 --> 7:35
function removeLeadingZero(sunRiseTime) {
let indexZero = sunRiseTime.indexOf("0");
if (indexZero === 0) {
let newTime = sunRiseTime.slice(1);
sunRiseTime = newTime;
}
return sunRiseTime;
};
//convert any military times to a normal time format, 15:00 -> 3:00
function militaryTimeConverter(militaryTime) {
let hourTime = militaryTime.split(":");
let hourTarget = hourTime.shift();
let hourNumber = parseInt(hourTarget);
if (hourNumber === 13) {
hourNumber = 1;
} else if (hourNumber === 14) {
hourNumber = 2;
} else if (hourNumber === 15) {
hourNumber = 3;
} else if (hourNumber === 16) {
hourNumber = 4;
} else if (hourNumber === 17) {
hourNumber = 5;
} else if (hourNumber === 18) {
hourNumber = 6;
} else if (hourNumber === 19) {
hourNumber = 7;
} else if (hourNumber === 20) {
hourNumber = 8;
} else if (hourNumber === 21) {
hourNumber = 9;
} else if (hourNumber === 22) {
hourNumber = 10;
} else if (hourNumber === 23) {
hourNumber = 11;
} else if (hourNumber === 24) {
hourNumber = 12;
};
let turnBackToString = hourNumber.toString();
hourTime.unshift(turnBackToString);
let normalHour = hourTime.join(":");
return normalHour;
};
function findTrails(latitude, longitude, maxResults=10, minLength=0, maxDistance=30) {
const params = {
key: apiHikingKey,
lat: latitude,
lon: longitude,
maxResults,
minLength,
maxDistance
};
const trailsQueryString = formatQuery(params);
const url = hikingProjectUrl + "?" + trailsQueryString;
fetch(url)
.then(response => {
if(response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => {
if (responseJson.trails.length == 0) {
$(".js-city-name").text(`No trails in ${cityName}`);
$(".view-trails-link-one").addClass("hide-results");
$(".view-trails-link-two").addClass("hide-results");
$(".js-trail-results").empty();
return $(".js-error-message").text(`No trails found there. Try another place or plan your day.`);
} else if (responseJson.trails.length > 0) {
$(".js-error-message").empty();
$(".js-trail-results").empty();
for (let i = 0; i < responseJson.trails.length; i++) {
let trailPhoto = responseJson.trails[i].imgSmallMed;
if (trailPhoto === "") { //check if a trail has a photo, if the value is empty don't include the photo
$(".view-trails-link-one").removeClass("hide-results");
$(".view-trails-link-two").removeClass("hide-results");
$(".js-trail-results").append(`
<li class="trail js-trail">
<div class="trail-heading">
<a href="${responseJson.trails[i].url}" target="_blank" class="trail-website">
<h4 class="trail-name">${responseJson.trails[i].name}</h4>
</a>
<button class="add-trail js-add-trail">
<span class="add-label">
<i class="fas fa-plus-circle"></i> Add Trail
</span>
</button>
</div>
<p>${responseJson.trails[i].location}</p>
<div class="trail-details">
<p class="rating">Rating: ${responseJson.trails[i].stars} / 5</p>
<p class="trail-length">Trail Length: ${responseJson.trails[i].length} mi</p>
</div>
<p>${responseJson.trails[i].summary}</p>
</li>`
);
} else if (trailPhoto !== "") { //if photo value is not empty, then add it in the results
$(".view-trails-link-one").removeClass("hide-results");
$(".view-trails-link-two").removeClass("hide-results");
$(".js-trail-results").append(`
<li class="trail js-trail">
<div class="trail-heading">
<a href="${responseJson.trails[i].url}" target="_blank" class="trail-website">
<h4 class="trail-name">${responseJson.trails[i].name}</h4>
</a>
<button class="add-trail js-add-trail">
<span class="add-label">
<i class="fas fa-plus-circle"></i> Add Trail
</span>
</button>
</div>
<img class="trail-photo" src="${responseJson.trails[i].imgSmallMed}" alt="Photo from ${responseJson.trails[i].name}"></img>
<p>${responseJson.trails[i].location}</p>
<div class="trail-details">
<p class="rating">Rating: ${responseJson.trails[i].stars} / 5</p>
<p class="trail-length">Trail Length: ${responseJson.trails[i].length} mi</p>
</div>
<p>${responseJson.trails[i].summary}</p>
</li>`);
}
}
};
})
.catch(error => {
return $(".js-error-message").text(`${error.message} trail data. The server is down.`);
});
};
//format query parameters for a url to make get requests to APIs
function formatQuery(params) {
const queryItems = Object.keys(params)
.map(key => `${key}=${params[key]}`);
return queryItems.join("&");
};
//Using Location IQ to convert city names and places
//into latitude and longitude coordinates for the other APIs to use in their parameters
function getCityGeoCode(userCity) {
const params = {
key: apiToken,
q: userCity,
format: jsonFormat,
json_callback: call
};
const locationQueryString = formatQuery(params);
const url = locationIqUrl + "?" + locationQueryString;
fetchJsonp(url, { //using fetch jsonp callback
jsonpCallback: 'json_callback', jsonpCallbackFunction: 'callBackGeoCode'
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => {
latitude = responseJson[0].lat;
longitude = responseJson[0].lon;
cityName = responseJson[0].display_name;
cityName = formatCityName(cityName); //if the place has a county name, then this will remove it
$(".js-city-name").text(`Trails around ${cityName}`);
$(".js-city-to-do").text(`${cityName}`);
let dateYearMonthDay = $("#date").val(); //2019-11-18
let maxResults= $("#max-results").val();
let minLength = $("#min-length").val();
let maxDistance = $("#max-length").val();
findTrails(latitude, longitude, maxResults, minLength, maxDistance);
findSunTimes(latitude, longitude, dateYearMonthDay);
})
.catch(error => {
return $(".js-error-message").text(`Cannot get latitude and longitude coordinates of your place. The server or connection might be down right now.`);
});
};
//removing county from a city's name to make city name appear shorter on page
function formatCityName(cityName) {
let getCounty = cityName.split(","); //["Salem", "Marion County", "Illinois", "USA"]
for (let i = 0; i < getCounty.length; i++) {
if (getCounty[i].includes("County")) {
let county = getCounty.splice(i, 1); //splice out Marion County
};
};
let removedCounty = getCounty.join(","); //Salem, Illinois, USA
cityName = removedCounty;
return cityName;
};
//changing date input format to appear on the page as a normal date with month day, year format
function formatDate(date) {
let newDate = date.split("-"); //["2019", "11", "18"]
if (newDate[1] === "01") {
newDate[1] = "January";
} else if (newDate[1] === "02") {
newDate[1] = "February";
} else if (newDate[1] === "03") {
newDate[1] = "March";
} else if (newDate[1] === "04") {
newDate[1] = "April";
} else if (newDate[1] === "05") {
newDate[1] = "May";
} else if (newDate[1] === "06") {
newDate[1] = "June";
} else if (newDate[1] === "07") {
newDate[1] = "July";
} else if (newDate[1] === "08") {
newDate[1] = "August";
} else if (newDate[1] === "09") {
newDate[1] = "September";
} else if (newDate[1] === "10") {
newDate[1] = "October";
} else if (newDate[1] === "11") {
newDate[1] = "November";
} else if (newDate[1] === "12") {
newDate[1] = "December";
};
let year = newDate.shift();
let day = newDate.join(" ");
newDate = day + ", " + year; //November 18, 2019
$(".js-date").text(`${newDate}`);
};
//when user clicks "add trail" button, the trail's name will be added to the list
function clickAddTrail() {
$(".js-trail-results").on("click", ".js-add-trail", function(event) {
$(this).closest("li").find(".add-label").text(`Added!`); //change text of button when Add trail is clicked
let trailName = $(this).closest("li").find(".trail-name").html();
$(".activities").append(
`<li class="list-item">
<div class="act-and-times">
<span class="activity-item">${trailName}</span>
<div class="edit-delete-buttons">
<button class="edit-button" aria-label="Edit list item title or add notes to list item"><i class="far fa-edit" aria-hidden="true"></i> Edit</button>
<button class="delete-button" aria-label="Delete list item from to do list"><i class="far fa-trash-alt" aria-hidden="true"></i> Delete</button>
</div>
</div>
<div class="times-or-notes">
<span class="times-notes"></span>
</div>
<div class="edit-activity hide-edit">
<label for="activity-title-1">Change Item or Trail Name</label>
<input type="text" name="activity-title" id="activity-title-1" class="activity-title" placeholder="${trailName}">
<label for="time-note-1">Add or Change Notes Here</label>
<input type="text" name="time-note" id="time-note-1" class="time-note" placeholder="e.g. Notes: 30 min">
<button class="save-button">Save Changes</button>
</div>
</li>`);
});
};
//allow user to add new items to list and input a value as the title of the item
function addActivity() {
$(".adding-activity").submit(event => {
event.preventDefault();
userActivity = $("#activity").val();
$(".activities").append(
`<li class="list-item">
<div class="act-and-times">
<span class="activity-item">${userActivity}</span>
<div class="edit-delete-buttons">
<button class="edit-button" aria-label="Edit list item title or add notes to list item"><i class="far fa-edit" aria-hidden="true"></i> Edit</button>
<button class="delete-button" aria-label="Delete list item from to do list"><i class="far fa-trash-alt" aria-hidden="true"></i> Delete</button>
</div>
</div>
<div class="times-or-notes">
<span class="times-notes"></span>
</div>
<div class="edit-activity hide-edit">
<label for="activity-title-1">Change Item or Trail Name</label>
<input type="text" name="activity-title" id="activity-title-1" class="activity-title" placeholder="${userActivity}">
<label for="time-note-1">Add or Change Notes Here</label>
<input type="text" name="time-note" id="time-note-1" class="time-note" placeholder="e.g. Notes: 30 min">
<button class="save-button">Save Changes</button>
</div>
</li>`);
$("#activity").val(""); //empty input value
});
};
//user can click edit button to open editing for a list item or delete button
function clickEditDeleteActivity() {
//edit list item
$(".activities").on("click", ".edit-button", function(event) {
$(this).closest("li").find(".edit-activity").toggleClass("hide-edit");
});
//delete list item
$(".activities").on("click", ".delete-button", function(event) {
$(this).closest("li").remove();
});
};
//Allow user to change and save a list item's title and add notes
function updateEditActivity() {
$(".activities").on("click", ".save-button", function(event) {
event.preventDefault();
title = $(this).closest("li").find(".activity-title").val();
if (title !== "" || title !== title) { //if item's title doesn't equal an empty input or doesn't equal itself, change the title
$(this).closest("li").find(".activity-item").text(`${title}`);
};
timeOrNote = $(this).closest("li").find(".time-note").val();
if (timeOrNote !== "") { //if note is not an empty input, then let new user input be the new note
$(this).closest("li").find(".times-notes").text(`Notes: ${timeOrNote}`);
};
$(this).closest("li").find(".edit-activity").toggleClass("hide-edit");
});
};
//open and close hamburger or bar icon for navigation menu by click or keypress
function toggleHamburgerIcon() {
$(".hamburger-icon").click(event => {
$(".nav-links").toggleClass("responsive");
$(".nav-list").toggleClass("respond-to-hamburger");
});
$(".hamburger-icon").keypress(event => {
$(".nav-links").toggleClass("responsive");
$(".nav-list").toggleClass("respond-to-hamburger");
});
};
//open and close add to list section by click or keypress
function openAddToList() {
$(".add-an-activity-button").click(event => {
$(".adding-activity").toggleClass("hide-add-activity");
});
$(".close-activity-button").click(event => {
$(".adding-activity").toggleClass("hide-add-activity");
});
$(".close-activity-button").keypress(event => {
$(".adding-activity").toggleClass("hide-add-activity");
});
};
//Open and close search section by click or keypress
function openSearchTrails() {
$(".search-button").click(event => {
$("#search").toggleClass("hide-search");
});
$(".close-search-button").click(event => {
$("#search").toggleClass("hide-search");
});
$(".close-search-button").keypress(event => {
$("#search").toggleClass("hide-search");
});
$(".search").click(event => {
$("#search").toggleClass("hide-search");
});
};
//open and close search filter section in search section by click or keypress on legend
function refineSearch() {
$(".refine-title").click(event => {
$(".refine-search").toggleClass("hide-refine-search")
});
$(".refine-title").keypress(event => {
$(".refine-search").toggleClass("hide-refine-search")
});
};
//listen when user submits a search and get the input values for city/place and date
function listenToSubmit() {
$(".search-city-date").submit(event => {
event.preventDefault();
const userCity = $("#city").val();
const userDate = $("#date").val();
getCityGeoCode(userCity);
formatDate(userDate);
});
};
//liseten for events on page
function listenForEvents() {
listenToSubmit();
clickAddTrail();
addActivity();
clickEditDeleteActivity();
updateEditActivity();
toggleHamburgerIcon();
openAddToList();
openSearchTrails();
refineSearch();
};
$(listenForEvents);