-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathocean-crosser.html
More file actions
834 lines (732 loc) · 34.5 KB
/
ocean-crosser.html
File metadata and controls
834 lines (732 loc) · 34.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Ocean Crosser - What's Across the Water?</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(to bottom, #87CEEB 0%, #4A90E2 100%);
height: 100vh;
overflow: hidden;
color: white;
}
#container {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 20px;
}
#header {
text-align: center;
background: rgba(0, 0, 0, 0.3);
padding: 15px;
border-radius: 10px;
}
#header h1 {
font-size: 24px;
margin-bottom: 5px;
}
#status {
font-size: 14px;
color: #FFD700;
}
#compass-container {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
position: relative;
overflow: hidden;
}
/* Horizon view - like looking at the ocean */
#compass {
width: 100%;
height: 100%;
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
/* Compass strip that scrolls horizontally */
#compass-strip {
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 80px;
background: rgba(0, 0, 0, 0.6);
border-top: 2px solid rgba(255, 255, 255, 0.5);
border-bottom: 2px solid rgba(255, 255, 255, 0.5);
display: flex;
align-items: center;
overflow: hidden;
}
#compass-tape {
display: flex;
position: absolute;
height: 100%;
transition: transform 0.1s ease-out;
white-space: nowrap;
}
.compass-mark {
display: inline-flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 60px;
font-weight: bold;
color: rgba(255, 255, 255, 0.8);
}
.compass-mark.major {
font-size: 20px;
color: #FFD700;
}
/* Center crosshair */
#crosshair {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40px;
height: 40px;
pointer-events: none;
z-index: 100;
}
#crosshair::before,
#crosshair::after {
content: '';
position: absolute;
background: #FF4444;
}
#crosshair::before {
left: 50%;
top: 0;
width: 3px;
height: 100%;
margin-left: -1.5px;
}
#crosshair::after {
top: 50%;
left: 0;
height: 3px;
width: 100%;
margin-top: -1.5px;
}
#heading-display {
position: absolute;
top: 20%;
left: 50%;
transform: translateX(-50%);
font-size: 64px;
font-weight: bold;
text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.8);
z-index: 10;
color: #FFD700;
}
#sensor-debug {
position: absolute;
top: 10px;
left: 10px;
background: rgba(0, 0, 0, 0.8);
padding: 10px;
border-radius: 5px;
font-size: 12px;
font-family: monospace;
z-index: 150;
max-width: 200px;
}
#sensor-debug div {
margin: 2px 0;
}
#destination {
background: rgba(0, 0, 0, 0.5);
padding: 20px;
border-radius: 10px;
text-align: center;
}
#destination-name {
font-size: 28px;
font-weight: bold;
margin-bottom: 10px;
color: #FFD700;
}
#destination-details {
font-size: 16px;
line-height: 1.5;
}
#controls {
background: rgba(0, 0, 0, 0.3);
padding: 15px;
border-radius: 10px;
text-align: center;
margin-top: 10px;
margin-bottom: 160px;
position: relative;
z-index: 10;
}
button {
background: #4CAF50;
color: white;
border: none;
padding: 18px 40px;
font-size: 18px;
font-weight: bold;
border-radius: 8px;
cursor: pointer;
margin: 5px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
button:disabled {
background: #cccccc;
cursor: not-allowed;
}
.error {
color: #FF6B6B;
}
#debug {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.9);
padding: 10px;
font-size: 11px;
max-height: 150px;
overflow-y: auto;
z-index: 5;
border-top: 2px solid #4CAF50;
}
</style>
</head>
<body>
<div id="container">
<div id="header">
<h1>🌊 Ocean Crosser</h1>
<div id="status">Initializing...</div>
</div>
<div id="compass-container">
<div id="compass">
<div id="sensor-debug" style="display: none;">
<div><strong>Raw Sensors:</strong></div>
<div id="sensor-alpha">α: --</div>
<div id="sensor-beta">β: --</div>
<div id="sensor-gamma">γ: --</div>
<div id="sensor-absolute">Absolute: --</div>
<div id="sensor-webkit">WebKit: --</div>
<div id="sensor-calculated">Calc: --</div>
</div>
<div id="heading-display">--°</div>
<div id="crosshair"></div>
<div id="compass-strip">
<div id="compass-tape"></div>
</div>
</div>
</div>
<div id="destination">
<div id="destination-name">Point your phone at the horizon</div>
<div id="destination-details">
<div id="distance">--</div>
<div id="location-info">--</div>
</div>
</div>
<div id="controls">
<button id="start-btn">Enable Compass</button>
</div>
</div>
<div id="debug" style="display: none;"></div>
<script>
// Comprehensive dataset of major coastal cities and landmarks
const COASTAL_DESTINATIONS = [
// North America - East Coast
{ name: "New York City, USA", lat: 40.7128, lon: -74.0060, country: "USA" },
{ name: "Miami, USA", lat: 25.7617, lon: -80.1918, country: "USA" },
{ name: "Boston, USA", lat: 42.3601, lon: -71.0589, country: "USA" },
{ name: "Charleston, USA", lat: 32.7765, lon: -79.9311, country: "USA" },
{ name: "Halifax, Canada", lat: 44.6488, lon: -63.5752, country: "Canada" },
// North America - West Coast
{ name: "Los Angeles, USA", lat: 34.0522, lon: -118.2437, country: "USA" },
{ name: "San Francisco, USA", lat: 37.7749, lon: -122.4194, country: "USA" },
{ name: "Seattle, USA", lat: 47.6062, lon: -122.3321, country: "USA" },
{ name: "Vancouver, Canada", lat: 49.2827, lon: -123.1207, country: "Canada" },
{ name: "San Diego, USA", lat: 32.7157, lon: -117.1611, country: "USA" },
// Central/South America
{ name: "Cancún, Mexico", lat: 21.1619, lon: -86.8515, country: "Mexico" },
{ name: "Rio de Janeiro, Brazil", lat: -22.9068, lon: -43.1729, country: "Brazil" },
{ name: "Buenos Aires, Argentina", lat: -34.6037, lon: -58.3816, country: "Argentina" },
{ name: "Lima, Peru", lat: -12.0464, lon: -77.0428, country: "Peru" },
{ name: "Cartagena, Colombia", lat: 10.3910, lon: -75.4794, country: "Colombia" },
{ name: "Valparaíso, Chile", lat: -33.0472, lon: -71.6127, country: "Chile" },
// Europe - West
{ name: "Lisbon, Portugal", lat: 38.7223, lon: -9.1393, country: "Portugal" },
{ name: "London, UK", lat: 51.5074, lon: -0.1278, country: "UK" },
{ name: "Dublin, Ireland", lat: 53.3498, lon: -6.2603, country: "Ireland" },
{ name: "Amsterdam, Netherlands", lat: 52.3676, lon: 4.9041, country: "Netherlands" },
{ name: "Barcelona, Spain", lat: 41.3851, lon: 2.1734, country: "Spain" },
{ name: "Marseille, France", lat: 43.2965, lon: 5.3698, country: "France" },
{ name: "Nice, France", lat: 43.7102, lon: 7.2620, country: "France" },
{ name: "Reykjavik, Iceland", lat: 64.1466, lon: -21.9426, country: "Iceland" },
// Europe - Mediterranean
{ name: "Rome, Italy", lat: 41.9028, lon: 12.4964, country: "Italy" },
{ name: "Athens, Greece", lat: 37.9838, lon: 23.7275, country: "Greece" },
{ name: "Istanbul, Turkey", lat: 41.0082, lon: 28.9784, country: "Turkey" },
{ name: "Venice, Italy", lat: 45.4408, lon: 12.3155, country: "Italy" },
// Africa
{ name: "Casablanca, Morocco", lat: 33.5731, lon: -7.5898, country: "Morocco" },
{ name: "Lagos, Nigeria", lat: 6.5244, lon: 3.3792, country: "Nigeria" },
{ name: "Cape Town, South Africa", lat: -33.9249, lon: 18.4241, country: "South Africa" },
{ name: "Alexandria, Egypt", lat: 31.2001, lon: 29.9187, country: "Egypt" },
{ name: "Dakar, Senegal", lat: 14.7167, lon: -17.4677, country: "Senegal" },
{ name: "Mombasa, Kenya", lat: -4.0435, lon: 39.6682, country: "Kenya" },
// Middle East
{ name: "Dubai, UAE", lat: 25.2048, lon: 55.2708, country: "UAE" },
{ name: "Tel Aviv, Israel", lat: 32.0853, lon: 34.7818, country: "Israel" },
{ name: "Beirut, Lebanon", lat: 33.8938, lon: 35.5018, country: "Lebanon" },
// Asia - East
{ name: "Tokyo, Japan", lat: 35.6762, lon: 139.6503, country: "Japan" },
{ name: "Shanghai, China", lat: 31.2304, lon: 121.4737, country: "China" },
{ name: "Hong Kong", lat: 22.3193, lon: 114.1694, country: "Hong Kong" },
{ name: "Seoul, South Korea", lat: 37.5665, lon: 126.9780, country: "South Korea" },
{ name: "Osaka, Japan", lat: 34.6937, lon: 135.5023, country: "Japan" },
{ name: "Manila, Philippines", lat: 14.5995, lon: 120.9842, country: "Philippines" },
// Asia - Southeast
{ name: "Singapore", lat: 1.3521, lon: 103.8198, country: "Singapore" },
{ name: "Bangkok, Thailand", lat: 13.7563, lon: 100.5018, country: "Thailand" },
{ name: "Ho Chi Minh City, Vietnam", lat: 10.8231, lon: 106.6297, country: "Vietnam" },
{ name: "Jakarta, Indonesia", lat: -6.2088, lon: 106.8456, country: "Indonesia" },
{ name: "Bali, Indonesia", lat: -8.4095, lon: 115.1889, country: "Indonesia" },
// Asia - South
{ name: "Mumbai, India", lat: 19.0760, lon: 72.8777, country: "India" },
{ name: "Chennai, India", lat: 13.0827, lon: 80.2707, country: "India" },
{ name: "Colombo, Sri Lanka", lat: 6.9271, lon: 79.8612, country: "Sri Lanka" },
{ name: "Karachi, Pakistan", lat: 24.8607, lon: 67.0011, country: "Pakistan" },
// Oceania
{ name: "Sydney, Australia", lat: -33.8688, lon: 151.2093, country: "Australia" },
{ name: "Melbourne, Australia", lat: -37.8136, lon: 144.9631, country: "Australia" },
{ name: "Perth, Australia", lat: -31.9505, lon: 115.8605, country: "Australia" },
{ name: "Auckland, New Zealand", lat: -36.8485, lon: 174.7633, country: "New Zealand" },
{ name: "Wellington, New Zealand", lat: -41.2865, lon: 174.7762, country: "New Zealand" },
// Pacific Islands
{ name: "Honolulu, Hawaii", lat: 21.3099, lon: -157.8581, country: "USA" },
{ name: "Papeete, Tahiti", lat: -17.5516, lon: -149.5585, country: "French Polynesia" },
{ name: "Fiji", lat: -17.7134, lon: 178.0650, country: "Fiji" },
// Caribbean
{ name: "Havana, Cuba", lat: 23.1136, lon: -82.3666, country: "Cuba" },
{ name: "San Juan, Puerto Rico", lat: 18.4655, lon: -66.1057, country: "Puerto Rico" },
{ name: "Kingston, Jamaica", lat: 17.9714, lon: -76.7931, country: "Jamaica" },
// Arctic/Northern
{ name: "Murmansk, Russia", lat: 68.9585, lon: 33.0827, country: "Russia" },
{ name: "Anchorage, Alaska", lat: 61.2181, lon: -149.9003, country: "USA" },
// Antarctica
{ name: "Antarctica (Palmer Station)", lat: -64.7744, lon: -64.0489, country: "Antarctica" },
{ name: "Antarctica (McMurdo)", lat: -77.8463, lon: 166.6686, country: "Antarctica" }
];
// State
let userLocation = null;
let currentHeading = 0;
let smoothedHeading = 0;
let isCompassActive = false;
let debugMode = true; // Set to true to see debug info
const SMOOTHING_FACTOR = 0.15; // Lower = smoother but slower response
// DOM elements
const statusEl = document.getElementById('status');
const headingDisplayEl = document.getElementById('heading-display');
const compassTapeEl = document.getElementById('compass-tape');
const destinationNameEl = document.getElementById('destination-name');
const distanceEl = document.getElementById('distance');
const locationInfoEl = document.getElementById('location-info');
const startBtn = document.getElementById('start-btn');
const debugEl = document.getElementById('debug');
const sensorDebugEl = document.getElementById('sensor-debug');
const sensorAlphaEl = document.getElementById('sensor-alpha');
const sensorBetaEl = document.getElementById('sensor-beta');
const sensorGammaEl = document.getElementById('sensor-gamma');
const sensorAbsoluteEl = document.getElementById('sensor-absolute');
const sensorWebkitEl = document.getElementById('sensor-webkit');
const sensorCalculatedEl = document.getElementById('sensor-calculated');
if (debugMode) {
debugEl.style.display = 'block';
sensorDebugEl.style.display = 'block';
}
// Create compass tape with cardinal directions
function createCompassTape() {
const directions = [
{ deg: 0, label: 'N', major: true },
{ deg: 45, label: 'NE', major: false },
{ deg: 90, label: 'E', major: true },
{ deg: 135, label: 'SE', major: false },
{ deg: 180, label: 'S', major: true },
{ deg: 225, label: 'SW', major: false },
{ deg: 270, label: 'W', major: true },
{ deg: 315, label: 'NW', major: false }
];
// Create tape 3 times to allow seamless wrapping
for (let repeat = 0; repeat < 3; repeat++) {
directions.forEach(dir => {
const mark = document.createElement('div');
mark.className = dir.major ? 'compass-mark major' : 'compass-mark';
mark.textContent = dir.label;
mark.dataset.degree = dir.deg;
compassTapeEl.appendChild(mark);
});
}
}
createCompassTape();
// Utility functions
function log(message) {
console.log(message);
if (debugMode) {
debugEl.innerHTML += `${new Date().toLocaleTimeString()}: ${message}<br>`;
debugEl.scrollTop = debugEl.scrollHeight;
}
}
function toRadians(degrees) {
return degrees * Math.PI / 180;
}
function toDegrees(radians) {
return radians * 180 / Math.PI;
}
// Smooth heading changes to reduce jitter
function smoothHeading(newHeading, oldHeading) {
// Handle angle wrapping (359° to 1° transition)
let diff = newHeading - oldHeading;
if (diff > 180) diff -= 360;
if (diff < -180) diff += 360;
let smoothed = oldHeading + (diff * SMOOTHING_FACTOR);
smoothed = (smoothed + 360) % 360; // Normalize to 0-360
return smoothed;
}
// Calculate distance between two points using Haversine formula
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth's radius in km
const dLat = toRadians(lat2 - lat1);
const dLon = toRadians(lon2 - lon1);
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
// Calculate initial bearing from point A to point B
function calculateBearing(lat1, lon1, lat2, lon2) {
const dLon = toRadians(lon2 - lon1);
const y = Math.sin(dLon) * Math.cos(toRadians(lat2));
const x = Math.cos(toRadians(lat1)) * Math.sin(toRadians(lat2)) -
Math.sin(toRadians(lat1)) * Math.cos(toRadians(lat2)) * Math.cos(dLon);
let bearing = toDegrees(Math.atan2(y, x));
return (bearing + 360) % 360; // Normalize to 0-360
}
// Find the closest destination in a given direction
function findDestinationInDirection(userLat, userLon, heading) {
let bestMatch = null;
let smallestAngleDiff = 180;
const toleranceAngle = 30; // degrees of tolerance
COASTAL_DESTINATIONS.forEach(dest => {
const bearing = calculateBearing(userLat, userLon, dest.lat, dest.lon);
let angleDiff = Math.abs(bearing - heading);
// Handle angle wrapping (e.g., 359° vs 1°)
if (angleDiff > 180) {
angleDiff = 360 - angleDiff;
}
// Only consider destinations within tolerance and closer than current best
if (angleDiff < toleranceAngle && angleDiff < smallestAngleDiff) {
smallestAngleDiff = angleDiff;
bestMatch = {
...dest,
bearing: bearing,
distance: calculateDistance(userLat, userLon, dest.lat, dest.lon),
angleDiff: angleDiff
};
}
});
return bestMatch;
}
// Format distance for display
function formatDistance(km) {
if (km < 1) {
return `${Math.round(km * 1000)} meters`;
} else if (km < 100) {
return `${km.toFixed(1)} km`;
} else {
return `${Math.round(km)} km (${Math.round(km * 0.621371)} miles)`;
}
}
// Get user's location
function getUserLocation() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation not supported'));
return;
}
statusEl.textContent = 'Requesting location permission...';
log('Requesting geolocation permission');
navigator.geolocation.getCurrentPosition(
(position) => {
userLocation = {
lat: position.coords.latitude,
lon: position.coords.longitude
};
log(`Location granted: ${userLocation.lat.toFixed(4)}, ${userLocation.lon.toFixed(4)}`);
statusEl.textContent = 'Location acquired';
resolve(userLocation);
},
(error) => {
log(`Geolocation error: ${error.code} - ${error.message}`);
let errorMsg = 'Location access denied';
if (error.code === 1) {
errorMsg = 'Location permission denied by user';
} else if (error.code === 2) {
errorMsg = 'Location unavailable';
} else if (error.code === 3) {
errorMsg = 'Location request timed out';
}
statusEl.innerHTML = `<span class="error">${errorMsg}</span>`;
reject(error);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
});
}
// Calculate compass heading from device orientation for vertical phone position
function calculateCompassHeading(alpha, beta, gamma) {
// Convert to radians
const alphaRad = toRadians(alpha);
const betaRad = toRadians(beta);
const gammaRad = toRadians(gamma);
// Calculate compass heading accounting for device tilt
// This works when phone is held vertically (portrait mode)
const compassHeading = Math.atan2(
-Math.sin(gammaRad) * Math.cos(betaRad),
Math.cos(gammaRad) * Math.cos(betaRad) * Math.cos(alphaRad) +
Math.sin(betaRad) * Math.sin(alphaRad)
);
// Convert to degrees and normalize to 0-360
let heading = toDegrees(compassHeading);
heading = (heading + 360) % 360;
return heading;
}
// Handle device orientation
let orientationEventCount = 0;
function handleOrientation(event) {
if (!isCompassActive || !userLocation) return;
// Update sensor debug display
if (sensorDebugEl) {
sensorAlphaEl.textContent = `α: ${event.alpha !== null ? event.alpha.toFixed(1) : 'null'}°`;
sensorBetaEl.textContent = `β: ${event.beta !== null ? event.beta.toFixed(1) : 'null'}°`;
sensorGammaEl.textContent = `γ: ${event.gamma !== null ? event.gamma.toFixed(1) : 'null'}°`;
sensorAbsoluteEl.textContent = `Absolute: ${event.absolute ? 'yes' : 'no'}`;
sensorWebkitEl.textContent = `WebKit: ${event.webkitCompassHeading !== undefined ? event.webkitCompassHeading.toFixed(1) + '°' : 'n/a'}`;
}
// Log first event for debugging
if (orientationEventCount === 0) {
log(`First orientation event received - alpha: ${event.alpha}, beta: ${event.beta}, gamma: ${event.gamma}, webkitCompassHeading: ${event.webkitCompassHeading}`);
}
orientationEventCount++;
// Get compass heading
let heading = null;
if (event.webkitCompassHeading !== undefined) {
// iOS - webkitCompassHeading is already calibrated
heading = event.webkitCompassHeading;
if (orientationEventCount === 1) log('Using iOS webkitCompassHeading');
} else if (event.alpha !== null && event.beta !== null && event.gamma !== null) {
// Android - calculate heading from orientation data
// Check if phone is roughly vertical (beta between 45 and 135 degrees)
if (Math.abs(event.beta) > 45 && Math.abs(event.beta) < 135) {
// Phone is vertical - use proper calculation
heading = calculateCompassHeading(event.alpha, event.beta, event.gamma);
if (orientationEventCount === 1) log('Using calculated heading for vertical orientation');
} else {
// Phone is flat - use simple alpha
heading = 360 - event.alpha;
if (orientationEventCount === 1) log('Using simple alpha for flat orientation');
}
}
if (heading !== null) {
currentHeading = heading;
if (sensorDebugEl) {
sensorCalculatedEl.textContent = `Calc: ${heading.toFixed(1)}°`;
}
// Apply smoothing to reduce jitter
smoothedHeading = orientationEventCount === 1 ? heading : smoothHeading(heading, smoothedHeading);
updateDisplay(Math.round(smoothedHeading));
} else {
if (orientationEventCount === 1) log('Warning: No valid heading data available');
}
}
// Handle device orientation for Android (alternative method)
let absoluteEventCount = 0;
function handleOrientationAbsolute(event) {
if (!isCompassActive || !userLocation) return;
if (absoluteEventCount === 0) {
log(`First absolute orientation event - absolute: ${event.absolute}, alpha: ${event.alpha}, beta: ${event.beta}, gamma: ${event.gamma}`);
}
absoluteEventCount++;
if (event.absolute && event.alpha !== null && event.beta !== null && event.gamma !== null) {
let heading = null;
// Check if phone is roughly vertical (beta between 45 and 135 degrees)
if (Math.abs(event.beta) > 45 && Math.abs(event.beta) < 135) {
// Phone is vertical - use proper calculation
heading = calculateCompassHeading(event.alpha, event.beta, event.gamma);
if (absoluteEventCount === 1) log('Using calculated heading for vertical orientation (absolute)');
} else {
// Phone is flat - use simple alpha
heading = 360 - event.alpha;
if (absoluteEventCount === 1) log('Using simple alpha for flat orientation (absolute)');
}
currentHeading = heading;
// Apply smoothing to reduce jitter
smoothedHeading = absoluteEventCount === 1 ? heading : smoothHeading(heading, smoothedHeading);
updateDisplay(Math.round(smoothedHeading));
}
}
// Update display with current heading
function updateDisplay(heading) {
// Update heading display
headingDisplayEl.textContent = `${heading}°`;
// Move compass tape (negative because we want the tape to move opposite of heading)
// 60px per direction mark, 8 marks = 480px for 360°
// Middle repeat starts at -480px (8 marks * 60px)
const pixelsPerDegree = 480 / 360; // 1.333px per degree
const offset = -heading * pixelsPerDegree - 480; // -480 to start at middle repeat
compassTapeEl.style.transform = `translateX(${offset}px)`;
// Find destination in this direction
const destination = findDestinationInDirection(
userLocation.lat,
userLocation.lon,
heading
);
if (destination) {
destinationNameEl.textContent = destination.name;
distanceEl.textContent = `${formatDistance(destination.distance)} away`;
locationInfoEl.textContent = `Bearing: ${Math.round(destination.bearing)}° | Match accuracy: ${Math.round((30 - destination.angleDiff) / 30 * 100)}%`;
statusEl.textContent = 'Tracking...';
} else {
destinationNameEl.textContent = 'Open Ocean';
distanceEl.textContent = 'No major landmass in this direction';
locationInfoEl.textContent = 'Try pointing in a different direction';
statusEl.textContent = 'No destination found';
}
}
// Request device orientation permission (iOS 13+)
async function requestOrientationPermission() {
if (typeof DeviceOrientationEvent !== 'undefined' &&
typeof DeviceOrientationEvent.requestPermission === 'function') {
try {
log('iOS detected - requesting DeviceOrientation permission');
statusEl.textContent = 'Requesting compass permission...';
const permission = await DeviceOrientationEvent.requestPermission();
log(`Permission response: ${permission}`);
if (permission === 'granted') {
log('Compass permission granted');
return true;
} else {
log('Compass permission denied');
statusEl.innerHTML = '<span class="error">Compass permission denied</span>';
return false;
}
} catch (error) {
log(`Permission error: ${error.toString()}`);
statusEl.innerHTML = `<span class="error">Permission error: ${error.message}</span>`;
return false;
}
}
log('Android/Desktop - no permission request needed');
return true; // No permission needed (Android, older iOS)
}
// Start compass
async function startCompass() {
try {
startBtn.disabled = true;
startBtn.textContent = 'Starting...';
log('=== Starting compass initialization ===');
// Check for HTTPS (required for sensors on most browsers)
if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
log(`WARNING: Running on ${location.protocol} - Many browsers require HTTPS for sensor access`);
statusEl.innerHTML = '<span class="error">HTTPS required for sensors</span>';
}
// Get location first
log('Step 1: Requesting location');
await getUserLocation();
log('Step 1: Complete');
// Request orientation permission if needed
log('Step 2: Requesting orientation permission');
const permissionGranted = await requestOrientationPermission();
if (!permissionGranted) {
startBtn.disabled = false;
startBtn.textContent = 'Enable Compass';
log('Permission denied - stopping');
return;
}
log('Step 2: Complete');
// Add orientation listeners
log('Step 3: Adding event listeners');
window.addEventListener('deviceorientation', handleOrientation, true);
window.addEventListener('deviceorientationabsolute', handleOrientationAbsolute, true);
log('Event listeners added');
isCompassActive = true;
statusEl.innerHTML = 'Compass active - <span style="color: #FFD700;">Wave phone in figure-8 to calibrate</span>';
startBtn.textContent = 'Compass Active';
log('=== Compass started successfully - waiting for orientation events ===');
// Show calibration reminder after 2 seconds
setTimeout(() => {
if (isCompassActive) {
log('TIP: Wave your phone in a figure-8 pattern to calibrate the magnetometer');
}
}, 2000);
// Set a timeout to check if we're receiving events
setTimeout(() => {
if (orientationEventCount === 0 && absoluteEventCount === 0) {
log('WARNING: No orientation events received after 3 seconds');
statusEl.innerHTML = '<span class="error">No sensor data - try moving your device</span>';
}
}, 3000);
} catch (error) {
log(`Error starting compass: ${error.toString()}`);
statusEl.innerHTML = `<span class="error">Error: ${error.message}</span>`;
startBtn.disabled = false;
startBtn.textContent = 'Enable Compass';
}
}
// Initialize
startBtn.addEventListener('click', startCompass);
// Check environment and log details
log('=== Ocean Crosser Initialization ===');
log(`Protocol: ${location.protocol}`);
log(`User Agent: ${navigator.userAgent}`);
log(`Geolocation supported: ${!!navigator.geolocation}`);
log(`DeviceOrientation supported: ${!!window.DeviceOrientationEvent}`);
log(`DeviceOrientation.requestPermission exists: ${!!(window.DeviceOrientationEvent && typeof DeviceOrientationEvent.requestPermission === 'function')}`);
// Check for required APIs
if (!navigator.geolocation) {
log('ERROR: Geolocation not supported');
statusEl.innerHTML = '<span class="error">Geolocation not supported</span>';
startBtn.disabled = true;
} else if (!window.DeviceOrientationEvent) {
log('ERROR: Device orientation not supported');
statusEl.innerHTML = '<span class="error">Device orientation not supported - Use a mobile device</span>';
startBtn.disabled = true;
} else {
log('All required APIs available');
statusEl.textContent = 'Ready to start - Tap button to begin';
}
// Add helpful hints
if (location.protocol === 'file:') {
log('WARNING: Running from file:// - This may not work. Use a web server.');
statusEl.innerHTML = '<span class="error">Must be served via HTTP/HTTPS</span>';
}
log('=== Initialization complete ===');
</script>
</body>
</html>