generated from chingu-voyages/voyage-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscript.js
791 lines (706 loc) · 24.3 KB
/
script.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
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
"use strict";
// DOM element references
const links = document.querySelectorAll(".links");
const panels = document.querySelectorAll(".panel");
const burger = document.querySelector(".burger");
const nav = document.querySelector(".nav-links");
const homeSection = document.getElementById("home");
const resultSection = document.getElementById("resultSection");
const summaryWrapper = document.getElementById("summaryWrapper");
const switchBtn = document.getElementById("switchBtn");
const switchButton = document.getElementById("switchButton");
const tableIcon = document.querySelector(".fa-table");
const globeIcon = document.querySelector(".fa-globe");
const yearChart = document.getElementById("yearHistogramContainer");
const compositionChart = document.getElementById(
"compositionHistogramContainer"
);
const explore = document.getElementById("explore");
const exploreLink = document.getElementById("exploreLink");
const searchInput = document.getElementById("searchInput");
const searchWrapper = document.getElementById("searchWrapper");
const searchButton = document.getElementById("searchButton");
const filterBtn = document.getElementById("filterBtn");
const filterWrapper = document.getElementById("filterContainer");
const exploreBtn = document.getElementById("exploreBtn");
const clearButton = document.getElementById("clearButton");
const searchIcon = document.getElementById("searchIcon");
const resultsWrapper = document.getElementById("advanceSearch");
const table = document.getElementById("detailDataDisplay");
const pageEl = document.getElementById("pagination");
const nextPrevContainer = document.getElementById("nextPrevContainer");
const paginationInfo = document.getElementById("paginationInfo");
const tablePagination = document.getElementById("tablePagination");
const sortArrow = document.querySelectorAll(".fa-sort");
const arrowLeft = document.querySelector(".arrow-left");
const arrowRight = document.querySelector(".arrow-right");
const mainWrapper = document.querySelector(".main-wrapper");
const mapBtn = document.getElementById("map-btn");
const filterButton = document.getElementById("filterButton");
const nameFilter = document.getElementById("nameFilter");
const compositionFilter = document.getElementById("compositionFilter");
const massMinFilter = document.getElementById("massMinFilter");
const massMaxFilter = document.getElementById("massMaxFilter");
const yearMinFilter = document.getElementById("yearMinFilter");
const yearMaxFilter = document.getElementById("yearMaxFilter");
const noResultsMessage = document.querySelector(".no-results");
const tableBtn = document.getElementById("switchButton");
const tableWrapper = document.getElementById("table");
const mapWrapper = document.getElementById("mapWrapper");
const saveButton = document.getElementById("saveButton");
const resetButton = document.getElementById("resetButton");
const delAllFiltersBtn = document.getElementById("delAllFiltersBtn");
const savedSearchDiv = document.getElementById("savedSearchDiv");
// Data
let meteorData = []; // Store fetched meteor data
let filteredResults = []; // Store filtered data
let filteredAdvanceResults = []; // Store filtered advance results
let currentImageIndex = 0; // Current image index
let currentPage = 1; // First page of detail display data
let rows = 10; // Number of rows per page
let searchText; // Store input search terms
let selectedYearRange; // Store year range data
let markerCluster; // Store marker cluster
let map; // Define map
let currentSortParameter = "name"; // Default sorting parameter
let isAscending = true; // Default sorting order
// Constants
const imagePaths = [
"assets/landing_page1.jpg",
"assets/landing_page2.jpg",
"assets/landing_page3.jpg",
];
// Data fetching and initialization
function fetchData() {
fetch("https://data.nasa.gov/resource/gh4g-9sfh.json")
.then((response) => {
if (!response.ok) {
throw new Error("Network response error");
}
return response.json();
})
.then((data) => {
meteorData = data;
populateDropdowns();
})
.catch((error) => {
console.error("Error fetching data:", error);
const errorElement = document.getElementById("error-message");
errorElement.textContent =
"An error occurred while fetching data. Please try again later.";
});
}
// Functions related to UI initialization
function initializePage() {
fetchData();
handleLinks();
initializeMap();
exploreBtn.addEventListener("click", handleStart);
exploreLink.addEventListener("click", displayResults);
burger.addEventListener("click", toggleMenu);
switchBtn.addEventListener("click", switchChart);
switchButton.addEventListener("click", switchDisplay);
searchInput.addEventListener("focus", handleInputEvents);
searchInput.addEventListener("blur", handleInputEvents);
searchInput.addEventListener("keyup", handleInputEvents);
arrowLeft.addEventListener("click", getPrevImg);
arrowRight.addEventListener("click", getNextImg);
filterBtn.addEventListener("click", getFilter);
filterButton.addEventListener("click", showFilteredResults);
saveButton.addEventListener("click", saveFilter);
resetButton.addEventListener("click", resetResults);
delAllFiltersBtn.addEventListener("click", clearSavedSearches);
clearButton.addEventListener("click", clearSearch);
}
function handleLinks() {
links.forEach((link) => {
link.addEventListener("click", (e) => {
panels.forEach((element) => {
element.classList.add("hidden");
});
document.getElementById(e.target.dataset.id).classList.remove("hidden");
});
});
}
function toggleMenu(e) {
e.preventDefault();
nav.classList.toggle("open");
burger.classList.toggle("open");
}
function handleStart(e) {
e.preventDefault();
displayResults(meteorData);
homeSection.classList.add("hidden");
explore.classList.remove("hidden");
}
function getFilter() {
summaryWrapper.classList.add("blur");
searchWrapper.classList.add("blur");
filterWrapper.classList.remove("hidden");
listSavedFilters();
}
function handleInputEvents(event) {
event.preventDefault();
if (event.key === "Enter") {
displayResults();
} else if (event.type === "focus") {
searchButton.classList.add("hidden");
}
}
function clearSearch() {
searchInput.value = "";
searchButton.classList.remove("hidden");
displayResults(meteorData);
}
function switchDisplay() {
if (mapWrapper.classList.contains("hidden")) {
tableWrapper.classList.add("hidden");
mapWrapper.classList.remove("hidden");
pageEl.classList.add("hidden");
tablePagination.classList.add("hidden");
tableIcon.classList.remove("hidden");
globeIcon.classList.add("hidden");
} else {
tableWrapper.classList.remove("hidden");
mapWrapper.classList.add("hidden");
pageEl.classList.remove("hidden");
tablePagination.classList.remove("hidden");
tableIcon.classList.add("hidden");
globeIcon.classList.remove("hidden");
}
}
function switchChart() {
if (compositionChart.classList.contains("hidden")) {
compositionChart.classList.remove("hidden");
yearChart.classList.add("hidden");
switchBtn.style.color = "var(--clr-orange)";
} else {
compositionChart.classList.add("hidden");
yearChart.classList.remove("hidden");
switchBtn.style.color = "var(--clr-blue)";
}
}
function showFilteredResults(e) {
e.preventDefault();
getAdvanceFilter();
summaryWrapper.classList.remove("blur");
searchWrapper.classList.remove("blur");
filterWrapper.classList.add("hidden");
}
// Functions to display data
function displayResults() {
getResults();
if (filteredResults.length === 0 || searchText === "") {
currentPage = 1;
displayList(meteorData, table, rows, currentPage, paginationInfo);
setupPagination(meteorData, pageEl, rows);
nextPrevButtons(nextPrevContainer, meteorData);
addMarkersToMap(meteorData);
updateChart(meteorData);
} else {
currentPage = 1;
displayList(filteredResults, table, rows, currentPage, paginationInfo);
setupPagination(filteredResults, pageEl, rows);
nextPrevButtons(nextPrevContainer, filteredResults);
updateChart(filteredResults);
addMarkersToMap(filteredResults);
}
}
// Function to filter results
function getResults() {
searchText = searchInput.value.toLowerCase().trim();
const searchNumber = parseFloat(searchText);
filteredResults = meteorData.filter((meteor) => {
const name = meteor.name.toLowerCase();
const mass = meteor.mass ? meteor.mass.toString() : "";
const year = meteor.year ? meteor.year.toString() : "";
const massMatches = mass === searchNumber;
return (
name.includes(searchText) ||
mass.includes(searchText) ||
year.includes(searchText) ||
massMatches
);
});
}
// Function to display first page items in a table
function displayList(items, wrapper, rowsPerPage, page, pageInfowrapper) {
page--;
const start = rowsPerPage * page;
const end = Math.min(start + rowsPerPage, items.length);
const paginatedItems = items.slice(start, end);
const itemCount = Math.min(end, items.length);
pageInfowrapper.innerText = `Showing meteorite landings ${
start + 1
} to ${itemCount} out of ${items.length}`;
wrapper.innerHTML = paginatedItems
.map(
(item) => `
<tr>
<td>${item.name || "-"}</td>
<td>${item.mass || "-"}</td>
<td>${item.year ? item.year.substring(0, 4) : "-"}</td>
<td>${item.recclass || "-"}</td>
</tr>
`
)
.join("");
}
// Adding event listeners to all sort icons
Array.from(sortArrow).forEach((el, i) => {
el.addEventListener("click", () => {
const parameters = ["name", "mass", "year", "recclass"];
const clickedParameter = parameters[i];
if (clickedParameter === currentSortParameter) {
isAscending = !isAscending; // Toggle sorting order
} else {
currentSortParameter = clickedParameter;
isAscending = true; // Reset sorting order
}
if (searchText) {
sortData(filteredResults);
} else {
sortData(meteorData);
}
});
});
// Function to sort results in ascending/descending order
function sortData(data) {
data = data.sort((a, b) => {
const aValue = a[currentSortParameter] || "";
const bValue = b[currentSortParameter] || "";
return isAscending
? aValue.localeCompare(bValue, undefined, { numeric: true })
: bValue.localeCompare(aValue, undefined, { numeric: true });
});
displayList(data, table, rows, currentPage, paginationInfo);
}
// Function to create pages
function setupPagination(items, wrapper, rowsPerPage) {
wrapper.innerHTML = "";
let pageCount = Math.ceil(items.length / rowsPerPage);
for (let i = 1; i < pageCount + 1; i++) {
wrapper.appendChild(paginationBtn(i, items));
}
}
//Function to create Next and Prev Buttons
function nextPrevButtons(wrapper, items) {
let prevBtn = document.createElement("button");
let nextBtn = document.createElement("button");
prevBtn.innerHTML = `<i class="fa fa-angle-left"></i><span>Prev</span>`;
nextBtn.innerHTML = `<span>Next</span><i class="fa fa-angle-right"></i>`;
wrapper.innerHTML = "";
wrapper.appendChild(prevBtn);
wrapper.appendChild(nextBtn);
prevBtn.addEventListener("click", () => {
currentPage--;
displayList(items, table, rows, currentPage, paginationInfo);
setupPagination(items, pageEl, rows);
if (currentPage < 1) {
currentPage = pageEl.childNodes.length;
displayList(items, table, rows, currentPage, paginationInfo);
setupPagination(items, pageEl, rows);
}
});
nextBtn.addEventListener("click", () => {
currentPage++;
displayList(items, table, rows, currentPage, paginationInfo);
setupPagination(items, pageEl, rows);
if (currentPage > pageEl.childNodes.length) {
currentPage = 1;
displayList(items, table, rows, currentPage, paginationInfo);
setupPagination(items, pageEl, rows);
}
});
}
// Function to create page buttons
function paginationBtn(page, items) {
let btn = document.createElement("button");
btn.innerText = page;
if (currentPage == page) {
btn.classList.add("active");
}
btn.addEventListener("click", () => {
currentPage = page;
displayList(items, table, rows, currentPage);
let currentBtn = document.querySelector("#pagination button.active");
currentBtn.classList.remove("active");
btn.classList.add("active");
});
return btn;
}
// Change background image
function changeBackgroundImage() {
const newBackgroundImage = `url('${imagePaths[currentImageIndex]}')`;
document.body.style.transition =
"background-image 0.5s ease, opacity 0.5s ease";
document.body.style.backgroundAttachment = "fixed";
document.body.style.backgroundImage = newBackgroundImage;
document.body.style.opacity = 0.8;
setTimeout(() => {
document.body.style.transition = "none";
document.body.style.backgroundPosition = "center";
document.body.style.backgroundSize = "cover";
}, 500);
}
function getNextImg(e) {
e.preventDefault();
currentImageIndex = (currentImageIndex + 1) % imagePaths.length;
changeBackgroundImage();
}
function getPrevImg(e) {
e.preventDefault();
currentImageIndex =
(currentImageIndex - 1 + imagePaths.length) % imagePaths.length;
changeBackgroundImage();
}
function populateDropdowns() {
const uniqueName = Array.from(
new Set(meteorData.map((meteor) => meteor.name || ""))
);
// Sort alphabetically
uniqueName.sort((a, b) => a.localeCompare(b));
uniqueName.forEach((name) => {
const option = document.createElement("option");
option.value = name.toLowerCase();
option.textContent = name;
nameFilter.appendChild(option);
});
const uniqueCompositions = Array.from(
new Set(meteorData.map((meteor) => meteor.recclass || ""))
);
// Sort alphabetically
uniqueCompositions.sort((a, b) => a.localeCompare(b));
uniqueCompositions.forEach((composition) => {
const option = document.createElement("option");
option.value = composition.toLowerCase();
option.textContent = composition;
compositionFilter.appendChild(option);
});
// Populate mass dropdowns
const uniqueMassValues = Array.from(
new Set(meteorData.map((meteor) => parseFloat(meteor.mass) || ""))
);
// Sort the mass in ascending order
const sortedMassValues = uniqueMassValues
.filter((value) => typeof value === "number")
.sort((a, b) => a - b);
sortedMassValues.forEach((massValue) => {
const optionMin = document.createElement("option");
const optionMax = document.createElement("option");
optionMin.value = massValue;
optionMin.textContent = `${massValue}`;
optionMax.value = massValue;
optionMax.textContent = `${massValue}`;
massMinFilter.appendChild(optionMin);
massMaxFilter.appendChild(optionMax);
});
// Populate year dropdowns
const uniqueYearValues = Array.from(
new Set(meteorData.map((meteor) => parseInt(meteor.year) || ""))
);
// Sort the year in ascending order
const sortedYearValues = uniqueYearValues
.filter((value) => typeof value === "number")
.sort((a, b) => a - b);
sortedYearValues.forEach((yearValue) => {
const optionMin = document.createElement("option");
const optionMax = document.createElement("option");
optionMin.value = yearValue;
optionMin.textContent = `${yearValue}`;
optionMax.value = yearValue;
optionMax.textContent = `${yearValue}`;
yearMinFilter.appendChild(optionMin);
yearMaxFilter.appendChild(optionMax);
});
}
// Initialize the map
function initializeMap() {
map = L.map("map").setView([0, 0], 2);
const cartodbAttribution =
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://carto.com/attribution">CARTO</a>';
L.tileLayer("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png", {
noWrap: true,
bounds: [
[-90, -180],
[90, 180],
],
attribution: cartodbAttribution,
}).addTo(map);
const resizeObserver = new ResizeObserver(() => {
map.invalidateSize();
});
const mapDiv = document.getElementById("map");
resizeObserver.observe(mapDiv);
}
// Add markers to the map
function addMarkersToMap(filteredData) {
try {
map.eachLayer((layer) => {
if (layer instanceof L.Circle) {
map.removeLayer(layer);
}
});
if (markerCluster) {
map.removeLayer(markerCluster);
}
const markers = [];
filteredData.forEach((meteor) => {
const lat = parseFloat(meteor.reclat);
const lon = parseFloat(meteor.reclong);
if (!isNaN(lat) && !isNaN(lon)) {
let marker = L.circle([lat, lon], {
color: "var(--clr-orange)",
})
.addTo(map)
.bindPopup(
`Name: ${meteor.name},<br>
Mass: ${meteor.mass},<br>
Year: ${meteor.year},<br>
Composition: ${meteor.recclass}
`
)
.on("mouseover", function () {
this.openPopup();
this.setRadius(15000);
})
.on("mouseout", function () {
this.closePopup();
this.setRadius(10000);
});
markers.push(marker);
}
});
markerCluster = L.markerClusterGroup();
markerCluster.addLayers(markers);
map.addLayer(markerCluster);
} catch (error) {
console.error("Error adding markers to map:", error);
}
}
function getAdvanceFilter() {
const nameTerm = nameFilter.value.toLowerCase();
const compositionTerm = compositionFilter.value.toLowerCase();
const massMin = parseFloat(massMinFilter.value);
const massMax = parseFloat(massMaxFilter.value);
const yearMin = parseInt(yearMinFilter.value);
const yearMax = parseInt(yearMaxFilter.value);
filteredAdvanceResults = meteorData.filter((meteor) => {
const name = (meteor.name || "").toLowerCase();
const composition = (meteor.recclass || "").toLowerCase();
const mass = parseFloat(meteor.mass);
const year = parseInt(meteor.year);
const massInRange =
(isNaN(massMin) || mass >= massMin) &&
(isNaN(massMax) || mass <= massMax);
const yearInRange =
(isNaN(yearMin) || year >= yearMin) &&
(isNaN(yearMax) || year <= yearMax);
const compositionValue = compositionFilter.value;
const selectedComposition = (meteor.recclass || "").toLowerCase();
if (
nameTerm === "" ||
(name.includes(nameTerm) && compositionValue === "") ||
selectedComposition.includes(compositionValue)
) {
return (
name.includes(nameTerm) &&
composition.includes(compositionTerm) &&
massInRange &&
yearInRange
);
}
});
checkResults(filteredAdvanceResults);
}
function checkResults(data) {
filteredAdvanceResults = data;
if (filteredAdvanceResults.length === 0) {
updateChart(meteorData);
addMarkersToMap(meteorData);
displayList(meteorData, table, rows, currentPage, paginationInfo);
} else {
updateChart(filteredAdvanceResults, selectedYearRange);
addMarkersToMap(filteredAdvanceResults);
displayList(
filteredAdvanceResults,
table,
rows,
currentPage,
paginationInfo
);
}
}
// Initialize the year histogram
Chart.defaults.color = "white";
const yearHistogram = new Chart(document.getElementById("yearHistogram"), {
type: "bar",
data: {
labels: [],
datasets: [
{
label: "Number of Strikes by Year",
data: [],
backgroundColor: "rgb(225, 85, 33, 0.2)",
borderColor: "rgb(225, 85, 33, 1)",
borderWidth: 1,
},
],
},
options: {
scales: {
y: {
beginAtZero: true,
},
},
},
});
// Initialize the composition histogram
const compositionHistogram = new Chart(
document.getElementById("compositionHistogram"),
{
type: "bar",
data: {
labels: [],
datasets: [
{
label: "Number of Strikes by Composition",
data: [],
backgroundColor: "rgba(75, 192, 192, 0.2)",
borderColor: "rgba(75, 192, 192, 1)",
borderWidth: 1,
color: "rgb(255, 255, 255)",
},
],
},
options: {
scales: {
y: {
beginAtZero: true,
},
},
},
}
);
function updateChart(results) {
const average = document.getElementById("averageStrikes");
const total = document.getElementById("totalStrikes");
const years = results.map((item) =>
item.year ? item.year.substring(0, 4) : "Unknown"
);
const compositions = results.map((item) => item.recclass || "Unknown");
const yearCounts = {};
const compositionCounts = {};
years.forEach((year) => (yearCounts[year] = (yearCounts[year] || 0) + 1));
compositions.forEach(
(composition) =>
(compositionCounts[composition] =
(compositionCounts[composition] || 0) + 1)
);
// Update the year histogram data
yearHistogram.data.labels = Object.keys(yearCounts);
yearHistogram.data.datasets[0].data = Object.values(yearCounts);
// Update the composition histogram data
compositionHistogram.data.labels = Object.keys(compositionCounts);
compositionHistogram.data.datasets[0].data = Object.values(compositionCounts);
yearHistogram.update();
compositionHistogram.update();
// Calculate and log the average strikes
const averageStrikes = calculateAverageStrikes(yearCounts);
console.log("Average Strikes per Year:", averageStrikes);
average.innerHTML = `${averageStrikes}`;
// Calculate and log the total strikes
const totalStrikes = calculateTotalStrikes(yearCounts);
console.log("Total Strikes:", totalStrikes);
total.innerHTML = `${totalStrikes}`;
}
// Calculate the average number of strikes
function calculateAverageStrikes(yearCounts) {
const totalYears = Object.keys(yearCounts).length;
const totalStrikes = Object.values(yearCounts).reduce(
(total, count) => total + count,
0
);
if (totalYears === 0) {
return 0;
}
const averageStrikes = Math.round(totalStrikes / totalYears);
return averageStrikes;
}
// Calculate the total number of strikes
function calculateTotalStrikes(yearCounts) {
const totalStrikes = Object.values(yearCounts).reduce(
(total, count) => total + count,
0
);
return totalStrikes;
}
// Function to save filters to local sotrage
function saveFilter() {
getAdvanceFilter();
const newFilterItem = JSON.stringify(filteredAdvanceResults);
const timestamp = new Date().toJSON().slice(0, 19).replace("T", " / ");
const filterID = "filterID: " + timestamp;
localStorage.setItem(filterID, newFilterItem);
listSavedFilters();
}
// Function to display local storage list of filters
function listSavedFilters() {
savedSearchDiv.innerHTML = "";
for (let i = 0; i < localStorage.length; i++) {
const timestamp = localStorage.key(i);
if (
timestamp.length === 31 &&
timestamp.indexOf(" / ") === 20 &&
timestamp.split(":").length === 4
) {
const filterDataJSON = localStorage.getItem(timestamp);
const filterData = JSON.parse(filterDataJSON);
const listItem = document.createElement("li");
savedSearchDiv.appendChild(listItem);
const listItemText = document.createElement("span");
listItem.appendChild(listItemText);
const deleteBtn = document.createElement("i");
deleteBtn.classList.add("fa-solid");
deleteBtn.classList.add("fa-trash-can");
listItemText.textContent = `${timestamp.slice(10)}`;
listItem.appendChild(deleteBtn);
deleteBtn.addEventListener("click", () => {
localStorage.removeItem(timestamp);
listSavedFilters();
});
listItemText.addEventListener("click", () => {
filterWrapper.classList.add("hidden");
summaryWrapper.classList.remove("blur");
searchWrapper.classList.remove("blur");
checkResults(filterData);
addMarkersToMap(filterData);
});
}
}
}
// Function to clear all saved filters
function clearSavedSearches() {
const keysToRemove = Object.keys(localStorage).filter(
(item) =>
item.startsWith("filterID: ") &&
item.split(":").length === 4 &&
item.indexOf(" / ") === 20
);
keysToRemove.forEach((key) => localStorage.removeItem(key));
listSavedFilters();
}
function resetResults() {
searchInput.value = "";
nameFilter.value = "";
compositionFilter.value = "";
massMinFilter.value = "";
massMaxFilter.value = "";
yearMinFilter.value = "";
yearMaxFilter.value = "";
filteredResults = [];
filteredAdvanceResults = [];
displayResults();
}
// Initialize the page when the DOM is loaded
document.addEventListener("DOMContentLoaded", initializePage);