-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1288 lines (1109 loc) · 40.6 KB
/
index.html
File metadata and controls
1288 lines (1109 loc) · 40.6 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
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Loop In the Wild</title>
<!-- Google Font for Modern Look -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@100;300;400;500;600&display=swap" rel="stylesheet" />
<!-- Set SVG Favicon -->
<link rel="icon" href="favicon.svg" type="image/svg+xml" />
<!-- Load environment variables -->
<script>
// Load environment variables from Vercel
window.env = {
GOOGLE_MAPS_API_KEY: '%NEXT_PUBLIC_GOOGLE_MAPS_API_KEY%',
GOOGLE_SHEET_ID: '%NEXT_PUBLIC_GOOGLE_SHEET_ID%',
GOOGLE_APPS_SCRIPT_URL: '%NEXT_PUBLIC_GOOGLE_APPS_SCRIPT_URL%'
};
</script>
<style>
body {
margin: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: #ffffff;
color: #1c1c1e;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2rem;
gap: 0.75rem;
background-color: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
position: relative;
z-index: 100; /* Increased z-index to ensure it's above the map */
}
/* Logo and title container */
.header-left {
display: flex;
align-items: center;
gap: 0.75rem;
}
.logo svg {
height: 42px;
width: 42px;
fill: #007aff;
}
h1 {
font-size: 2.5rem;
font-weight: 100;
margin: 0;
line-height: 1.1;
}
.header-controls {
display: flex;
gap: 12px;
position: relative;
z-index: 101; /* Even higher z-index for the controls */
}
.map-container {
width: 100%;
height: calc(100vh - 90px);
position: relative;
cursor: default; /* Default cursor for view mode */
}
/* Controls container */
.map-button {
background-color: white;
border: none;
border-radius: 50%;
width: 56px;
height: 56px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
color: #555;
}
.map-button svg {
width: 24px;
height: 24px;
fill: currentColor;
}
.map-button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.map-button.active {
background-color: #007aff;
color: white;
}
/* Stats panel */
.stats-panel {
position: fixed;
top: 0;
right: -400px;
width: 380px;
height: 100vh;
background-color: white;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
z-index: 1000;
transition: right 0.3s ease;
overflow-y: auto;
padding: 0;
}
.stats-panel.open {
right: 0;
}
.stats-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
border-bottom: 1px solid #eee;
position: sticky;
top: 0;
background: white;
z-index: 2;
}
.stats-header h2 {
margin: 0;
font-weight: 500;
font-size: 1.5rem;
color: #333;
}
.stats-close {
background: none;
border: none;
cursor: pointer;
color: #555;
padding: 8px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.stats-close:hover {
background-color: #f5f5f5;
}
.stats-content {
padding: 20px;
}
.stat-card {
background-color: #f9f9f9;
border-radius: 12px;
padding: 16px;
margin-bottom: 16px;
}
.stat-title {
font-size: 0.9rem;
color: #666;
margin-bottom: 8px;
}
.stat-value {
font-size: 2rem;
font-weight: 600;
color: #333;
margin: 0;
}
.stat-subtitle {
font-size: 0.8rem;
color: #888;
margin-top: 4px;
}
.year-stat {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}
.year-stat:last-child {
border-bottom: none;
}
.year-count {
font-weight: 500;
color: #333;
}
/* Add pin mode indicator */
.add-pin-mode-indicator {
position: fixed;
top: 90px;
left: 50%;
transform: translateX(-50%);
background-color: rgba(0, 122, 255, 0.9);
color: white;
padding: 8px 16px;
border-radius: 24px;
font-size: 0.9rem;
font-weight: 500;
z-index: 900;
display: none;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
}
.add-pin-mode-indicator.visible {
display: block;
animation: fadeInDown 0.3s ease;
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translate(-50%, -20px);
}
to {
opacity: 1;
transform: translate(-50%, 0);
}
}
/* Form styling */
#location-form-container {
background-color: rgba(255, 255, 255, 0.98);
border-radius: 16px;
overflow: hidden;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
max-width: 500px;
width: 90%;
}
#location-form-container h2 {
font-weight: 400;
margin-top: 0;
margin-bottom: 1.5rem;
color: #1c1c1e;
}
#location-form-container form {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
#location-form-container label {
font-size: 0.9rem;
font-weight: 500;
color: #666;
margin-bottom: 0.25rem;
}
#location-form-container input,
#location-form-container select,
#location-form-container textarea {
width: 100%;
padding: 0.75rem;
font-size: 1rem;
border-radius: 8px;
border: 1px solid #ddd;
background-color: #f9f9f9;
font-family: inherit;
transition: border-color 0.2s, box-shadow 0.2s;
}
/* Add styling for the file input */
#location-form-container input[type="file"] {
padding: 0.5rem;
background-color: #fff;
cursor: pointer;
}
/* Add a preview container for the image */
.image-preview {
margin-top: 0.5rem;
width: 100%;
max-height: 150px;
display: flex;
justify-content: center;
align-items: center;
}
.image-preview img {
max-width: 100%;
max-height: 150px;
border-radius: 8px;
display: none; /* Hidden initially */
}
#location-form-container input:focus,
#location-form-container select:focus,
#location-form-container textarea:focus {
border-color: #007aff;
outline: none;
box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.2);
}
#location-form-container .button-group {
display: flex;
gap: 1rem;
margin-top: 0.5rem;
}
#location-form-container button {
padding: 0.75rem 1.25rem;
font-size: 1rem;
border-radius: 8px;
border: none;
cursor: pointer;
font-weight: 500;
transition: background-color 0.2s, transform 0.1s;
}
#location-form-container button[type="submit"] {
background-color: #007aff;
color: white;
flex: 1;
}
#location-form-container button[type="button"] {
background-color: #f1f1f1;
color: #555;
}
#location-form-container button:hover {
opacity: 0.9;
}
#location-form-container button:active {
transform: scale(0.98);
}
/* Info Window Styling */
.gm-style .gm-style-iw-c {
border-radius: 12px;
padding: 12px;
}
.gm-style .gm-style-iw-d {
overflow: hidden !important;
}
/* Map pin animation */
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
/* Responsive styles */
@media (max-width: 600px) {
header {
padding: 1rem;
gap: 0.5rem;
}
.logo svg {
height: 26px;
width: 26px;
}
h1 {
font-size: 1.8rem;
}
#location-form-container {
width: 95%;
padding: 1.5rem;
}
.stats-panel {
width: 100%;
right: -100%;
}
.header-controls {
gap: 8px;
}
}
</style>
<script>
// Get environment variables from the window.env object
const SHEET_ID = window.env.GOOGLE_SHEET_ID;
const API_KEY = window.env.GOOGLE_MAPS_API_KEY;
const APPS_SCRIPT_URL = window.env.GOOGLE_APPS_SCRIPT_URL;
let map; // Ensure map is globally accessible
let isAddPinMode = false; // Track whether we're in add pin mode
async function fetchPins() {
const url = `https://sheets.googleapis.com/v4/spreadsheets/${SHEET_ID}/values/Sheet1?key=${API_KEY}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.values && data.values.length > 0) {
// Skip header row if present
const rows = data.values.length > 1 ? data.values.slice(1) : data.values;
rows.forEach(row => {
if (row.length >= 7) { // Make sure we have at least the core fields
// Map to the correct columns according to sheet layout:
// Timestamp | Year | Month | Name | Description | Latitude | Longitude | City | State | Country
const year = row[1]; // Year is column 2
const month = row[2]; // Month is column 3
const name = row[3]; // Name is column 4
const description = row[4]; // Description is column 5
const lat = parseFloat(row[5]); // Latitude is column 6
const lng = parseFloat(row[6]); // Longitude is column 7
const city = row.length > 7 ? row[7] : ""; // City is column 8 (if exists)
const state = row.length > 8 ? row[8] : ""; // State is column 9 (if exists)
const country = row.length > 9 ? row[9] : ""; // Country is column 10 (if exists)
if (!isNaN(lat) && !isNaN(lng)) {
addPinToMap({
year,
lat,
lng,
name,
description,
month,
city,
state,
country
});
}
}
});
}
} catch (error) {
console.error("Error fetching pins:", error);
}
}
async function addPinToSheet(pin) {
// Better logging to debug state and country data
console.log("=== PIN DATA DEBUG ===");
console.log("About to submit pin with following data:");
console.log("City:", pin.city || "MISSING");
console.log("State:", pin.state || "MISSING");
console.log("Country:", pin.country || "MISSING");
console.log("Full pin object:", pin);
console.log("====================");
// Create a virtual form element
const form = document.createElement('form');
form.action = APPS_SCRIPT_URL;
form.method = 'POST';
// Add all pin data as form fields
const addField = (name, value) => {
const field = document.createElement('input');
field.type = 'hidden';
field.name = name;
field.value = value || '';
form.appendChild(field);
// Log each field we're adding
console.log(`Adding form field: ${name} = ${value || 'EMPTY'}`);
};
// Add all fields from the pin object
addField('year', pin.year);
addField('lat', pin.lat);
addField('lng', pin.lng);
addField('name', pin.name);
addField('description', pin.description);
addField('month', pin.month);
addField('city', pin.city);
addField('state', pin.state);
addField('country', pin.country);
addField('photoData', pin.photoData); // Add photo data field
// Create a hidden iframe to prevent opening a new tab
const iframe = document.createElement('iframe');
iframe.name = 'hidden-form-iframe';
iframe.style.display = 'none';
document.body.appendChild(iframe);
form.target = 'hidden-form-iframe';
// Listen for the iframe load event to detect form submission completion
iframe.addEventListener('load', function() {
console.log("Form submission completed (iframe loaded)");
try {
// Try to get response content from iframe (may fail due to CORS)
const iframeContent = iframe.contentDocument || iframe.contentWindow.document;
console.log("Iframe response:", iframeContent.body.innerText);
} catch (e) {
console.log("Could not read iframe response due to CORS restrictions");
}
});
// Append the form to the document, submit it, and remove it
document.body.appendChild(form);
console.log("Submitting form to Google Apps Script...");
form.submit();
// Remove the form and iframe after submission (with a delay)
setTimeout(() => {
document.body.removeChild(form);
document.body.removeChild(iframe);
console.log("Form and iframe removed from DOM");
}, 5000); // Longer delay to ensure data is processed
// Schedule a refresh of the stats after a short delay
setTimeout(() => {
refreshStateAndCountryCounts();
}, 5000); // Longer delay to ensure data is processed
return true;
}
async function geocodeLatLng(lat, lng) {
const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${API_KEY}`;
console.log(`Geocoding request for: ${lat}, ${lng}`);
try {
const response = await fetch(url);
const geo = await response.json();
let city = "";
let state = "";
let country = "";
console.log("Geocoding API response status:", geo.status);
if (geo.status === "OK" && geo.results.length > 0) {
// Process all results to find the best address components
for (let i = 0; i < Math.min(geo.results.length, 5); i++) {
const result = geo.results[i];
const components = result.address_components;
if (!components || !components.length) continue;
// First pass: look for exact type matches
for (const component of components) {
if (!component.types) continue;
// City/locality
if (component.types.includes("locality")) {
city = component.long_name;
}
// State/province (administrative_area_level_1)
else if (component.types.includes("administrative_area_level_1")) {
state = component.long_name;
}
// Country
else if (component.types.includes("country")) {
country = component.long_name;
}
}
// If we've found all three components, break out
if (city && state && country) break;
}
// Second pass: If still missing data, look for alternate terms
if (!city || !state || !country) {
for (let i = 0; Math.min(geo.results.length, 5); i++) {
const result = geo.results[i];
const components = result.address_components;
if (!components || !components.length) continue;
for (const component of components) {
if (!component.types) continue;
// Alternative city lookups
if (!city && (
component.types.includes("postal_town") ||
component.types.includes("administrative_area_level_3") ||
component.types.includes("sublocality_level_1") ||
component.types.includes("sublocality")
)) {
city = component.long_name;
}
// Alternative state lookups
if (!state && component.types.includes("administrative_area_level_2")) {
state = component.long_name;
}
}
}
}
// Final fallback: Use formatted address parts for any still-missing components
if (!city || !state || !country) {
const firstResult = geo.results[0];
if (firstResult && firstResult.formatted_address) {
const parts = firstResult.formatted_address.split(',').map(p => p.trim());
// Simplistic approach: first part might be city, second-to-last might be state, last part might be country
if (parts.length >= 3) {
if (!city) city = parts[0];
if (!state) state = parts[parts.length - 2];
if (!country) country = parts[parts.length - 1];
}
else if (parts.length === 2) {
if (!city) city = parts[0];
if (!country) country = parts[1];
}
}
}
} else {
console.warn(`Geocoding API returned status: ${geo.status}`);
}
console.log("Final geocoded location:", { city, state, country });
return { city, state, country };
} catch (error) {
console.error("Error geocoding location:", error);
return { city: "", state: "", country: "" };
}
}
async function handleFormSubmit(event) {
event.preventDefault();
const name = document.getElementById("name").value;
const month = document.getElementById("month").value;
const description = document.getElementById("description").value;
const year = document.getElementById("year").value;
const lat = parseFloat(document.getElementById("latitude").value);
const lng = parseFloat(document.getElementById("longitude").value);
// Process photo if one was uploaded
let photoData = "";
const photoInput = document.getElementById("photo");
if (photoInput.files && photoInput.files[0]) {
try {
photoData = await convertImageToBase64(photoInput.files[0]);
} catch (error) {
console.error("Error processing image:", error);
}
}
// Geocode location to get city, state, country
const locationData = await geocodeLatLng(lat, lng);
// Store the location data directly in variables
const city = locationData.city || "";
const state = locationData.state || "";
const country = locationData.country || "";
// Update the hidden form fields
document.getElementById("city").value = city;
document.getElementById("state").value = state;
document.getElementById("country").value = country;
// Log the values for debugging
console.log("Form location data:", {
city: city,
state: state,
country: country
});
// Create the pin object with ALL location data
const pin = {
year,
lat,
lng,
name,
description,
month,
city,
state,
country,
photoData // Add the photo data to the pin object
};
// Log the complete pin data
console.log("Complete pin data to be saved:", {...pin, photoData: photoData ? "Base64 data (truncated)" : "None" });
// Add to map and save to sheet
addPinToMap(pin);
try {
await addPinToSheet(pin);
console.log("Pin successfully saved to sheet");
// Force refresh of state and country counts after successful save
setTimeout(() => {
refreshStateAndCountryCounts();
}, 2000);
} catch (error) {
console.error("Error saving pin:", error);
}
// Reset and close form
event.target.reset();
document.getElementById("location-form-container").style.display = "none";
}
function addPinToMap({ year, lat, lng, name, description, month }) {
const color = getColorByYear(year);
// Create a DOM element for the marker content
const markerContent = document.createElement("div");
markerContent.style.backgroundColor = color;
markerContent.style.width = "16px";
markerContent.style.height = "16px";
markerContent.style.borderRadius = "50%";
markerContent.style.border = "2px solid white";
markerContent.style.boxShadow = "0 2px 4px rgba(0,0,0,0.3)";
markerContent.style.cursor = "pointer"; // Set cursor to pointer for pins
// Create the advanced marker element
const marker = new google.maps.marker.AdvancedMarkerElement({
position: { lat, lng },
map,
title: name,
content: markerContent,
zIndex: 100, // Ensure pins are above other map elements
});
// Store pin data with marker to ensure it's available on click
marker.pinData = { year, lat, lng, name, description, month };
// Add direct click handler
markerContent.addEventListener('click', function(e) {
e.stopPropagation();
e.preventDefault();
// Log to debug
console.log("Pin clicked:", marker.pinData);
// Create info window content
const contentDiv = document.createElement("div");
contentDiv.style.padding = "15px";
contentDiv.style.maxWidth = "300px";
contentDiv.innerHTML = `
<h3 style="margin-top: 0;">${name}</h3>
<p><strong>Year:</strong> ${year}</p>
<p><strong>Month:</strong> ${month || "N/A"}</p>
<p><strong>Description:</strong> ${description}</p>
<p><strong>Location:</strong> ${lat.toFixed(6)}, ${lng.toFixed(6)}</p>
`;
// If we already have an active info window, close it
if (window.activeInfoWindow) {
window.activeInfoWindow.close();
}
// Create a new info window
const infoWindow = new google.maps.InfoWindow({
content: contentDiv,
});
infoWindow.open({
map,
anchor: marker,
});
// Store reference to open info window
window.activeInfoWindow = infoWindow;
return false;
});
}
function getColorByYear(year) {
// Generate colors based on year (using a consistent algorithm)
const yearNum = parseInt(year);
const baseYear = 2018;
const colorOptions = [
"#FF5252", // Red
"#FF9800", // Orange
"#FFEB3B", // Yellow
"#4CAF50", // Green
"#2196F3", // Blue
"#673AB7", // Purple
"#E91E63", // Pink
"#795548" // Brown
];
const index = (yearNum - baseYear) % colorOptions.length;
return colorOptions[index];
}
function populateYearDropdown() {
const yearSelect = document.getElementById("year");
yearSelect.innerHTML = ""; // Clear existing options
const currentYear = new Date().getFullYear();
for (let year = 2018; year <= currentYear; year++) {
const option = document.createElement("option");
option.value = year;
option.textContent = year;
yearSelect.appendChild(option);
}
// Set current year as default
yearSelect.value = currentYear;
}
function populateMonthDropdown() {
const monthSelect = document.getElementById("month");
monthSelect.innerHTML = ""; // Clear existing options
const months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
months.forEach((month, index) => {
const option = document.createElement("option");
option.value = month;
option.textContent = month;
monthSelect.appendChild(option);
});
// Set current month as default
const currentMonth = new Date().getMonth();
monthSelect.selectedIndex = currentMonth;
}
// Make sure dropdowns always show current year/month when form opens
function resetForm() {
// Reset the form itself
document.getElementById("location-form-container").querySelector("form").reset();
// Explicitly set the current year and month again
const currentYear = new Date().getFullYear();
const currentMonth = new Date().getMonth();
document.getElementById("year").value = currentYear;
document.getElementById("month").selectedIndex = currentMonth;
}
function closeForm() {
document.getElementById("location-form-container").style.display = "none";
// Reset form values when closing
resetForm();
}
function setupMapControls() {
// Add Pin Button Toggle
const addPinButton = document.getElementById('add-pin-button');
const addPinIndicator = document.getElementById('add-pin-mode-indicator');
const mapContainer = document.querySelector('.map-container');
addPinButton.addEventListener('click', () => {
isAddPinMode = !isAddPinMode;
// Update UI
if (isAddPinMode) {
addPinButton.classList.add('active');
addPinIndicator.classList.add('visible');
mapContainer.style.cursor = 'crosshair';
} else {
addPinButton.classList.remove('active');
addPinIndicator.classList.remove('visible');
mapContainer.style.cursor = 'default';
}
});
// Stats Button and Panel
const statsButton = document.getElementById('stats-button');
const statsPanel = document.getElementById('stats-panel');
const closeStatsButton = document.getElementById('close-stats');
statsButton.addEventListener('click', () => {
// Open stats panel
statsPanel.classList.add('open');
// Generate stats when opening
generateTravelStats();
});
closeStatsButton.addEventListener('click', () => {
// Close stats panel
statsPanel.classList.remove('open');
});
}
async function generateTravelStats() {
const statsContent = document.getElementById('stats-content');
statsContent.innerHTML = '<p>Loading stats...</p>';
try {
// Fetch all pins data
const response = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${SHEET_ID}/values/Sheet1?key=${API_KEY}`);
const data = await response.json();
if (!data.values || data.values.length <= 1) {
statsContent.innerHTML = '<p>No travel data available yet.</p>';
return;
}
const rows = data.values.length > 1 ? data.values.slice(1) : data.values;
const totalTrips = rows.length;
const yearCounts = {};
const monthCounts = {};
const locations = new Set();
// Track unique states and countries directly here
const uniqueStates = new Set();
const uniqueCountries = new Set();
const uniqueCities = new Set();
// Column indices based on actual spreadsheet structure:
// Timestamp[0], Year[1], Month[2], Name[3], Description[4], Latitude[5], Longitude[6], City[7], State[8], Country[9]
rows.forEach(row => {
// Year is index 1
const year = row[1];
yearCounts[year] = (yearCounts[year] || 0) + 1;
// Month is at index 2 according to your spreadsheet structure
const month = row[2];
if (month) {
monthCounts[month] = (monthCounts[month] || 0) + 1;
}
// Parse lat/lng from columns 5 and 6
if (row[5] && row[6]) {
const lat = parseFloat(row[5]);
const lng = parseFloat(row[6]);
locations.add(`${lat.toFixed(1)},${lng.toFixed(1)}`);
}
// Get city, state and country data
const city = row[7]; // City is at index 7
const state = row[8]; // State is at index 8
const country = row[9]; // Country is at index 9
if (city && city.trim() !== "") {
uniqueCities.add(city.trim());
}
if (state && state.trim() !== "") {
uniqueStates.add(state.trim());
}
if (country && country.trim() !== "") {
uniqueCountries.add(country.trim());
}
});
// Get the counts directly from our Sets
const citiesVisited = uniqueCities.size;
const statesVisited = uniqueStates.size;
const countriesVisited = uniqueCountries.size;
let statsHTML = `
<div class="stat-card">
<div class="stat-title">Total Trips</div>
<div class="stat-value">${totalTrips}</div>
</div>
<div class="stat-card">
<div class="stat-title">Unique Cities</div>
<div class="stat-value">${citiesVisited}</div>
<div class="stat-subtitle">Count of Unique Cities Visited</div>
</div>
<div class="stat-card">
<div class="stat-title">States Visited</div>
<div class="stat-value">${statesVisited}</div>
<div class="stat-subtitle">Count of Unique States Visited</div>
</div>
<div class="stat-card">
<div class="stat-title">Countries Visited</div>
<div class="stat-value">${countriesVisited}</div>
<div class="stat-subtitle">Count of Unique Countries Visited</div>
</div>
<div class="stat-card">
<div class="stat-title">Travel by Year</div>
<div style="margin-top: 12px;">
`;
const sortedYears = Object.keys(yearCounts).sort((a, b) => b - a);
sortedYears.forEach(year => {
statsHTML += `
<div class="year-stat">
<span>${year}</span>
<span class="year-count">${yearCounts[year]} trips</span>
</div>
`;
});
statsHTML += `
</div>
</div>
<div class="stat-card">
<div class="stat-title">Most Visited Months</div>