Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1426 lines (1193 loc) · 45.8 KB
/
Copy pathscript.js
File metadata and controls
1426 lines (1193 loc) · 45.8 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
/**
* ISS Mission Control - Enhanced Tracker
* Three.js 3D Globe + Anime.js Animations + Real-time Tracking
*/
// ═══════════════════════════════════════════════════════════════
// GLOBAL STATE
// ═══════════════════════════════════════════════════════════════
let map;
let issMarker;
let currentOrbitLine;
let futureOrbitLine;
let currentOrbitPoints = [];
let followISS = false;
let totalDistance = 0;
let lastUpdateTime = Date.now();
let orbitsToday = 0;
let startTime = new Date().setHours(0, 0, 0, 0);
let userLocation = null;
let userLocationMarker = null;
let currentISSData = null;
let baseLayer;
let currentView = 'map'; // 'map' or 'globe'
// Three.js Globe Variables
let scene, camera, renderer, globe, issMarker3D, orbitLine3D;
let globeRotation = { x: 0, y: 0 };
let targetISSPosition = { lat: 0, lng: 0 };
let currentISSPosition = { lat: 0, lng: 0 };
let animationFrameId;
// Orbit colors for themes
const orbitColors = {
dark: { past: '#00d4aa', future: '#ffb347' },
light: { past: '#008866', future: '#cc8833' }
};
// ═══════════════════════════════════════════════════════════════
// INITIALIZATION
// ═══════════════════════════════════════════════════════════════
window.addEventListener('load', async () => {
// Initialize theme first
const savedTheme = localStorage.getItem('theme') || 'dark';
setTheme(savedTheme);
// Show loading with anime.js
anime({
targets: '.loader',
rotate: '1turn',
duration: 1000,
easing: 'linear',
loop: true
});
// Initialize both views
initializeMap();
initializeGlobe();
// Check stream compatibility
initStreamSection();
// Start data fetching
await updateISSPosition();
fetchCrewData();
// Hide loading screen with animation
setTimeout(() => {
anime({
targets: '#loadingScreen',
opacity: 0,
duration: 500,
easing: 'easeOutQuad',
complete: () => {
document.getElementById('loadingScreen').classList.add('hidden');
document.getElementById('app').classList.add('loaded');
// Animate telemetry bar entrance
anime({
targets: '.telemetry-item',
translateY: [20, 0],
opacity: [0, 1],
delay: anime.stagger(80),
duration: 500,
easing: 'easeOutExpo'
});
}
});
}, 1500);
// Start tracking loop
startTracking();
});
window.addEventListener('resize', () => {
if (renderer && camera) {
const container = document.getElementById('globe-container');
if (container) {
camera.aspect = container.clientWidth / container.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
}
}
});
// ═══════════════════════════════════════════════════════════════
// MAP INITIALIZATION (2D Leaflet)
// ═══════════════════════════════════════════════════════════════
function getTileLayerUrl() {
const theme = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
return theme === 'light'
? 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'
: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png';
}
function updateBaseLayer() {
if (baseLayer) {
baseLayer.setUrl(getTileLayerUrl());
}
}
function updateOrbitColors(theme) {
if (currentOrbitLine) {
currentOrbitLine.setStyle({ color: orbitColors[theme].past });
}
if (futureOrbitLine) {
futureOrbitLine.setStyle({ color: orbitColors[theme].future });
}
}
function initializeMap() {
map = L.map('map', {
center: [0, 0],
zoom: 2,
worldCopyJump: true,
zoomControl: false
});
L.control.zoom({ position: 'topright' }).addTo(map);
baseLayer = L.tileLayer(getTileLayerUrl(), {
attribution: '© OpenStreetMap © CARTO',
maxZoom: 19
}).addTo(map);
// Custom ISS icon with pulse effect - clean design using CSS
const issIcon = L.divIcon({
html: '<div class="iss-marker-container"><div class="iss-marker-pulse"></div><div class="iss-marker-dot"></div></div>',
className: 'iss-icon',
iconSize: [40, 40],
iconAnchor: [20, 20]
});
issMarker = L.marker([0, 0], { icon: issIcon }).addTo(map);
}
// ═══════════════════════════════════════════════════════════════
// GLOBE INITIALIZATION (3D Three.js)
// ═══════════════════════════════════════════════════════════════
function initializeGlobe() {
const container = document.getElementById('globe-container');
if (!container) return;
// Scene setup
scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0a0f);
// Camera
camera = new THREE.PerspectiveCamera(
45,
container.clientWidth / container.clientHeight,
0.1,
1000
);
camera.position.z = 3;
// Renderer
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
container.appendChild(renderer.domElement);
// Create Earth
createEarth();
// Create ISS marker
createISSMarker3D();
// Create orbit line
createOrbitLine3D();
// Add stars
createStars();
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 3, 5);
scene.add(directionalLight);
// Add subtle hemisphere light for atmosphere effect
const hemiLight = new THREE.HemisphereLight(0x00d4aa, 0x0a0a0f, 0.3);
scene.add(hemiLight);
// Mouse interaction
let isDragging = false;
let previousMousePosition = { x: 0, y: 0 };
container.addEventListener('mousedown', (e) => {
isDragging = true;
previousMousePosition = { x: e.clientX, y: e.clientY };
});
container.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const deltaX = e.clientX - previousMousePosition.x;
const deltaY = e.clientY - previousMousePosition.y;
globeRotation.y += deltaX * 0.005;
globeRotation.x += deltaY * 0.005;
globeRotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, globeRotation.x));
previousMousePosition = { x: e.clientX, y: e.clientY };
});
container.addEventListener('mouseup', () => { isDragging = false; });
container.addEventListener('mouseleave', () => { isDragging = false; });
// Touch support
container.addEventListener('touchstart', (e) => {
isDragging = true;
previousMousePosition = { x: e.touches[0].clientX, y: e.touches[0].clientY };
});
container.addEventListener('touchmove', (e) => {
if (!isDragging) return;
const deltaX = e.touches[0].clientX - previousMousePosition.x;
const deltaY = e.touches[0].clientY - previousMousePosition.y;
globeRotation.y += deltaX * 0.005;
globeRotation.x += deltaY * 0.005;
globeRotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, globeRotation.x));
previousMousePosition = { x: e.touches[0].clientX, y: e.touches[0].clientY };
});
container.addEventListener('touchend', () => { isDragging = false; });
// Start animation loop
animateGlobe();
}
function createEarth() {
const geometry = new THREE.SphereGeometry(1, 128, 128);
// Create enhanced procedural Earth texture
const canvas = document.createElement('canvas');
canvas.width = 2048;
canvas.height = 1024;
const ctx = canvas.getContext('2d');
// Deep ocean gradient
const oceanGradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
oceanGradient.addColorStop(0, '#0d2847');
oceanGradient.addColorStop(0.3, '#1a4a6e');
oceanGradient.addColorStop(0.5, '#1a3d5c');
oceanGradient.addColorStop(0.7, '#1a4a6e');
oceanGradient.addColorStop(1, '#0d2847');
ctx.fillStyle = oceanGradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Add ocean texture noise
for (let i = 0; i < 5000; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const brightness = Math.random() * 20;
ctx.fillStyle = `rgba(30, 80, 120, ${Math.random() * 0.3})`;
ctx.fillRect(x, y, 2, 2);
}
// Continent color with subtle variation
const drawContinent = (points, baseColor) => {
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i][0], points[i][1]);
}
ctx.closePath();
// Fill with gradient
const bounds = points.reduce((acc, p) => ({
minX: Math.min(acc.minX, p[0]),
maxX: Math.max(acc.maxX, p[0]),
minY: Math.min(acc.minY, p[1]),
maxY: Math.max(acc.maxY, p[1])
}), { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity });
const landGradient = ctx.createLinearGradient(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
landGradient.addColorStop(0, baseColor);
landGradient.addColorStop(0.5, '#3d6a4d');
landGradient.addColorStop(1, '#2a4a35');
ctx.fillStyle = landGradient;
ctx.fill();
};
// More detailed continents with polygon shapes
// North America
drawContinent([
[280, 80], [420, 100], [480, 140], [460, 200], [400, 280],
[340, 300], [280, 260], [220, 200], [200, 140], [240, 100]
], '#2d5a3d');
// Central America
drawContinent([
[340, 300], [380, 320], [400, 380], [380, 400], [340, 380], [320, 340]
], '#3d6a4d');
// South America
drawContinent([
[420, 400], [500, 420], [540, 520], [520, 680], [440, 760],
[380, 700], [360, 560], [380, 460]
], '#2d5a3d');
// Europe
drawContinent([
[980, 100], [1080, 80], [1140, 120], [1120, 180], [1040, 200],
[980, 180], [960, 140]
], '#3d6a4d');
// Africa
drawContinent([
[980, 240], [1100, 220], [1180, 300], [1160, 480], [1080, 580],
[980, 560], [940, 440], [920, 320]
], '#4a7a5a');
// Asia (large landmass)
drawContinent([
[1140, 80], [1400, 60], [1600, 100], [1700, 180], [1680, 280],
[1580, 340], [1400, 360], [1280, 320], [1200, 260], [1160, 180]
], '#2d5a3d');
// India
drawContinent([
[1340, 340], [1420, 320], [1460, 400], [1420, 500], [1360, 480], [1320, 400]
], '#3d6a4d');
// Southeast Asia
drawContinent([
[1480, 340], [1560, 320], [1600, 400], [1580, 480], [1500, 500], [1460, 420]
], '#3d6a4d');
// Australia
drawContinent([
[1600, 520], [1720, 500], [1800, 560], [1780, 660], [1680, 700],
[1580, 660], [1560, 580]
], '#5a8a6a');
// Antarctica (southern edge)
ctx.fillStyle = '#d0e0e8';
ctx.fillRect(0, 920, canvas.width, 104);
// Greenland
drawContinent([
[560, 40], [640, 30], [680, 80], [660, 140], [580, 160], [540, 100]
], '#e0f0f0');
// Add city lights (small dots on land)
const cityLights = [
// North America
[300, 180], [350, 200], [380, 220], [420, 180], [280, 220],
// Europe
[1000, 140], [1040, 160], [1080, 140], [1020, 180],
// Asia
[1300, 160], [1400, 200], [1500, 180], [1600, 240], [1380, 280],
// South America
[460, 500], [480, 560], [420, 600],
// Africa
[1020, 320], [1080, 400],
// Australia
[1680, 620], [1740, 580]
];
ctx.fillStyle = '#ffdd88';
ctx.shadowColor = '#ffaa44';
ctx.shadowBlur = 8;
cityLights.forEach(([x, y]) => {
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
});
ctx.shadowBlur = 0;
// Add subtle cloud wisps
ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
for (let i = 0; i < 30; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const w = 50 + Math.random() * 100;
const h = 10 + Math.random() * 30;
ctx.beginPath();
ctx.ellipse(x, y, w, h, Math.random() * Math.PI, 0, Math.PI * 2);
ctx.fill();
}
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
const material = new THREE.MeshPhongMaterial({
map: texture,
shininess: 8,
specular: new THREE.Color(0x222244)
});
globe = new THREE.Mesh(geometry, material);
scene.add(globe);
// Multi-layer atmosphere for more realistic glow
// Inner atmosphere
const atmosphereGeometry = new THREE.SphereGeometry(1.015, 64, 64);
const atmosphereMaterial = new THREE.MeshPhongMaterial({
color: 0x00aaff,
transparent: true,
opacity: 0.08,
side: THREE.BackSide
});
const atmosphere = new THREE.Mesh(atmosphereGeometry, atmosphereMaterial);
scene.add(atmosphere);
// Outer glow
const outerGlowGeometry = new THREE.SphereGeometry(1.04, 64, 64);
const outerGlowMaterial = new THREE.MeshBasicMaterial({
color: 0x00d4aa,
transparent: true,
opacity: 0.05,
side: THREE.BackSide
});
const outerGlow = new THREE.Mesh(outerGlowGeometry, outerGlowMaterial);
scene.add(outerGlow);
}
function createISSMarker3D() {
// Create ISS representation with main body and solar panels
issMarker3D = new THREE.Group();
// Main station body (central module)
const bodyGeometry = new THREE.BoxGeometry(0.02, 0.008, 0.008);
const bodyMaterial = new THREE.MeshPhongMaterial({
color: 0xcccccc,
emissive: 0x333333,
shininess: 60
});
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
issMarker3D.add(body);
// Solar panel material
const solarMaterial = new THREE.MeshPhongMaterial({
color: 0x1a237e,
emissive: 0x0d1447,
shininess: 30
});
// Left solar panel array
const leftPanelGeometry = new THREE.BoxGeometry(0.004, 0.04, 0.001);
const leftPanel = new THREE.Mesh(leftPanelGeometry, solarMaterial);
leftPanel.position.set(-0.014, 0, 0);
issMarker3D.add(leftPanel);
// Right solar panel array
const rightPanel = new THREE.Mesh(leftPanelGeometry, solarMaterial);
rightPanel.position.set(0.014, 0, 0);
issMarker3D.add(rightPanel);
// Secondary perpendicular panels
const perpPanelGeometry = new THREE.BoxGeometry(0.003, 0.025, 0.001);
const frontPanel = new THREE.Mesh(perpPanelGeometry, solarMaterial);
frontPanel.position.set(0, 0, 0.008);
frontPanel.rotation.x = Math.PI / 2;
issMarker3D.add(frontPanel);
const backPanel = new THREE.Mesh(perpPanelGeometry, solarMaterial);
backPanel.position.set(0, 0, -0.008);
backPanel.rotation.x = Math.PI / 2;
issMarker3D.add(backPanel);
// Add point light emanating from ISS
const issLight = new THREE.PointLight(0x00d4aa, 0.5, 0.3);
issLight.position.set(0, 0, 0);
issMarker3D.add(issLight);
// Outer glow sphere
const glowGeometry = new THREE.SphereGeometry(0.03, 16, 16);
const glowMaterial = new THREE.MeshBasicMaterial({
color: 0x00d4aa,
transparent: true,
opacity: 0.2
});
const glow = new THREE.Mesh(glowGeometry, glowMaterial);
issMarker3D.add(glow);
// Second larger glow for bloom effect
const outerGlowGeometry = new THREE.SphereGeometry(0.05, 16, 16);
const outerGlowMaterial = new THREE.MeshBasicMaterial({
color: 0x00d4aa,
transparent: true,
opacity: 0.1
});
const outerGlow = new THREE.Mesh(outerGlowGeometry, outerGlowMaterial);
issMarker3D.add(outerGlow);
scene.add(issMarker3D);
}
function createOrbitLine3D() {
const material = new THREE.LineBasicMaterial({
color: 0xffb347,
transparent: true,
opacity: 0.6
});
// Create orbit path (simplified ISS orbit)
const points = [];
for (let i = 0; i <= 360; i += 2) {
const rad = (i * Math.PI) / 180;
const inclination = 51.6 * Math.PI / 180;
const radius = 1.06; // Slightly above Earth surface
const x = radius * Math.cos(rad);
const y = radius * Math.sin(rad) * Math.sin(inclination);
const z = radius * Math.sin(rad) * Math.cos(inclination);
points.push(new THREE.Vector3(x, y, z));
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
orbitLine3D = new THREE.Line(geometry, material);
scene.add(orbitLine3D);
}
function createStars() {
// Create multiple star layers for depth
const createStarLayer = (count, minRadius, maxRadius, size, opacity) => {
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(count * 3);
const colors = new Float32Array(count * 3);
const sizes = new Float32Array(count);
for (let i = 0; i < count; i++) {
const i3 = i * 3;
const radius = minRadius + Math.random() * (maxRadius - minRadius);
const theta = Math.random() * Math.PI * 2;
const phi = Math.acos(2 * Math.random() - 1);
positions[i3] = radius * Math.sin(phi) * Math.cos(theta);
positions[i3 + 1] = radius * Math.sin(phi) * Math.sin(theta);
positions[i3 + 2] = radius * Math.cos(phi);
// Vary star colors slightly (blue-white to yellow-white)
const colorType = Math.random();
if (colorType < 0.6) {
// White
colors[i3] = 1;
colors[i3 + 1] = 1;
colors[i3 + 2] = 1;
} else if (colorType < 0.8) {
// Blue-white
colors[i3] = 0.8;
colors[i3 + 1] = 0.9;
colors[i3 + 2] = 1;
} else {
// Yellow-white
colors[i3] = 1;
colors[i3 + 1] = 0.95;
colors[i3 + 2] = 0.8;
}
// Random sizes within range
sizes[i] = size * (0.5 + Math.random());
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
const material = new THREE.PointsMaterial({
size: size,
transparent: true,
opacity: opacity,
vertexColors: true,
sizeAttenuation: true
});
return new THREE.Points(geometry, material);
};
// Near stars (brighter, larger)
const nearStars = createStarLayer(500, 30, 50, 0.8, 0.9);
scene.add(nearStars);
// Mid stars
const midStars = createStarLayer(1500, 50, 80, 0.5, 0.7);
scene.add(midStars);
// Far stars (dimmer, smaller)
const farStars = createStarLayer(3000, 80, 150, 0.3, 0.5);
scene.add(farStars);
}
function updateISSPosition3D(lat, lng) {
if (!issMarker3D) return;
// Convert lat/lng to 3D position
const phi = (90 - lat) * (Math.PI / 180);
const theta = (lng + 180) * (Math.PI / 180);
const radius = 1.06; // Slightly above Earth
const x = -radius * Math.sin(phi) * Math.cos(theta);
const y = radius * Math.cos(phi);
const z = radius * Math.sin(phi) * Math.sin(theta);
// Animate to new position
anime({
targets: issMarker3D.position,
x: x,
y: y,
z: z,
duration: 1800,
easing: 'easeOutQuad'
});
}
function animateGlobe() {
animationFrameId = requestAnimationFrame(animateGlobe);
const time = Date.now() * 0.001;
if (globe) {
// Apply user rotation
globe.rotation.x = globeRotation.x;
globe.rotation.y += 0.0005; // Slow auto-rotation
globe.rotation.y += globeRotation.y * 0.1;
globeRotation.y *= 0.95; // Damping
}
if (orbitLine3D) {
orbitLine3D.rotation.y = globe ? globe.rotation.y : 0;
}
// Rotate ISS model to face direction of travel and add subtle animation
if (issMarker3D) {
// Orient ISS along orbital path (tangent to orbit)
const orbitProgress = time * 0.05;
issMarker3D.rotation.y = orbitProgress;
issMarker3D.rotation.z = Math.sin(time * 2) * 0.02; // Subtle wobble
// Pulse the glow
const glows = issMarker3D.children.filter(c => c.material && c.material.opacity !== undefined);
glows.forEach((glow, i) => {
if (glow.material.opacity) {
glow.material.opacity = (i === 0 ? 0.2 : 0.1) + Math.sin(time * 3 + i) * 0.05;
}
});
}
renderer.render(scene, camera);
}
// ═══════════════════════════════════════════════════════════════
// ISS TRACKING
// ═══════════════════════════════════════════════════════════════
async function updateISSPosition() {
try {
const response = await fetch('https://api.wheretheiss.at/v1/satellites/25544');
const data = await response.json();
const lat = parseFloat(data.latitude);
const lng = parseFloat(data.longitude);
const altitude = parseFloat(data.altitude);
const velocity = parseFloat(data.velocity);
currentISSData = data;
// Update 2D map
updateMapDisplay(lat, lng, altitude, velocity);
// Update 3D globe
updateISSPosition3D(lat, lng);
// Update UI with smooth animations
updateUIDisplay(lat, lng, altitude, velocity, data.visibility);
} catch (error) {
console.error('Error fetching ISS position:', error);
}
}
function updateMapDisplay(lat, lng, altitude, velocity) {
// Animate marker to new position
const currentLatLng = issMarker.getLatLng();
anime({
targets: currentLatLng,
lat: lat,
lng: lng,
duration: 1800,
easing: 'easeOutQuad',
update: () => {
issMarker.setLatLng([currentLatLng.lat, currentLatLng.lng]);
}
});
if (followISS) {
map.panTo([lat, lng]);
}
// Update trajectory
currentOrbitPoints.push([lat, lng]);
if (currentOrbitPoints.length > 300) {
currentOrbitPoints.shift();
}
// Draw past trajectory
const theme = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
if (currentOrbitLine) {
currentOrbitLine.setLatLngs(currentOrbitPoints);
} else {
currentOrbitLine = L.polyline(currentOrbitPoints, {
color: orbitColors[theme].past,
weight: 3,
opacity: 0.8,
smoothFactor: 1
}).addTo(map);
}
// Draw future trajectory
const futurePoints = calculateFutureOrbit(lat, lng);
if (futureOrbitLine) {
futureOrbitLine.setLatLngs([[lat, lng], ...futurePoints]);
} else {
futureOrbitLine = L.polyline([[lat, lng], ...futurePoints], {
color: orbitColors[theme].future,
weight: 2,
opacity: 0.5,
dashArray: '5, 10',
smoothFactor: 1
}).addTo(map);
}
}
function calculateFutureOrbit(lat, lng, numPoints = 90) {
const points = [];
const orbitalPeriod = 92;
const degreesPerMinute = 360 / orbitalPeriod;
for (let i = 1; i <= numPoints; i++) {
let futureLng = (lng + (degreesPerMinute * i * 1.5)) % 360;
if (futureLng > 180) futureLng -= 360;
let futureLat = 51.6 * Math.sin((i / numPoints) * 2 * Math.PI + (lat * Math.PI / 180));
points.push([futureLat, futureLng]);
}
return points;
}
function updateUIDisplay(lat, lng, altitude, velocity, visibility) {
// Animate number changes (shared telemetry bar for both 2D and 3D views)
animateValue('latitude', lat.toFixed(4) + '°');
animateValue('longitude', lng.toFixed(4) + '°');
animateValue('altitude', altitude.toFixed(1));
animateValue('velocity', velocity.toFixed(0));
// Update statistics
updateStatistics(velocity);
// Check if ISS is in daylight - update icon and text
const isDaylight = visibility === 'daylight';
const daylightText = document.getElementById('daylightText');
const daylightStatus = document.getElementById('daylightStatus');
if (daylightText) {
daylightText.textContent = isDaylight ? 'Daylight' : 'Night';
}
// Update the status icon
if (daylightStatus) {
const statusIcon = daylightStatus.querySelector('.status-icon');
if (statusIcon) {
statusIcon.setAttribute('data-lucide', isDaylight ? 'sun' : 'moon');
lucide.createIcons({ nodes: [statusIcon] });
}
}
// Update pass predictions if user location is set
if (userLocation) {
updatePassPredictions();
}
}
function animateValue(elementId, newValue) {
const el = document.getElementById(elementId);
if (!el) return;
el.classList.add('updating');
el.textContent = newValue;
setTimeout(() => {
el.classList.remove('updating');
}, 300);
}
function updateStatistics(velocity) {
const now = Date.now();
const timeDiff = (now - lastUpdateTime) / 1000 / 3600;
totalDistance += velocity * timeDiff;
lastUpdateTime = now;
const hoursElapsed = (now - startTime) / 1000 / 3600;
orbitsToday = Math.floor(hoursElapsed / 1.53);
document.getElementById('orbitsToday').textContent = orbitsToday;
document.getElementById('distanceTraveled').textContent =
totalDistance > 1000
? (totalDistance / 1000).toFixed(1) + 'k km'
: totalDistance.toFixed(0) + ' km';
}
function startTracking() {
updateISSPosition();
setInterval(updateISSPosition, 2000);
}
// ═══════════════════════════════════════════════════════════════
// CREW DATA
// ═══════════════════════════════════════════════════════════════
async function fetchCrewData() {
try {
const response = await fetch('http://api.open-notify.org/astros.json');
const data = await response.json();
const issCrew = data.people.filter(p => p.craft === 'ISS');
displayCrew(issCrew);
} catch (error) {
console.error('Error fetching crew data:', error);
// Show placeholder on error using safe DOM methods
const crewList = document.getElementById('crewList');
crewList.textContent = '';
const member = createCrewMemberElement('Crew data unavailable', 'Check back later');
crewList.appendChild(member);
}
}
function createCrewMemberElement(name, agency) {
const member = document.createElement('div');
member.className = 'crew-member';
const avatar = document.createElement('div');
avatar.className = 'crew-avatar';
// Use Lucide icon instead of emoji
const icon = document.createElement('i');
icon.setAttribute('data-lucide', 'user');
icon.className = 'icon';
avatar.appendChild(icon);
const info = document.createElement('div');
info.className = 'crew-info';
const nameEl = document.createElement('div');
nameEl.className = 'crew-name';
nameEl.textContent = name;
const agencyEl = document.createElement('div');
agencyEl.className = 'crew-agency';
agencyEl.textContent = agency;
info.appendChild(nameEl);
info.appendChild(agencyEl);
member.appendChild(avatar);
member.appendChild(info);
return member;
}
function displayCrew(crew) {
const crewList = document.getElementById('crewList');
crewList.textContent = ''; // Clear existing content safely
if (!crew || crew.length === 0) {
const p = document.createElement('p');
p.style.color = 'var(--text-secondary)';
p.textContent = 'No crew data available';
crewList.appendChild(p);
return;
}
crew.forEach(member => {
const el = createCrewMemberElement(member.name, 'ISS Crew Member');
crewList.appendChild(el);
});
// Initialize Lucide icons for dynamically created crew avatars
lucide.createIcons();
// Animate crew list
anime({
targets: '.crew-member',
translateX: [-20, 0],
opacity: [0, 1],
delay: anime.stagger(50),
duration: 400,
easing: 'easeOutQuad'
});
}
// ═══════════════════════════════════════════════════════════════
// VIEW TOGGLE
// ═══════════════════════════════════════════════════════════════
function toggleView() {
const mapSection = document.getElementById('mapSection');
const globeSection = document.getElementById('globeSection');
const viewBtn = document.getElementById('viewToggleBtn');
const viewIcon = document.getElementById('viewIcon');
const viewLabel = viewBtn?.querySelector('.nav-label');
if (currentView === 'map') {
// Switch to 3D globe
currentView = 'globe';
anime({
targets: mapSection,
opacity: 0,
duration: 300,
easing: 'easeOutQuad',
complete: () => {
mapSection.classList.add('hidden');
globeSection.classList.add('active');
anime({
targets: globeSection,
opacity: [0, 1],
duration: 300,
easing: 'easeInQuad'
});
}
});
// Update button with Lucide icon
if (viewIcon) {
viewIcon.setAttribute('data-lucide', 'map');
lucide.createIcons({ nodes: [viewIcon] });
}
if (viewLabel) viewLabel.textContent = '2D Map';
viewBtn?.classList.add('active');
} else {
// Switch to 2D map
currentView = 'map';
anime({
targets: globeSection,
opacity: 0,
duration: 300,
easing: 'easeOutQuad',
complete: () => {
globeSection.classList.remove('active');
mapSection.classList.remove('hidden');
anime({
targets: mapSection,
opacity: [0, 1],
duration: 300,
easing: 'easeInQuad'
});
}
});
// Update button with Lucide icon
if (viewIcon) {
viewIcon.setAttribute('data-lucide', 'globe-2');
lucide.createIcons({ nodes: [viewIcon] });
}
if (viewLabel) viewLabel.textContent = '3D Globe';
viewBtn?.classList.remove('active');
}
}
// ═══════════════════════════════════════════════════════════════
// LOCATION & PASS PREDICTIONS
// ═══════════════════════════════════════════════════════════════
function useMyLocation() {