-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtrip copy.html
1223 lines (1003 loc) · 47.2 KB
/
trip copy.html
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="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="title">Zuginformationen</title>
<link rel="stylesheet" href="./assets/css/styles.css">
<link rel="stylesheet" href="./assets/css/dark-styles.css">
<link rel="stylesheet" href="./assets/css/line-colors.css">
<link rel="shortcut icon" type="image/x-icon" href="./assets/branding/favicon.ico">
<link rel="manifest" href="/manifest.json" type="application/json">
<meta name="theme-color" content="#000">
<meta name="robots" content="noindex">
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.js"></script>
</head>
<body>
<center>
<noscript> You need to enable JavaScript to run this app.</noscript>
<nav id="navbar">
<div class="tabs"><span class="active"> Zuginformationen </span></div>
<div class="iconbar bigonly"><a href="#" onclick="history.go(-1)">Schließen</a></div>
<div class="iconbar"><a href="#" onclick="history.go(-1)"><img src="./assets/icons/close.svg"
class="mediumicon"></a></div>
</nav>
<div class="coloredSpace" id="bigheaderbox">
<div class="darker">
<br>
<div class="blanktable">
<div class="trip-header">
<div class="trip-title">
<div class="whiteBadge" id="linebadge"></div><br>
</div>
</div>
<div class="trip-progress-bar">
<div class="trip-station-info">
<div class="trip-origin-info">
<span id="originStation">Origin Station</span>
</div>
<div class="trip-destination-info">
<span id="destinationStation">Destination Station</span>
</div>
</div>
<div class="trip-time-info">
<div class="trip-origin-time">
<span id="originTime">00:00</span>
</div>
<div class="trip-duration-div">
<span class="trip-duration" id="">Dauer: <span id="tripDurationTime"></span></span>
</div>
<div class="trip-destination-time">
<span id="destinationTime">00:00</span>
</div>
</div>
<br>
</div>
</div>
</div>
</div>
<div class="coloredSpace displayflex">
<div class="tinybutton">
<img src="./assets/icons/train.svg" class="slidericon"><br>
<span id="trainTitle">Zugnummer</span><br>
<small class="disabled">Zugnummer</small>
</div>
<div class="tinybutton">
<img src="./assets/icons/calendar.svg" class="slidericon"><br>
<span id="trip-date">Tag </span><br>
<small class="disabled">Datum</small>
</div>
<div class="tinybutton" id="openMapBtn">
<img src="./assets/icons/train-map.svg" class="slidericon"><br>
Karte<br>
<small class="disabled">Strecke & Live-Position</small>
</div>
<div class="tinybutton" id="myDiv">
<img src="./assets/icons/addtrain.png" id="addtrainIcon" class="slidericon"><br>
<span id="pinIt">Anheften</span><br>
<small class="disabled">Fahrt anpinnen</small>
</div>
<a href="https://www.bahn.de/buchung/jetzt-einchecken?dbkanal_007=tutorialSlider_14-1_link_KomfortCheckinimBrowseraufrufen">
<div class="tinybutton" id="comfortbutton">
<img src="./assets/icons/comfortcheckin.svg" class="slidericon"><br>
Komfort-Checkin<br>
<small class="disabled">Jetzt einchecken</small>
</div>
</a>
<a id="wagonorderbutton">
<div class="tinybutton">
<img src="./assets/icons/wagonorder.svg" class="slidericon"><br>
Wagenreihung<br>
<small>Würfelsektoren</small>
</div>
</a>
<a href="#remarks">
<div class="tinybutton yellowbutton">
<div class="trip-warning-counter" id="trip-warning-counter-button"> Keine </div>
<span id="pinIt">aktuelle Meldung</span><br>
<small>Hinweise zur Fahrt</small>
</div>
</a>
</div>
<div class="trip-container-centered">
<div class="trip-status-container"></div>
<!-- Header der Seite mit Zugdetails -->
<!-- Modal -->
<div class="secondary" id="tripStatus"><img src="./assets/blackSpinner.svg" class="loadingspinner multicolorspinner"></div>
</div>
<div id="mapModal" style="display: none;">
<div class="modal-content">
<span class="close">×</span>
<div id="map"></div>
</div>
</div>
<!-- Liste der Haltestellen -->
<div class="trip-stopovers blanktext">
<!-- Dynamisch generierte Stopover-Elemente werden hier eingefügt -->
</div>
<!-- Warnungen und Hinweise -->
<div class="gray" id="remarks">
<div class="blanktext">
<table id="remarksTable" cellpadding="10"></table>
</div>
</div>
<br>
<small>Datenanbieter:</small><br>
<img class="trip-logo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Logo_%C3%96BB.svg/2560px-Logo_%C3%96BB.svg.png" alt="ÖBB Logo" class="dataproviderLogo">
<br><br><br>
</div>
</center>
<script>
// Profilzustände über Seitenaktualisierungen hinweg speichern
let profileFailureCache = {};
let currentTripId = null;
let profileUsed;
// Funktion zur Bestimmung der Profile basierend auf Zugtyp und Betreiber
function determineProfiles(train) {
const operatorId = train.line.operator && train.line.operator.id ? train.line.operator.id.toLowerCase() : '';
const productName = train.line.productName ? train.line.productName.toLowerCase() : '';
let mainProfile = 'oebb';
let fallbackProfile = 'db';
// Prüfen, ob der Zug eine S-Bahn oder ein Regionalzug der DB ist
const isRegionalDBTrain = (
(productName.includes('s') || productName.includes('re') || productName.includes('fex') || productName.includes('rb') || productName.includes('bus')) &&
operatorId.includes('db')
);
if (isRegionalDBTrain) {
mainProfile = 'db';
fallbackProfile = 'oebb';
}
return {mainProfile, fallbackProfile};
}
// Funktion, um Parameter aus der URL zu extrahieren
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
const results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
let map;
let marker;
let intervalId;
// Funktion zur Aktualisierung der aktuellen Position auf der Karte
async function updateCurrentPosition(tripId, profile) {
let tripApiUrl = `https://data.cuzimmartin.dev/${profile === 'oebb' ? 'oebb-trip' : 'trip'}?tripId=${encodeURIComponent(tripId)}`;
let tripResponse;
try {
tripResponse = await fetch(tripApiUrl);
if (!tripResponse.ok) {
throw new Error('Request failed');
}
} catch (error) {
// Falls die Anfrage fehlschlägt, auf die alternative API umstellen
const fallbackProfile = profile === 'oebb' ? 'db' : 'oebb';
tripApiUrl = `https://data.cuzimmartin.dev/${fallbackProfile === 'oebb' ? 'oebb-trip' : 'trip'}?tripId=${encodeURIComponent(tripId)}`;
tripResponse = await fetch(tripApiUrl);
profile = fallbackProfile;
}
const tripData = await tripResponse.json();
if (tripData.trip.currentLocation && marker) {
const newPosition = [tripData.trip.currentLocation.longitude, tripData.trip.currentLocation.latitude];
marker.setLngLat(newPosition);
}
}
// Funktion zum Initialisieren der Karte
async function initMap(profileUsed) {
const tripId = decodeURIComponent(getParameterByName('tripId'));
const stationId = getParameterByName('stationID');
if (!tripId) {
alert("Keine tripId in der URL gefunden.");
return;
}
let profile = profileUsed;
let polylineApiUrl = `https://data.cuzimmartin.dev/trip/${encodeURIComponent(tripId)}/polyline?profile=${profile}`;
let polylineResponse;
try {
polylineResponse = await fetch(polylineApiUrl);
if (!polylineResponse.ok) {
throw new Error('Polyline request failed');
}
} catch (error) {
// Falls die Anfrage fehlschlägt, auf das alternative Profil umstellen
const fallbackProfile = profile === 'oebb' ? 'db' : 'oebb';
profile = fallbackProfile;
polylineApiUrl = `https://data.cuzimmartin.dev/trip/${encodeURIComponent(tripId)}/polyline?profile=${profile}`;
polylineResponse = await fetch(polylineApiUrl);
}
const polylineData = await polylineResponse.json();
let tripApiUrl = `https://data.cuzimmartin.dev/${profile === 'oebb' ? 'oebb-trip' : 'trip'}?tripId=${encodeURIComponent(tripId)}`;
let tripResponse;
try {
tripResponse = await fetch(tripApiUrl);
if (!tripResponse.ok) {
throw new Error('Trip request failed');
}
} catch (error) {
// Falls die Anfrage fehlschlägt, auf das alternative Profil umstellen
const fallbackProfile = profile === 'oebb' ? 'db' : 'oebb';
profile = fallbackProfile;
tripApiUrl = `https://data.cuzimmartin.dev/${profile === 'oebb' ? 'oebb-trip' : 'trip'}?tripId=${encodeURIComponent(tripId)}`;
tripResponse = await fetch(tripApiUrl);
}
const tripData = await tripResponse.json();
// Bestimmen der Startposition aus den Polyline-Daten
let startPosition = [16.3738, 48.2082]; // Standardposition
if (polylineData.polyline && polylineData.polyline.features && polylineData.polyline.features.length > 0) {
const firstFeature = polylineData.polyline.features[0];
if (firstFeature.geometry.type === "Point") {
startPosition = [firstFeature.geometry.coordinates[0], firstFeature.geometry.coordinates[1]];
}
}
mapboxgl.accessToken = 'pk.eyJ1IjoibWFydGlpbmhpZXIiLCJhIjoiY2x6b284ZGxtMHRlbzJpcjd5em80MDIxcSJ9.BMb9-B_QvsdFy6arQxennw';
map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/dark-v10',
center: startPosition,
zoom: 10
});
if (polylineData.polyline && polylineData.polyline.features) {
const coordinates = polylineData.polyline.features.map(feature => {
if (feature.geometry.type === "Point") {
return [feature.geometry.coordinates[0], feature.geometry.coordinates[1]];
}
}).filter(coord => coord);
const fullRoute = {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': coordinates
}
};
map.on('load', () => {
map.addSource('fullRoute', {
'type': 'geojson',
'data': fullRoute
});
map.addLayer({
'id': 'fullRoute',
'type': 'line',
'source': 'fullRoute',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#1db7dd',
'line-width': 4
}
});
if (tripData.trip.currentLocation) {
const currentLocation = [tripData.trip.currentLocation.longitude, tripData.trip.currentLocation.latitude];
marker = new mapboxgl.Marker({color: "red"})
.setLngLat(currentLocation)
.addTo(map);
} else {
console.warn("Aktuelle Position nicht verfügbar, Marker wird nicht gesetzt.");
}
const bounds = coordinates.reduce(function (bounds, coord) {
return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
map.fitBounds(bounds, {
padding: {top: 50, bottom: 50, left: 50, right: 50}
});
if (tripData.trip.currentLocation) {
intervalId = setInterval(() => updateCurrentPosition(tripId, profile), 10000);
}
});
} else {
console.error("Keine gültigen Polyline-Daten gefunden");
}
}
// Funktion zum Abrufen und Anzeigen der Daten
async function fetchAndDisplayData() {
const currentUrl = window.location.href;
const tripId = decodeURIComponent(getParameterByName('tripId', currentUrl));
const stationId = getParameterByName('stationID', currentUrl);
if (tripId !== currentTripId) {
// Fehlercache für den neuen Trip initialisieren
profileFailureCache = {
'db': false,
'oebb': false
};
currentTripId = tripId;
}
let data;
// Prüfe, welche Profile zuvor fehlgeschlagen sind (für diesen Trip)
const oebbFailedPreviously = profileFailureCache['oebb'] === true;
const dbFailedPreviously = profileFailureCache['db'] === true;
// Zuerst die Trip-Daten abrufen
if (!oebbFailedPreviously) {
try {
// Versuche, die Daten über das ÖBB-Profil abzurufen
let apiUrl = `https://data.cuzimmartin.dev/oebb-trip?tripId=${encodeURIComponent(tripId)}`;
let response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Request failed');
}
data = await response.json();
if (!data.trip) {
throw new Error('Keine Daten für diese Reise gefunden.');
}
profileUsed = 'oebb';
} catch (error) {
console.warn('Problem mit der ÖBB API, markiere als fehlgeschlagen.', error);
// Markiere ÖBB als fehlgeschlagen
profileFailureCache['oebb'] = true;
}
}
if (!data && !dbFailedPreviously) {
try {
// Fallback auf das DB-Profil
let apiUrl = `https://data.cuzimmartin.dev/trip?tripId=${encodeURIComponent(tripId)}`;
let response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Request failed');
}
data = await response.json();
if (!data.trip) {
throw new Error('Keine Daten für diese Reise gefunden.');
}
profileUsed = 'db';
} catch (secondError) {
console.warn('Problem mit der DB API, markiere als fehlgeschlagen.', secondError);
// Markiere DB als fehlgeschlagen
profileFailureCache['db'] = true;
}
}
if (!data) {
// Beide Profile haben keine Daten geliefert
console.error('Fehler beim Abrufen der Trip-Daten mit beiden Profilen.');
const statusElement = document.getElementById('tripStatus');
statusElement.textContent = `Fehler beim Abrufen der Zugdaten.`;
return;
}
// Erfolgreiches Profil zurücksetzen
profileFailureCache[profileUsed] = false;
// Bestimme die Profile basierend auf den Trip-Daten
const {mainProfile, fallbackProfile} = determineProfiles(data.trip);
// Funktion zur Aktualisierung des Zugstatus
function updateTrainStatus(trip) {
let currentTime = new Date();
let departureTime = trip.departure ? new Date(trip.departure) : null;
let arrivalTime = trip.arrival ? new Date(trip.arrival) : null;
const statusElement = document.getElementById('tripStatus');
// Funktion zur Formatierung der Zeitangabe
function formatTimeDifference(timeDiffMillis) {
const totalMinutes = Math.round(timeDiffMillis / 60000);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
let timeString = '';
if (hours > 0) {
timeString = `${hours} Stunde${hours > 1 ? 'n' : ''}`;
if (minutes > 0) {
timeString += ` und ${minutes} Minute${minutes !== 1 ? 'n' : ''}`;
}
} else {
timeString = `${minutes} Minute${minutes !== 1 ? 'n' : ''}`;
}
return timeString;
}
// Hilfsfunktion zur Generierung des Plattform-Strings
function getPlatformInfo(platform) {
return platform ? `auf Gleis ${platform}` : 'ohne festgelegtes Gleis';
}
// Prüfen, ob der gesamte Zug storniert wurde
const isTripCancelled = trip.cancelled === true;
// Prüfen, ob alle Stopovers storniert wurden
const allStopoversCancelled = trip.stopovers.every(stop => stop.cancelled === true);
// Wenn der Zug vollständig storniert wurde
if (isTripCancelled && allStopoversCancelled) {
statusElement.textContent = `Der Zug ${trip.line.name} ist vollständig ausgefallen.`;
return;
}
// Wenn der Zug teilweise storniert wurde
const cancelledStopovers = trip.stopovers.filter(stop => stop.cancelled === true);
const activeStopovers = trip.stopovers.filter(stop => !stop.cancelled);
// Funktion zum Finden des nächsten aktiven Stopovers
function findNextActiveStopover() {
for (let i = 0; i < activeStopovers.length; i++) {
const stop = activeStopovers[i];
const plannedDeparture = stop.plannedDeparture ? new Date(stop.plannedDeparture) : null;
const actualDeparture = stop.departure ? new Date(stop.departure) : null;
if ((plannedDeparture && plannedDeparture > currentTime) || (actualDeparture && actualDeparture > currentTime)) {
return stop;
}
}
return null;
}
// Wenn der Zug noch nicht abgefahren ist
if (departureTime && currentTime < departureTime && !trip.origin.cancelled) {
const timeUntilDeparture = departureTime - currentTime;
const timeString = formatTimeDifference(timeUntilDeparture);
const platformInfo = getPlatformInfo(trip.departurePlatform || trip.plannedDeparturePlatform);
statusElement.textContent = `Der Zug fährt in ${timeString} von 🔻 ${trip.origin.name} ${platformInfo} ab.`;
return;
}
// Wenn der Zug bereits abgefahren ist oder der Abfahrtsbahnhof storniert wurde
let nextStop = findNextActiveStopover();
if (nextStop) {
const arrivalTimeAtNextStop = nextStop.arrival ? new Date(nextStop.arrival) : new Date(nextStop.plannedArrival);
const timeUntilNextStop = arrivalTimeAtNextStop - currentTime;
const timeString = formatTimeDifference(timeUntilNextStop);
const platformInfoArrival = getPlatformInfo(nextStop.arrivalPlatform || nextStop.plannedArrivalPlatform);
const platformInfoDeparture = getPlatformInfo(nextStop.departurePlatform || nextStop.plannedDeparturePlatform);
if (timeUntilNextStop > 0) {
// Zug erreicht bald den nächsten Halt
statusElement.textContent = `Der Zug erreicht in ${timeString} 🔻 ${nextStop.stop.name} ${platformInfoArrival}.`;
} else {
// Zug ist bereits am nächsten Halt angekommen
const departureTimeAtNextStop = nextStop.departure ? new Date(nextStop.departure) : new Date(nextStop.plannedDeparture);
const timeUntilDeparture = departureTimeAtNextStop - currentTime;
if (timeUntilDeparture > 0) {
const departureTimeString = formatTimeDifference(timeUntilDeparture);
statusElement.textContent = `Der Zug steht aktuell in 🔻 ${nextStop.stop.name} und fährt in ${departureTimeString} ${platformInfoDeparture} ab.`;
} else {
statusElement.textContent = `Der Zug hat 🔻 ${nextStop.stop.name} gerade verlassen und ist auf dem Weg zum nächsten Halt.`;
}
}
} else {
// Wenn kein weiterer aktiver Halt mehr bevorsteht
if (arrivalTime && currentTime >= arrivalTime && !trip.destination.cancelled) {
statusElement.textContent = `Der Zug hat sein Ziel 🔻 ${trip.destination.name} erreicht.`;
} else if (trip.destination.cancelled) {
statusElement.textContent = `Der Zug endet vorzeitig und erreicht nicht sein geplantes Ziel.`;
} else {
const timeUntilArrival = arrivalTime ? arrivalTime - currentTime : null;
const timeString = timeUntilArrival ? formatTimeDifference(timeUntilArrival) : 'unbekannter Zeit';
const platformInfo = getPlatformInfo(trip.arrivalPlatform || trip.plannedArrivalPlatform);
statusElement.textContent = `Der Zug ist auf dem Weg zu seinem Endziel 🔻 ${trip.destination.name} und wird in ${timeString} ${platformInfo} ankommen.`;
}
}
// Hinweis auf ausgefallene Halte
if (cancelledStopovers.length > 0) {
const cancelledStopsNames = cancelledStopovers.map(stop => stop.stop.name).join(', ');
statusElement.textContent += `\nDie folgenden Halte entfallen: ${cancelledStopsNames}.`;
}
}
// Titel und Details setzen
document.getElementById('trainTitle').innerHTML = `${data.trip.line.fahrtNr}`;
var lineName = data.trip.line.name.split('(')[0];
document.getElementById('linebadge').textContent = `${lineName}`;
document.getElementById('title').textContent = `${data.trip.line.productName} ${data.trip.line.fahrtNr} 🡺 ${data.trip.destination.name}`;
// Dauer berechnen
const departureTime = new Date(data.trip.plannedDeparture);
const arrivalTime = new Date(data.trip.plannedArrival);
const duration = (arrivalTime - departureTime) / (1000 * 60 * 60); // Stunden
const minutes = Math.floor((duration % 1) * 60);
document.getElementById('tripDurationTime').textContent = `${Math.floor(duration)}:${minutes.toString().padStart(2, '0')} Std`;
// Datum setzen
const tripDate = departureTime.toLocaleDateString('de-DE', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
document.getElementById('trip-date').innerHTML = tripDate;
// Ursprungsstation und Zielstation setzen
document.getElementById('originStation').textContent = data.trip.origin.name;
document.getElementById('originTime').textContent = departureTime.toLocaleTimeString('de-DE', {
hour: '2-digit',
minute: '2-digit'
});
document.getElementById('destinationStation').textContent = data.trip.destination.name;
document.getElementById('destinationTime').textContent = arrivalTime.toLocaleTimeString('de-DE', {
hour: '2-digit',
minute: '2-digit'
});
// Haltestellen dynamisch hinzufügen
const stopoversContainer = document.querySelector('.trip-stopovers');
stopoversContainer.innerHTML = '';
data.trip.stopovers.forEach(stop => {
const stopElement = document.createElement('div');
if (stop.cancelled) {
stopElement.classList.add('trip-stopover');
stopElement.innerHTML = `
<div class="trip-stop-time">
<div class="trip-delay" style="font-size: 16px">Entfällt</div>
</div>
<div class="trip-stop-info">
<span class="trip-stop-name">${stop.stop.name}</span>
</div>
`;
} else {
const plannedArrivalTime = stop.plannedArrival ? new Date(stop.plannedArrival).toLocaleTimeString('de-DE', {
hour: '2-digit',
minute: '2-digit'
}) : '';
const actualArrivalTime = stop.arrival ? new Date(stop.arrival).toLocaleTimeString('de-DE', {
hour: '2-digit',
minute: '2-digit'
}) : '';
const plannedDepartureTime = stop.plannedDeparture ? new Date(stop.plannedDeparture).toLocaleTimeString('de-DE', {
hour: '2-digit',
minute: '2-digit'
}) : '';
const actualDepartureTime = stop.departure ? new Date(stop.departure).toLocaleTimeString('de-DE', {
hour: '2-digit',
minute: '2-digit'
}) : '';
const arrivalTimeDisplay = plannedArrivalTime === actualArrivalTime || !actualArrivalTime ? plannedArrivalTime : `<s class=\"disabled\">${plannedArrivalTime}</s> <span>${actualArrivalTime}</span>`;
const departureTimeDisplay = plannedDepartureTime === actualDepartureTime || !actualDepartureTime ? plannedDepartureTime : `<s class=\"disabled\">${plannedDepartureTime}</s> <span>${actualDepartureTime}</span>`;
let stopname = stop.stop.name;
if (stationId === stop.stop.id) {
stopElement.classList.add('marked-stopover');
}
stopElement.classList.add('trip-stopover');
if (stop.arrival !== null) {
stopElement.innerHTML = `
<div class="trip-stop-time">
<div>${arrivalTimeDisplay}</div>
<div>${departureTimeDisplay}</div>
</div>
<div class="trip-stop-info">
<span class="trip-stop-name">${stopname}</span>
<span class="trip-platform">${(stop.arrivalPlatform || stop.departurePlatform) ? `Gl<span class=\"bigonly\">eis</span> ${stop.arrivalPlatform || stop.departurePlatform}` : '-'}</span>
</div>
<div>
<a href="connections.html?stop=${stop.stop.location.id}&plannedArrival=${stop.plannedArrival}&todayArrival=${stop.arrival}"> <img src="./assets/icons/connectingTrain.svg"></a>
</div>
`;
} else {
stopElement.innerHTML = `
<div class="trip-stop-time">
<div>${arrivalTimeDisplay}</div>
<div>${departureTimeDisplay}</div>
</div>
<div class="trip-stop-info">
<span class="trip-stop-name">${stopname}</span>
<span class="trip-platform">${(stop.arrivalPlatform || stop.departurePlatform) ? `Gl<span class=\"bigonly\">eis</span> ${stop.arrivalPlatform || stop.departurePlatform}` : '-'}</span>
</div>
<div>
<img src="./assets/icons/placeholder.svg">
</div>
`;
}
}
stopoversContainer.appendChild(stopElement);
});
// Wagenreihungsbutton
var wagonorderbutton = document.getElementById('wagonorderbutton');
var test = '2';
// Setze das href-Attribut
const tripdepartureTime = new Date(new URLSearchParams(window.location.search).get('departureTime')).toISOString();
console.log(tripdepartureTime);
;
if ((stationId === null) || tripdepartureTime === null) {
var choosenstation = data.trip.stopovers[0].stop.id;
const tripdepartureTime = data.trip.stopovers[0].plannedDeparture;
} else {
var choosenstation = stationId;
const tripdepartureTime = new URLSearchParams(window.location.search).get('departureTime');
}
if (wagonorderbutton) {
wagonorderbutton.href = `wagonorder.html?trainnumber=${data.trip.line.fahrtNr}&station=${choosenstation}&producttype=${data.trip.line.productName}&departure=${tripdepartureTime}`;
}
// Funktion zum Entfernen von HTML-Tags aus Text (ohne Veränderung der Groß-/Kleinschreibung)
function sanitizeText(text) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = text;
return tempDiv.textContent || tempDiv.innerText || '';
}
// Funktion zum Entfernen von HTML-Tags und Normalisieren des Textes für Vergleichszwecke
function sanitizeAndNormalizeText(text) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = text;
let sanitizedText = tempDiv.textContent || tempDiv.innerText || '';
// Konvertiere zu Kleinbuchstaben und entferne führende/trailing Leerzeichen
sanitizedText = sanitizedText.toLowerCase().trim();
// Ersetze mehrere Leerzeichen durch ein einzelnes
sanitizedText = sanitizedText.replace(/\s+/g, ' ');
// Optional: Ersetze Zahlen durch Platzhalter, um ähnliche Warnungen zu erkennen
sanitizedText = sanitizedText.replace(/\d+/g, '#');
return sanitizedText;
}
// Warnungen dynamisch hinzufügen
const warningsList = document.getElementById('remarksTable');
warningsList.innerHTML = '';
const warningCounterElement = document.getElementById('trip-warning-counter-button');
// Sammle die Remarks der Station
let stationRemarks = [];
if (stationId) {
const stationStopover = data.trip.stopovers.find(stopover => stopover.stop.id === stationId);
if (stationStopover && stationStopover.remarks && stationStopover.remarks.length > 0) {
stationRemarks = stationStopover.remarks;
}
}
// Sammle die Remarks des Trips
const tripRemarks = data.trip.remarks || [];
// Kombiniere die Remarks, wobei die der Station zuerst kommen
const combinedRemarks = [...stationRemarks, ...tripRemarks];
if (combinedRemarks.length > 0) {
const uniqueMessages = new Set();
const uniqueRemarks = [];
combinedRemarks.forEach(remark => {
const normalizedText = sanitizeAndNormalizeText(remark.text);
const remarkcode = (remark.code);
if (!uniqueMessages.has(normalizedText)) {
uniqueMessages.add(normalizedText);
uniqueRemarks.push(remark);
}
});
const warningCount = uniqueRemarks.length;
// Aktualisiere den Warnungszähler oben
warningCounterElement.innerHTML = ` ${warningCount} `;
const WarningHeaderItem = document.createElement('tr');
WarningHeaderItem.innerHTML = `<td colspan="2"><h3><span class=\"pill\"> ${warningCount} </span> aktuelle Informationen:</h3></td>`;
warningsList.appendChild(WarningHeaderItem);
uniqueRemarks.forEach(remark => {
const warningItem = document.createElement('tr');
warningItem.innerHTML += (`<td class="clear"><img src="./assets/icons/remark${sanitizeText(remark.code.replace(/\./g, ''))}.svg" class="serviceicon"></td><td class="clear wide">${sanitizeText(remark.text)}</td>`);
warningsList.appendChild(warningItem);
});
} else {
// Aktualisiere den Warnungszähler oben
warningCounterElement.innerHTML = ' Keine ';
const WarningHeaderItem = document.createElement('div');
WarningHeaderItem.classList.add('trip-warning-item');
WarningHeaderItem.textContent = 'Keine Warnungen vorhanden.';
warningsList.appendChild(WarningHeaderItem);
}
// Dynamischen Status des Zuges setzen
updateTrainStatus(data.trip);
// Header Farbe
const badgeClassProductName = encodeURIComponent(data.trip.line.productName);
const badgeClassProduct = encodeURIComponent(data.trip.line.product);
const badgeClassLineOperator = encodeURIComponent(lineName.replace(/\s+/g, '')) + encodeURIComponent(data.trip.line.operator.id);
const badgeClassOperator = encodeURIComponent(data.trip.line.operator.id);
const tripID = encodeURIComponent(data.trip.id);
document.getElementById('bigheaderbox').classList.add(badgeClassProductName);
document.getElementById('bigheaderbox').classList.add(badgeClassProduct);
document.getElementById('bigheaderbox').classList.add(badgeClassLineOperator);
document.getElementById('bigheaderbox').classList.add(badgeClassOperator);
document.getElementById('linebadge').classList.add(badgeClassProductName);
document.getElementById('linebadge').classList.add(badgeClassProduct);
document.getElementById('linebadge').classList.add(badgeClassLineOperator);
document.getElementById('linebadge').classList.add(badgeClassOperator);
let $number = encodeURIComponent(data.trip.id);
// Funktion, um ein Cookie zu setzen
function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
// Funktion, um ein Cookie abzurufen
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// Funktion beim Klick auf das Div
document.getElementById('myDiv').addEventListener('click', function () {
// Setze das Cookie
setCookie('pinnedjourney', $number, 7); // Cookie für 7 Tage speichern
document.getElementById("pinIt").textContent = "Angeheftet";
document.getElementById("addtrainIcon").src = "./assets/icons/addedtrain.svg";
// Logge den Cookie-Wert zur Konsole
console.log('Cookie-Wert:', cookieValue);
});
// Rufe das Cookie ab
const cookieValue = getCookie('pinnedjourney');
const activeValue = `${encodeURIComponent(tripId)}`;
if (cookieValue === activeValue) {
console.log('It is pinned Journey');
document.getElementById("pinIt").textContent = "Angeheftet";
document.getElementById("addtrainIcon").src = "./assets/icons/addedtrain.svg";
} else {
console.log('It is not pinned Journey');
}
// Datenanbieter-Logo aktualisieren
const dataProviderLogo = document.querySelector('.trip-logo');
if (profileUsed === 'oebb') {
dataProviderLogo.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Logo_%C3%96BB.svg/2560px-Logo_%C3%96BB.svg.png";
dataProviderLogo.alt = "ÖBB Logo";
} else if (profileUsed === 'db') {
dataProviderLogo.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Deutsche_Bahn_AG-Logo.svg/512px-Deutsche_Bahn_AG-Logo.svg.png";
dataProviderLogo.alt = "DB Logo";
}
// Initialisiere die Karte mit dem verwendeten Profil
if (document.getElementById("mapModal").style.display === "block") {
initMap(profileUsed);
}
}
// Event-Handler für das Öffnen und Schließen des Modals
document.addEventListener('DOMContentLoaded', function () {
const modal = document.getElementById("mapModal");
const btn = document.getElementById("openMapBtn");
const closeBtn = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
setTimeout(() => {
if (!map) {
initMap(profileUsed);
} else {
map.resize();
}
}, 300);
};
closeBtn.onclick = function () {
modal.style.display = "none";
clearInterval(intervalId); // Stoppe die regelmäßige Positionsabfrage, wenn das Modal geschlossen wird
};
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
clearInterval(intervalId); // Stoppe die regelmäßige Positionsabfrage, wenn das Modal geschlossen wird
}
};
// Rufe fetchAndDisplayData auf
fetchAndDisplayData();
// Alle 30 Sekunden die Daten aktualisieren
setInterval(fetchAndDisplayData, 30000); // 30 Sekunden in Millisekunden
});
function fetchtraincomposition(zugnummer, datetime, stationId) {
fetch(`https://ist-wr.noncd.db.de/wagenreihung/1.0/${zugnummer}/${datetime}`)
.then(response => response.json())
.then(data => {
// Check for valid JSON
if (data.error) {
document.getElementById('notice').innerHTML = '<br><br>Wagenreihung für diesen Zug nicht verfügbar.<br><br>';
document.getElementById('coacheswrapper').classList.add('hidden');
return;
}
if (data.data.istformation.halt.evanummer !== stationId) { //Check if Wagenreihung is for the right station
console.log("StationID does not match:", stationId, data.data.istformation);
document.getElementById('notice').innerHTML = '<br><br>Wagenreihung für diesen Zug nicht verfügbar.<br><br>';
document.getElementById('coacheswrapper').classList.add('hidden');
document.getElementById('git-info').className = '';
//Create direct link for Issue report on GitHub
document.getElementById('git-error').innerHTML = `<a
href="https://github.com/hoolycrash/trainboard/issues/new?title=Bug%20Wagenreihung:&body=Train:${zugnummer}%20Datetime:${datetime}%20Station:${stationId}"
target="_blank" class="black">Open new Issue with Train data on Github</a>`;
return;
}
document.getElementById('git-info').className = '';
document.getElementById('git-error').innerHTML = `<a
href="https://github.com/hoolycrash/trainboard/issues/new?title=Bug%20Wagenreihung:&body=Train:${zugnummer}%20Datetime:${datetime}%20Station:${stationId}"
target="_blank" class="black">Open new Issue with Train data on Github</a>`;
rendertraincomposition(data.data.istformation);
});
}
function rendertraincomposition(data) {
/* //Did not work with more then one train set
const allFahrzeuggruppe = data.allFahrzeuggruppe;
const firstElementsMap = new Map();
for (let i = 0; i < allFahrzeuggruppe.length; i++) {
let fahrzeuggruppe = allFahrzeuggruppe[i];
for ( let j = 0; j < fahrzeuggruppe.allFahrzeug.length; j++) {
const fahrzeug = fahrzeuggruppe.allFahrzeug[j];
const positioningruppe = fahrzeug.positioningruppe;
if (!firstElementsMap.has(positioningruppe)) {
firstElementsMap.set(positioningruppe, fahrzeug);
} else {
console.log("Already set", positioningruppe, fahrzeug);
//const existingFahrzeuge = firstElementsMap.get(positioningruppe);
//existingFahrzeuge.push(fahrzeug);
//firstElementsMap.set(positioningruppe, existingFahrzeuge);
} } }
// Sort elements
const sortedFahrzeuge = Array.from(firstElementsMap.values()).sort((a, b) => {
return parseInt(a.positioningruppe) - parseInt(b.positioningruppe);
});
console.log(firstElementsMap);
*/
const blocksContainer = document.getElementById('blocksContainer');
let vehiclename = "";
const imgpath = 'assets/icons/carriage';
const allFahrzeuggruppe = data.allFahrzeuggruppe;
console.log("Wagenreihung:", data);
// several trains -> every train
for (let i = 0; i < allFahrzeuggruppe.length; i++) {
let fahrzeuggruppe = allFahrzeuggruppe[i];
let setLOK = false; //Boolean TrainSet has LOK
//
let vehicletype;
let getvehicleType = getVehicleType(fahrzeuggruppe.fahrzeuggruppebezeichnung);