Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
1654 lines (1605 loc) · 96.9 KB
/
Copy pathindex.html
File metadata and controls
1654 lines (1605 loc) · 96.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Train netmap</title>
<link id="favicon" rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ccircle cx='16' cy='16' r='15' fill='%235f7180' opacity='.45'/%3E%3Ccircle cx='16' cy='16' r='9' fill='%235f7180'/%3E%3Ccircle cx='16' cy='16' r='4' fill='%23eef3f6'/%3E%3C/svg%3E">
<link rel="stylesheet" href="vendor/leaflet/leaflet.css">
<script src="vendor/leaflet/leaflet.js"></script>
<script src="config.js"></script>
<script src="version.js"></script>
<style>
:root {
--ink: #0d1b26; --ink-2: #142634; --line: #2a3d4d;
--fg: #eef3f6; --muted: #93a6b5;
--good: #4cc38a; --fair: #e3b341; --poor: #f0883e; --off: #ef5b5b; --none: #5f7180;
--sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--ink); color: var(--fg); font: 14px/1.45 var(--sans); font-variant-numeric: tabular-nums; }
::selection { background: rgba(76, 195, 138, .35); }
:focus-visible { outline: 2px solid var(--fg); outline-offset: 3px; border-radius: 4px; }
#map { position: absolute; inset: 0; background: var(--ink); }
.leaflet-tile-pane { filter: sepia(1) hue-rotate(165deg) saturate(1.8) brightness(.85); }
.fade-top { position: absolute; left: 0; right: 0; z-index: 500; pointer-events: none; top: 0; height: 240px; background: linear-gradient(var(--ink) 15%, rgba(13, 27, 38, 0)); }
#status { position: absolute; top: 28px; left: 32px; right: 320px; z-index: 600; }
#status h1 { margin: 0; font-size: 44px; line-height: 1.05; font-weight: 650; letter-spacing: -.02em; display: flex; flex-wrap: wrap; gap: 0 16px; align-items: baseline; }
#state { color: var(--muted); transition: color .4s; }
[data-state="online"] #state { color: var(--good); }
[data-state="offline"] #state { color: var(--off); }
#for { font-weight: 400; color: var(--fg); }
#for .short { display: none; }
@media (max-width: 1100px) { #for .long { display: none; } #for .short { display: inline; } }
.readings { margin: 14px 0 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 6px 28px; color: var(--muted); }
#forecast { margin: 12px 0 0; font-size: 15px; color: var(--muted); }
#forecast:empty { display: none; }
#notice { margin: 12px 0 0; color: var(--fair); max-width: 60ch; }
#notice a { color: var(--fg); }
#notice code { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px; }
#notice:empty { display: none; }
#notice.ok, #setup-msg.ok { color: var(--good); }
#detail { margin: 4px 0 0; font-size: 15px; color: var(--muted); display: grid; gap: 4px; }
#detail:has(#arrive:empty):has(#trip-sum:empty) { display: none; }
#arrive b { color: var(--fg); font-weight: 600; font-variant-numeric: tabular-nums; }
#near-mast:empty { display: none; }
#near-mast b { color: var(--fg); font-weight: 600; }
#trip-sum { opacity: .7; font-size: 13px; margin-top: 10px; }
#trip-best, #trip-worst { opacity: .7; font-size: 13px; }
#trip-best:empty, #trip-worst:empty { display: none; }
.soft-warn { color: #ecc97a; }
.soft-off { color: #9fb0bf; }
.soft-bad { color: #f0a097; }
.soft-good { color: #8fd9b3; }
[data-zoom="far"] .stop-label:not(.end):not(.next) { display: none; }
.leaflet-control-scale-line { background: none; border-color: var(--muted); color: var(--muted); font: 11px var(--sans); text-shadow: 0 0 3px var(--ink); }
#forecast b { color: var(--fg); font-weight: 600; }
.readings b { font-size: 20px; font-weight: 600; color: var(--fg); margin-right: 6px; }
.controls { position: absolute; top: 24px; right: 24px; z-index: 950; }
#menu-btn { width: 40px; height: 40px; padding: 0; display: grid; place-items: center; color: var(--muted); background: rgba(238, 243, 246, .06); }
#menu-btn:hover, #menu-btn[aria-expanded="true"] { color: var(--fg); background: rgba(238, 243, 246, .12); }
#menu { position: absolute; top: 48px; right: 0; min-width: 200px; display: grid; padding: 6px; border-radius: 14px; background: rgba(20, 38, 52, .92); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); box-shadow: 0 4px 16px rgba(0, 0, 0, .25); }
#menu[hidden] { display: none; }
#menu button { text-align: left; border-radius: 9px; padding: 9px 12px; }
/* Map switches sit quietly on the legend line: a dot that fills when on. The top bar keeps only buttons that open or do something. */
.trip-foot { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 8px 24px; margin-top: 6px; }
.trip-foot .legend { margin: 0; }
.switches { display: flex; flex-wrap: wrap; gap: 6px; }
.switch { display: flex; align-items: center; gap: 7px; padding: 5px 12px 5px 10px; font-size: 12px; color: var(--muted); background: rgba(13, 27, 38, .75); box-shadow: inset 0 0 0 1px var(--line); transition: background .2s, color .2s, box-shadow .2s; }
.switch:hover { background: rgba(20, 38, 52, .9); color: var(--fg); }
.switch::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--line); transition: background .2s; }
.switch[aria-pressed="true"] { color: var(--fg); background: rgba(76, 195, 138, .14); box-shadow: inset 0 0 0 1px rgba(76, 195, 138, .35); }
.switch[aria-pressed="true"]::before { background: var(--good); }
button {
font: inherit; color: var(--fg); background: none; border: 0; border-radius: 999px;
padding: 6px 14px; cursor: pointer; white-space: nowrap; transition: background .15s, color .15s;
}
button:hover { background: rgba(238, 243, 246, .08); }
#trip { position: absolute; left: 32px; right: 32px; bottom: 40px; z-index: 600; }
.trip-head { text-shadow: 0 0 3px var(--ink), 0 0 8px var(--ink); display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 24px; align-items: baseline; }
#trip-name { font-size: 17px; font-weight: 600; }
#trip-name span { color: var(--muted); font-weight: 400; margin-left: 8px; }
/* Two right-aligned lines with fixed-width digits, so a changing delay or minute count never shifts the line beside it. */
#trip-eta { color: var(--muted); display: grid; justify-items: end; min-width: 30ch; text-align: right; font-variant-numeric: tabular-nums; }
#trip-eta .late { font-size: 12px; }
#trip-eta b { color: var(--fg); font-weight: 600; }
#ribbon { display: block; width: 100%; height: 92px; overflow: visible; }
#ribbon text { fill: var(--muted); font: 12px var(--sans); paint-order: stroke; stroke: var(--ink); stroke-width: 4px; stroke-linejoin: round; }
#ribbon text.end { fill: var(--fg); font-weight: 600; }
#ribbon text.next { fill: var(--fg); }
.legend { text-shadow: 0 0 3px var(--ink), 0 0 8px var(--ink); margin: 6px 0 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 4px 20px; color: var(--muted); font-size: 12px; }
.legend li { display: flex; align-items: center; gap: 8px; }
.legend .op { display: none; }
body[data-masts="on"] .legend .op { display: flex; }
.legend i { width: 18px; height: 6px; border-radius: 3px; }
#setup, .overlay { position: absolute; inset: 0; z-index: 900; background: rgba(13, 27, 38, .9); display: grid; place-items: center; padding: 24px; }
#setup[hidden], .overlay[hidden] { display: none; }
#setup form, .overlay form { width: min(560px, 100%); }
#setup h2, .overlay h2 { margin: 0 0 28px; font-size: 36px; line-height: 1.1; font-weight: 650; letter-spacing: -.02em; }
#alerts-perm { margin: -12px 0 16px; color: var(--muted); }
.muted-text { color: var(--muted); max-width: 60ch; }
#arrived-sum { margin: -12px 0 16px; font-size: 17px; }
#alerts-enable[hidden] { display: none; }
#alerts-perm:empty { display: none; }
#alerts-perm a { color: var(--fg); }
#alerts-last { margin: 20px 0 0; color: var(--muted); }
#alerts-last:empty { display: none; }
#toasts { position: absolute; top: 72px; right: 32px; z-index: 1000; display: grid; gap: 8px; justify-items: end; max-width: min(420px, calc(100% - 32px)); }
.toast { width: fit-content; background: rgba(20, 38, 52, .6); backdrop-filter: blur(24px) saturate(1.4); -webkit-backdrop-filter: blur(24px) saturate(1.4); border-radius: 14px; padding: 12px 16px; cursor: pointer; box-shadow: 0 2px 10px rgba(0, 0, 0, .18); animation: toast-in .45s cubic-bezier(.16, 1, .3, 1); transition: transform .3s cubic-bezier(.4, 0, 1, 1), opacity .3s; }
.toast.leaving { transform: translateX(120%); opacity: 0; }
.toast b { display: flex; align-items: center; gap: 8px; font-size: 15px; margin-bottom: 2px; }
.toast b::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--good); flex: none; }
.toast.bad b::before { background: var(--off); }
.toast.warn b::before { background: var(--fair); }
.toast span { color: var(--muted); font-size: 13px; }
@keyframes toast-in { from { transform: translateX(120%); opacity: 0; } }
@media (max-width: 720px) { #toasts { top: 56px; right: 16px; } }
.checks { display: grid; gap: 10px; }
.checks label { display: flex; align-items: center; gap: 12px; cursor: pointer; }
.checks input { width: 18px; height: 18px; margin: 0; accent-color: var(--good); }
.fields { display: grid; grid-template-columns: 1fr 1fr; gap: 20px 24px; }
.fields label { display: grid; gap: 6px; color: var(--muted); }
.fields .wide { grid-column: 1 / -1; }
.leg-row { margin-top: 24px; }
.leg-change { grid-column: 1 / -1; margin: 0; color: var(--fg); font-weight: 600; display: flex; justify-content: space-between; align-items: baseline; }
.leg-change button { font-weight: 400; color: var(--muted); }
#add-leg { margin-top: 20px; padding-left: 0; color: var(--good); }
input {
font: inherit; font-size: 20px; color: var(--fg); background: transparent; width: 100%;
border: 0; border-bottom: 2px solid var(--line); padding: 6px 0; border-radius: 0; transition: border-color .15s;
}
input:focus { outline: none; border-color: var(--good); }
.submit { margin-top: 32px; display: flex; gap: 12px; align-items: center; }
.primary { background: var(--good); color: var(--ink); font-weight: 600; padding: 10px 22px; }
.primary:hover { background: #63d29c; }
.primary:disabled { background: var(--line); color: var(--muted); cursor: progress; }
#setup-msg { margin: 20px 0 0; min-height: 1.45em; color: var(--off); }
.leaflet-container { font: 12px/1.4 var(--sans); background: var(--ink); }
.leaflet-bar { border: 0 !important; box-shadow: none !important; }
.leaflet-bar a { background: var(--ink-2); color: var(--fg); border-bottom-color: var(--line); }
.leaflet-bar a:hover { background: var(--line); color: var(--fg); }
.leaflet-control-attribution { background: none !important; color: var(--muted); }
.leaflet-control-attribution a { color: var(--fg); }
.leaflet-tooltip { background: var(--ink-2); color: var(--fg); border: 0; border-radius: 6px; box-shadow: none; padding: 6px 10px; }
.leaflet-tooltip::before { display: none; }
.leaflet-tooltip.stop-label { background: none; padding: 0 0 0 4px; color: var(--muted); font-size: 12px; text-shadow: 0 0 3px var(--ink), 0 0 8px var(--ink); }
.leaflet-tooltip.stop-label.end, .leaflet-tooltip.stop-label.next { color: var(--fg); font-weight: 600; }
.leaflet-tooltip.stop-label.passed { opacity: .6; }
.leaflet-tooltip.stop-label.covered { display: none; }
@media (max-width: 720px) {
#status { left: 16px; right: 16px; top: 96px; }
#status h1 { font-size: 34px; }
.readings { display: grid; grid-template-columns: 1fr 1fr; }
.controls { top: 12px; left: 8px; right: 8px; max-width: none; }
#trip { left: 16px; right: 16px; bottom: 20px; }
.legend { grid-template-columns: repeat(2, max-content); }
.fields { grid-template-columns: 1fr; }
}
.you { --ring: var(--muted); }
[data-state="online"] .you { --ring: var(--good); }
[data-state="offline"] .you { --ring: var(--off); }
.you i, .you b { position: absolute; inset: 0; border-radius: 50%; }
.you b { background: var(--fg); border: 3px solid var(--ink); box-shadow: 0 0 0 2px var(--ring); }
.you i { background: var(--ring); animation: pulse 2s cubic-bezier(.16, 1, .3, 1) infinite; }
.mast { --c: #9fb0bf; }
.mast.op5, .mast.op21 { --c: #4f8cff; }
.mast.op91, .mast.op36 { --c: #b073ff; }
.mast.op12, .mast.op3 { --c: #ff6fb1; }
.mast.guessed { opacity: .3; }
.mast.guessed i { animation: none; }
.mast i, .mast b { position: absolute; inset: 0; border-radius: 50%; }
.mast { opacity: .6; }
.mast b { background: var(--c); transform: scale(.4); box-shadow: 0 0 3px var(--c); }
.mast i { background: var(--c); opacity: 0; animation: beacon 3s ease-out infinite; animation-delay: var(--d); }
.mast.mobile { --c: var(--good); }
@keyframes beacon { 0% { transform: scale(.4); opacity: .35; } 100% { transform: scale(2.6); opacity: 0; } }
.ribbon-pulse { fill: var(--good); transform-box: fill-box; transform-origin: center; animation: pulse 2s cubic-bezier(.16, 1, .3, 1) infinite; }
[data-state="offline"] .ribbon-pulse { fill: var(--off); }
[data-state="connecting"] .ribbon-pulse { fill: var(--muted); }
@keyframes pulse { from { transform: scale(1); opacity: .7; } to { transform: scale(3.2); opacity: 0; } }
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; }
.you i, .ribbon-pulse { animation: none; opacity: .35; transform: scale(1.8); }
.mast i { animation: none; opacity: .25; transform: scale(1.6); }
}
</style>
</head>
<body>
<div id="map"></div>
<div class="fade-top"></div>
<header id="status" data-state="connecting">
<h1><span id="state">Connecting</span><span id="for"></span></h1>
<ul class="readings">
<li><b id="rtt">-</b>latency</li>
<li><b id="down">-</b>bandwidth</li>
<li><b id="speed">-</b>train speed</li>
<li><b id="outages">0</b>outages</li>
</ul>
<p id="forecast"></p>
<p id="detail"><span id="arrive"></span><span id="near-mast"></span><span id="trip-sum"></span><span id="trip-best"></span><span id="trip-worst"></span></p>
<p id="notice"></p>
</header>
<nav class="controls">
<button id="menu-btn" aria-label="Settings" aria-expanded="false"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg></button>
<div id="menu" hidden>
<button id="trip-btn">Change trip</button>
<button id="notify">Alerts</button>
<button id="export">Export data</button>
<button id="import">Import data</button>
</div>
<input type="file" id="import-file" accept=".json,application/json" hidden>
</nav>
<section id="trip" hidden>
<div class="trip-head">
<div id="trip-name"></div>
<div id="trip-eta"></div>
</div>
<svg id="ribbon" role="img" aria-label="Connection quality along the trip"></svg>
<div class="trip-foot">
<ul class="legend">
<li><i style="background:var(--good)"></i>under 150 ms</li>
<li><i style="background:var(--fair)"></i>150 to 400 ms</li>
<li><i style="background:var(--poor)"></i>over 400 ms</li>
<li><i style="background:var(--off)"></i>offline</li>
<li><i style="background:var(--none)"></i>not measured</li>
<li class="op"><i style="background:#4f8cff;border-radius:50%;width:8px;height:8px"></i>Elisa</li>
<li class="op"><i style="background:#b073ff;border-radius:50%;width:8px;height:8px"></i>Telia</li>
<li class="op"><i style="background:#ff6fb1;border-radius:50%;width:8px;height:8px"></i>DNA</li>
</ul>
<div class="switches" aria-label="Map switches">
<button id="follow" class="switch" aria-pressed="true">Follow train</button>
<button id="whole" class="switch" aria-pressed="false">Whole route</button>
<button id="masts-btn" class="switch" aria-pressed="false">Masts</button>
</div>
</div>
</section>
<div id="setup" hidden>
<form>
<h2>Where are you travelling?</h2>
<div class="fields">
<label>From<input id="from" list="stations" placeholder="Like Pieksämäki" autocomplete="off" required></label>
<label>To<input id="to" list="stations" placeholder="Like Oulu" autocomplete="off" required></label>
<label class="wide">Train<input id="train-no" list="trains" placeholder="Filled in from the stations, or type one like IC 63" autocomplete="off"></label>
</div>
<div id="legs"></div>
<p><button type="button" id="add-leg">Add a connecting train</button></p>
<div class="submit">
<button class="primary" type="submit">Track trip</button>
<button type="button" id="setup-import">Import data</button>
<button type="button" id="setup-cancel">Cancel</button>
</div>
<p id="setup-msg" role="alert"></p>
</form>
</div>
<div id="toasts" aria-live="polite"></div>
<div id="arrived" class="overlay" hidden>
<form>
<h2 id="arrived-title">Arrived</h2>
<p id="arrived-sum"></p>
<p class="muted-text">This trip's samples are saved in this browser and already sharpen the forecast on this line: the next time you ride it, in either direction, the dead zones come from what was measured here rather than from Speedtest averages, and every further trip adds weight. Keep the page at this address and the data stays; a cleared browser or another computer loses it, so export a copy. The file holds every trip logged so far, and Import on the first screen puts it all back.</p>
<div class="submit">
<button type="button" class="primary" id="arrived-export">Export trip data</button>
<button type="button" id="arrived-close">Done</button>
</div>
</form>
</div>
<div id="alerts" class="overlay" hidden>
<form>
<h2>Alerts</h2>
<p id="alerts-perm"></p>
<p><button type="button" class="primary" id="alerts-enable">Enable system notifications</button></p>
<div class="checks">
<label><input type="checkbox" data-kind="deadzone" checked> Dead zone ahead</label>
<label><input type="checkbox" data-kind="offline" checked> Connection dropped</label>
<label><input type="checkbox" data-kind="back" checked> Connection back</label>
<label><input type="checkbox" data-kind="slow" checked> Connection slow</label>
<label><input type="checkbox" data-kind="faster" checked> Connection faster</label>
<label><input type="checkbox" data-kind="bandwidth" checked> Bandwidth collapses or recovers</label>
<label><input type="checkbox" data-kind="stop" checked> Next stop</label>
<label><input type="checkbox" data-kind="arrive" checked> Arrival</label>
<label><input type="checkbox" data-kind="delay" checked> Delay changes</label>
<label><input type="checkbox" data-kind="sound" checked> Sound</label>
</div>
<div class="submit">
<button type="button" class="primary" id="alerts-test">Send a test alert</button>
<button type="button" id="alerts-close">Done</button>
</div>
<p id="alerts-last"></p>
</form>
</div>
<datalist id="stations"></datalist>
<datalist id="trains"></datalist>
<script>
const API = 'https://rata.digitraffic.fi/api/v1';
const CARTO_KEY = window.NETMAP_CONFIG?.cartoKey || '';
const POLL = 5000, LOCATION_EVERY = 15000;
const PROBE = 'https://cp.cloudflare.com/generate_204';
let locAt = 0, locPausedUntil = 0;
const COLORS = { good: '#4cc38a', fair: '#e3b341', poor: '#f0883e', off: '#ef5b5b', none: '#5f7180' };
const $ = id => document.getElementById(id);
const store = {
get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } },
set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); return true; } catch { $('notice').textContent = 'Browser storage is full, so new samples are not being saved. Export your data.'; return false; } },
};
// Digitraffic grants a higher request rate when the app names itself.
const DT_HEADERS = { 'Digitraffic-User': 'train-netmap' };
const get = (path, ms = 8000) => fetch(API + path, { signal: AbortSignal.timeout(ms), cache: 'no-store', headers: DT_HEADERS })
.then(r => r.ok ? r.json() : Promise.reject(new Error(r.status)));
const when = r => Date.parse(r.actualTime || r.liveEstimateTime || r.scheduledTime);
// The name on the ticket: VR sells its HDM railbuses as Kiskobussi.
const TRAIN_TYPES = { HDM: 'Kiskobussi' };
const trainName = t => t.commuterLineID ? `${t.commuterLineID} train` : `${TRAIN_TYPES[t.trainType] || t.trainType} ${t.trainNumber}`;
const hhmm = t => { const d = new Date(t); return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; };
const hours = h => `${h} ${h === 1 ? 'hour' : 'hours'}`;
// The same span in full words, for the places with room for it: "1 hour, 12 minutes, 40 seconds".
const durLong = ms => {
const s = Math.max(0, Math.floor(ms / 1000)), h = Math.floor(s / 3600), m = Math.floor(s / 60) % 60, sec = s % 60;
const unit = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
return [h ? unit(h, 'hour') : '', m ? unit(m, 'minute') : '', !h && sec ? unit(sec, 'second') : ''].filter(Boolean).join(', ') || '0 seconds';
};
const dur = ms => {
const s = Math.max(0, Math.floor(ms / 1000)), m = Math.floor(s / 60);
// Hours are spelled out, minutes and seconds are glued shorthand, units separated by commas: "1 hour, 10min, 5s".
const h = Math.floor(m / 60);
return [h ? hours(h) : '', m % 60 ? `${m % 60}min` : '', !h && s % 60 ? `${s % 60}s` : ''].filter(Boolean).join(', ') || '0s';
};
// Chrome caps navigator.connection.downlink at 10 Mbps.
const mbps = d => d >= 100 ? `${Math.round(d)} Mbps` : d >= 10 ? `${Math.round(d)} Mbps` : `${d.toFixed(1)} Mbps`;
// A 2 MB download every couple of minutes measures real throughput; Chrome's own estimate stops at 10 Mbps.
const SPEED_URL = 'https://speed.cloudflare.com/__down?bytes=2000000', SPEED_EVERY = 120000;
let speedAt = 0, measured = null, speedRunning = false;
async function measureSpeed() {
speedAt = Date.now();
speedRunning = true;
const t0 = performance.now();
try {
const r = await fetch(SPEED_URL, { cache: 'no-store', signal: AbortSignal.timeout(20000) });
const bytes = (await r.arrayBuffer()).byteLength;
measured = bytes * 8 / 1e6 / ((performance.now() - t0) / 1000);
} catch { measured = null; }
speedRunning = false;
return measured;
}
// Bands for a warm connection to a nearby edge: calls and SSH are fine under 150 ms, browsing drags past 400 ms.
const quality = p => !p.ok ? 'off' : p.rtt < 150 ? 'good' : p.rtt < 400 ? 'fair' : 'poor';
const median = a => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };
// ---------- map ----------
const map = L.map('map', { zoomControl: false }).setView([63.2, 27.2], 8);
const tiles = L.tileLayer(`https://basemaps.cartocdn.com/rastertiles/dark_all/{z}/{x}/{y}{r}.png?key=${CARTO_KEY}`, {
maxZoom: 19,
attribution: 'Map © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> © <a href="https://carto.com/attributions">CARTO</a>, trains © <a href="https://www.digitraffic.fi">Fintraffic</a> CC BY 4.0, coverage © <a href="https://www.ookla.com/ookla-for-good/open-data">Ookla</a> CC BY-NC-SA 4.0, cells © <a href="https://opencellid.org">OpenCelliD</a> CC BY-SA 4.0'
});
if (CARTO_KEY) tiles.addTo(map);
const baseLayer = L.layerGroup().addTo(map);
const hexLayer = L.layerGroup().addTo(map);
const trailLayer = L.layerGroup().addTo(map);
function addTrail(prev, p) {
if (!prev?.lat || !p.lat || (prev.lat === p.lat && prev.lon === p.lon)) return;
L.polyline([[prev.lat, prev.lon], [p.lat, p.lon]], { color: COLORS[quality(p)], weight: 3, opacity: .85, interactive: false, lineCap: 'round' }).addTo(trailLayer);
}
L.control.scale({ imperial: false, position: 'bottomright' }).addTo(map);
map.on('zoomend', () => { document.body.dataset.zoom = map.getZoom() < 8 ? 'far' : ''; });
// Stop names that would sit under the route line at the bottom are hidden rather than overprinted.
function hideCoveredLabels() {
const top = $('trip').hidden ? Infinity : $('trip').getBoundingClientRect().top - 12;
routeLayer.eachLayer(l => {
const el = l.getTooltip?.()?.getElement();
if (el) el.classList.toggle('covered', map.latLngToContainerPoint(l.getLatLng()).y > top);
});
}
map.on('move', hideCoveredLabels);
const marker = L.marker([0, 0], {
icon: L.divIcon({ className: 'you', html: '<i></i><b></b>', iconSize: [20, 20] }),
interactive: false, keyboard: false, zIndexOffset: 1000
});
const routeLayer = L.layerGroup().addTo(map);
let follow = true;
function setFollow(on) {
follow = on;
$('follow').setAttribute('aria-pressed', on);
if (on && lastPos) map.setView(lastPos, Math.max(map.getZoom(), 10));
}
map.on('dragstart', () => setFollow(false));
// Hexagons are sized in Web Mercator metres; 2600 is about 1.2 km across at 62-65 degrees north.
const HEX = 2600, crs = L.CRS.EPSG3857;
const hexes = new Map();
function hexOf(lat, lon) {
const p = crs.project(L.latLng(lat, lon));
let q = (Math.sqrt(3) / 3 * p.x - p.y / 3) / HEX, r = (2 / 3 * p.y) / HEX, s = -q - r;
let rq = Math.round(q), rr = Math.round(r), rs = Math.round(s);
const dq = Math.abs(rq - q), dr = Math.abs(rr - r), ds = Math.abs(rs - s);
if (dq > dr && dq > ds) rq = -rr - rs; else if (dr > ds) rr = -rq - rs;
return [rq, rr];
}
function hexPolygon(q, r) {
const cx = HEX * Math.sqrt(3) * (q + r / 2), cy = HEX * 1.5 * r;
return [0, 1, 2, 3, 4, 5].map(i => {
const a = Math.PI / 180 * (60 * i - 30);
return crs.unproject(L.point(cx + HEX * Math.cos(a), cy + HEX * Math.sin(a)));
});
}
function addToHex(p) {
if (!p.lat) return;
const [q, r] = hexOf(p.lat, p.lon), k = q + ',' + r;
let h = hexes.get(k);
if (!h) {
h = { n: 0, off: 0, rtts: [], poly: L.polygon(hexPolygon(q, r), { stroke: false }).addTo(hexLayer) };
hexes.set(k, h);
}
// n and off are seconds, weighted by the gap each sample covers.
const w = p.g ?? POLL / 1000;
h.n += w;
// v1 samples timed a Digitraffic API call, roughly 150 ms heavier than today's edge probe.
if (p.ok) h.rtts.push(p.v === 2 ? p.rtt : Math.max(20, p.rtt - 150)); else h.off += w;
const m = h.rtts.length ? median(h.rtts) : null;
const q8 = h.off / h.n > .5 || m === null ? 'off' : quality({ ok: true, rtt: m });
// More time in a hex, more opaque: a single reading should not look like settled coverage.
h.poly.setStyle({ fillColor: COLORS[q8], fillOpacity: .18 + Math.min(h.n, 120) / 120 * .37 });
const offPct = Math.round(h.off / h.n * 100);
h.poly.bindTooltip(`${Math.round(h.n)} s sampled<br><span style="color:${m === null ? COLORS.off : COLORS[quality({ ok: true, rtt: m })]}">${m === null ? 'no answer' : 'median ' + m + ' ms'}</span><br><span style="color:${offPct > 50 ? COLORS.off : offPct > 0 ? COLORS.fair : COLORS.good}">${offPct}% offline</span>`, { sticky: true });
}
// Every trip ever logged feeds the coverage map. Trips older than 30 days are folded into per-hex totals,
// so the coverage keeps everything ever measured while the raw samples stop filling the browser's storage.
const ARCHIVE_AFTER = 30 * 86400000;
const archive = store.get('netmap-archive') || {};
for (const k of Object.keys(localStorage)) {
if (!k.startsWith('netmap-2')) continue;
const date = Date.parse(k.slice(7, 17));
if (Date.now() - date < ARCHIVE_AFTER) continue;
for (const p of store.get(k) || []) {
if (!p.lat) continue;
const [q, r] = hexOf(p.lat, p.lon), key = q + ',' + r, a = archive[key] || (archive[key] = [0, 0, 0, 0]);
const w = p.g ?? POLL / 1000;
a[0] += w;
if (p.ok) { a[2] += p.v === 2 ? p.rtt : Math.max(20, p.rtt - 150); a[3]++; } else a[1] += w;
}
localStorage.removeItem(k);
store.set('netmap-archive', archive);
}
for (const [key, [n, off, rttSum, rttN]] of Object.entries(archive)) {
const [q, r] = key.split(',').map(Number);
let h = hexes.get(key);
if (!h) { h = { n: 0, off: 0, rtts: [], poly: L.polygon(hexPolygon(q, r), { stroke: false }).addTo(hexLayer) }; hexes.set(key, h); }
h.n += n; h.off += off;
// The archive keeps a mean per hex; it enters the median as many times as it has minutes behind it.
if (rttN) for (let i = 0; i < Math.max(1, Math.min(20, Math.round(n / 60))); i++) h.rtts.push(Math.round(rttSum / rttN));
const m = h.rtts.length ? median(h.rtts) : null;
h.poly.setStyle({ fillColor: COLORS[h.off / h.n > .5 || m === null ? 'off' : quality({ ok: true, rtt: m })], fillOpacity: .18 + Math.min(h.n, 120) / 120 * .37 });
}
for (const k of Object.keys(localStorage)) if (k.startsWith('netmap-2')) (store.get(k) || []).forEach(addToHex);
// Storage is a few megabytes; a warning well before it fills beats a silent failure.
const used = Object.keys(localStorage).reduce((a, k) => a + (localStorage.getItem(k)?.length || 0), 0);
if (used > 3500000) $('notice').textContent = `Browser storage is ${Math.round(used / 50000)}% full. Export your data; trips older than 30 days are folded into the coverage map automatically.`;
// ---------- stations ----------
let stations = store.get('netmap-stations-v2') || [];
const stationName = code => stations.find(s => s.code === code)?.name || code;
const stationCode = text => {
const t = text.trim().toLowerCase();
return stations.find(s => s.name.toLowerCase() === t || s.code.toLowerCase() === t)?.code;
};
function fillStations() {
$('stations').replaceChildren(...stations.map(s => Object.assign(document.createElement('option'), { value: s.name })));
}
async function loadStations() {
if (stations.length) return fillStations();
const all = await get('/metadata/stations', 20000);
stations = all.filter(s => s.passengerTraffic && s.countryCode === 'FI')
.map(s => ({ code: s.stationShortCode, name: s.stationName.replace(/ asema$/, ''), lat: s.latitude, lon: s.longitude }))
.sort((a, b) => a.name.localeCompare(b.name, 'fi'));
store.set('netmap-stations-v2', stations);
fillStations();
}
// ---------- trip ----------
const params = new URLSearchParams(location.search);
// Digitraffic keys trains by their Finnish departure date, so the date must be local, never UTC.
const localDate = ms => { const d = new Date(ms); return new Date(d - d.getTimezoneOffset() * 60000).toISOString().slice(0, 10); };
const today = localDate(Date.now());
// "IC 63", "IC63" and "63" all mean train 63.
const trainNo = v => String(v ?? '').match(/\d+/)?.[0];
const lastTrip = store.get('netmap-trip');
// A trip from yesterday is still live after midnight on a night train.
let trip = [today, localDate(Date.now() - 86400000)].includes(lastTrip?.date) && trainNo(lastTrip.train) ? { ...lastTrip, train: trainNo(lastTrip.train) } : null;
if (trainNo(params.get('train'))) trip = { train: trainNo(params.get('train')), from: params.get('from'), to: params.get('to'), date: today };
// A trip is a list of legs, one per train; trip.train, from and to always mirror the leg being ridden now.
if (trip && !trip.legs) trip.legs = [{ train: trip.train, from: trip.from, to: trip.to, date: trip.date }];
if (trip) trip.leg ??= 0;
const isFinalLeg = () => !trip || trip.leg >= trip.legs.length - 1;
let stops = [], timetableAt = 0, trainLabel = '', track = [], trackEnd = Infinity, lastLate = null;
const pointsKey = () => `netmap-${trip.date}-${trip.train}`;
const stopsKey = () => `netmap-stops-${trip.date}-${trip.train}`;
const trackKey = () => `netmap-track-${trip.train}`;
async function findTrains(from, to) {
const board = await get(`/live-trains/station/${from}?arrived_trains=0&arriving_trains=0&departed_trains=20&departing_trains=20&include_nonstopping=false`, 20000);
const now = Date.now();
const options = board.map(t => {
const rows = t.timeTableRows;
const di = rows.findIndex(r => r.stationShortCode === from && r.type === 'DEPARTURE');
const ai = rows.findIndex((r, i) => i > di && r.stationShortCode === to && r.type === 'ARRIVAL');
return di >= 0 && ai >= 0 && { t, dep: when(rows[di]), arr: when(rows[ai]), label: trainName(t) };
}).filter(Boolean);
// Prefer the train that is between the two stations right now, then the nearest departure.
options.sort((a, b) => score(a) - score(b));
function score(o) { return now >= o.dep && now <= o.arr ? 0 : Math.abs(now - o.dep); }
if (options.length) return options;
// No direct train, so this is a journey with a change: every train running right now that still arrives at the destination.
// Trains that left the boarding station today show where a change could have happened; a candidate sharing a station with them ranks first.
const reachable = new Set(board.flatMap(t => { const i = t.timeTableRows.findIndex(r => r.stationShortCode === from); return i < 0 ? [] : t.timeTableRows.slice(i + 1).map(r => r.stationShortCode); }));
const arrivals = await get(`/live-trains/station/${to}?arrived_trains=0&arriving_trains=30&departed_trains=0&departing_trains=0&include_nonstopping=false`, 20000);
return arrivals.filter(t => t.runningCurrently).map(t => {
const rows = t.timeTableRows, ai = rows.findIndex(r => r.stationShortCode === to && r.type === 'ARRIVAL');
const change = rows.some(r => reachable.has(r.stationShortCode));
return ai >= 0 && { t, dep: when(rows[0]), arr: when(rows[ai]), change, label: trainName(t) };
}).filter(o => o && o.arr > now).sort((a, b) => (b.change - a.change) || (a.arr - b.arr));
}
async function loadTimetable() {
const train = trip.train;
let t;
try { [t] = await get(`/trains/${trip.date}/${train}`, 15000); }
finally { timetableAt = Date.now(); }
if (train !== trip?.train) return;
if (!t) {
stops = [];
timetableAt = Date.now();
$('trip-name').textContent = `Train ${trip.train} is not in today's timetable. Use Change trip to pick another.`;
$('trip-eta').textContent = '';
return;
}
trainLabel = trainName(t);
const rows = t.timeTableRows.filter(r => r.trainStopping && r.commercialStop);
const codes = [...new Set(rows.map(r => r.stationShortCode))];
// Boarded from another train: start at the last stop this train left before the first sample, or before now.
const t0 = points[0]?.t ?? Date.now();
const boarded = [...rows].reverse().find(r => r.type === 'DEPARTURE' && when(r) <= t0)?.stationShortCode;
const from = trip.from && codes.includes(trip.from) ? trip.from : boarded && codes.includes(boarded) ? boarded : codes[0];
const to = trip.to && codes.includes(trip.to) ? trip.to : codes.at(-1);
const seq = codes.slice(codes.indexOf(from), codes.indexOf(to) + 1);
stops = seq.map((code, i) => {
const arr = rows.find(r => r.stationShortCode === code && r.type === 'ARRIVAL');
const dep = rows.find(r => r.stationShortCode === code && r.type === 'DEPARTURE');
const row = (i === 0 ? dep : arr) || arr || dep;
return row && { code, name: stationName(code), t: when(row), late: row.differenceInMinutes || 0, passed: !!row.actualTime };
}).filter(Boolean);
store.set(stopsKey(), stops);
const late = stops.at(-1)?.late ?? 0;
if (lastLate != null && Math.abs(late - lastLate) >= 3) notify('delay', late > lastLate ? `Train now ${late}min late` : `Delay down to ${Math.max(0, late)}min`, `${stops.at(-1).name} at ${hhmm(stops.at(-1).t)}.`, 600000);
lastLate = late;
drawRoute();
}
// ---------- track ----------
// The same train number runs the same line every day, so its GPS trail from an earlier day is the real track geometry.
// A train's GPS trail from an earlier day, cached per train number.
const legTracks = {};
// A day's trail counts only if it passes within 2 km of both ends of the stretch; a train that lost GPS halfway would draw a stub.
const passesBoth = (pts, ends) => !ends || ends.every(([la, lo]) => pts.some(([a, b]) => L.latLng(a, b).distanceTo([la, lo]) < 2000));
async function fetchTrack(train, ends) {
const cached = store.get(`netmap-track-${train}`)?.pts;
if (cached?.length && passesBoth(cached, ends)) return cached;
for (let back = 1; back <= 7; back++) {
const d = localDate(Date.now() - back * 86400000);
const pts = await get(`/train-locations/${d}/${train}`, 30000).catch(() => []);
if (pts.length < 50) continue;
pts.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
const out = pts.filter((_, i) => i % 4 === 0).map(p => [+p.location.coordinates[1].toFixed(5), +p.location.coordinates[0].toFixed(5)]);
if (!passesBoth(out, ends)) continue;
store.set(`netmap-track-${train}`, { date: d, pts: out });
return out;
}
return [];
}
const endsOf = codes => { const at = codes.map(c => stations.find(x => x.code === c)).filter(Boolean); return at.length === codes.length ? at.map(s => [s.lat, s.lon]) : null; };
async function loadTrack() {
if (track.length) return;
const train = trip.train, pts = await fetchTrack(train, endsOf([trip.from, trip.to].filter(Boolean)));
if (train !== trip?.train || !pts.length) return;
track = pts;
drawRoute();
drawBaseline();
prefetchJourney();
}
function nearIndex(line, pos) {
let best = 0, bd = Infinity;
const [la, lo] = pos, k = Math.cos(la * Math.PI / 180);
line.forEach(([a, b], i) => { const d = (a - la) ** 2 + ((b - lo) * k) ** 2; if (d < bd) { bd = d; best = i; } });
return best;
}
const trackIndexNear = pos => nearIndex(track, pos);
// ---------- masts ----------
// Cell sites from OpenCelliD with the operator and the measured range of each; only the ones in view, from zoom 8 in.
const OPERATORS = { 5: 'Elisa', 21: 'Elisa', 91: 'Telia', 36: 'Telia', 12: 'DNA', 3: 'DNA', 14: 'Ålcom' };
const RADIOS = [[8, '5G'], [4, '4G'], [2, '3G'], [1, '2G']];
const mastLayer = L.layerGroup(), coverageLayer = L.layerGroup();
let masts = null, mastsOn = store.get('netmap-masts') ?? true;
function loadMasts() {
if (masts) return drawMasts();
const el = document.createElement('script');
el.src = 'data/fi-cells.js';
el.onload = () => { masts = window.NETMAP_CELLS || []; drawMasts(); nearestMast(); };
document.head.appendChild(el);
}
// Measured coverage: every Speedtest tile in view, so what surrounds a mast is what people actually got there.
function drawCoverageInView() {
coverageLayer.clearLayers();
if (!mastsOn || !ookla || map.getZoom() < 9) return;
const b = map.getBounds(), [x0, y0] = tileXY(b.getNorth(), b.getWest()), [x1, y1] = tileXY(b.getSouth(), b.getEast());
let n = 0;
for (let x = x0; x <= x1 && n < 4000; x++) for (let y = y0; y <= y1 && n < 4000; y++) {
const o = ookla.get(quadkey(x, y));
if (!o) continue;
n++;
L.rectangle(tileBounds(x, y), { stroke: false, fillColor: COLORS[tileQuality(o)], fillOpacity: .14, interactive: false }).addTo(coverageLayer);
}
}
function drawMasts() {
mastLayer.clearLayers();
drawCoverageInView();
if (!mastsOn || !masts || map.getZoom() < 8) return;
const b = map.getBounds().pad(.2);
const colour = { 5: '#4f8cff', 21: '#4f8cff', 91: '#b073ff', 36: '#b073ff', 12: '#ff6fb1', 3: '#ff6fb1' };
const inView = masts.filter(([lat, lon]) => b.contains([lat, lon]));
// Too many for one screen: an even sample across the view, never the first few hundred of the file.
const step = Math.max(1, Math.ceil(inView.length / 500));
// The measured range is where a site has been seen from; with more than a few dozen sites in view the circles blur into a blob, so they wait for a closer zoom.
const close = map.getZoom() >= 11 && inView.length <= 80;
for (const [lat, lon, nets, range, samples, radios, kind] of inView.filter((_, i) => i % step === 0)) {
const net = nets[0];
if (close && range) L.circle([lat, lon], { radius: range, stroke: false, fillColor: colour[net] || '#9fb0bf', fillOpacity: .05, interactive: false }).addTo(mastLayer);
const who = nets.length ? [...new Set(nets.map(n => OPERATORS[n] || 'MNC ' + n))].join(' and ') : 'operator unknown';
const tech = RADIOS.filter(([bit]) => radios & bit).map(([, name]) => name).join(', ');
const seen = range ? `<br>seen up to ${range >= 1000 ? (range / 1000).toFixed(1) + ' km' : range + ' m'} away, ${samples} measurements` : '';
const where = kind ? 'Mapped mast' : 'Cell seen from here, mast unmapped';
L.marker([lat, lon], {
icon: L.divIcon({ className: `mast op${net ?? 'x'}${kind ? '' : ' guessed'}`, html: `<i style="--d:-${(lat * 7919 + lon * 104729) % 3}s"></i><b></b>`, iconSize: [16, 16] }),
keyboard: false
}).bindTooltip(`${where}, ${who}${tech ? ', ' + tech : ''}${seen}`).addTo(mastLayer);
}
}
// The closest mapped mast to the train, with its operators where OpenCelliD knows them.
function nearestMast() {
if (!masts || !lastPos) return;
const [la, lo] = lastPos, k = Math.cos(la * Math.PI / 180);
let best = null, bd = Infinity;
for (const m of masts) {
if (!m[6]) continue;
const d = ((m[0] - la) * 111320) ** 2 + ((m[1] - lo) * 111320 * k) ** 2;
if (d < bd) { bd = d; best = m; }
}
if (!best) return;
const km = Math.sqrt(bd) / 1000, who = best[2].length ? [...new Set(best[2].map(n => OPERATORS[n] || 'MNC ' + n))].join(' and ') : 'operator unknown';
const tech = RADIOS.filter(([bit]) => best[5] & bit).map(([, name]) => name).join(', ');
$('near-mast').replaceChildren('Nearest mast ', Object.assign(document.createElement('b'), { textContent: km < 1 ? `${Math.round(km * 1000)} m` : `${km.toFixed(1)} km` }), `, ${who}${tech ? ', ' + tech : ''}.`);
}
function setMasts(on) {
mastsOn = on;
store.set('netmap-masts', on);
$('masts-btn').setAttribute('aria-pressed', on);
document.body.dataset.masts = on ? 'on' : 'off';
if (on) { coverageLayer.addTo(map); mastLayer.addTo(map); loadMasts(); } else { mastLayer.remove(); coverageLayer.remove(); }
}
map.on('moveend zoomend', drawMasts);
// ---------- forecast ----------
// Coverage ahead comes from earlier trips' hexes, so the first trip on a line has nothing to go on.
let speeds = [], poorSince = null, notified = {}, prefetched = new Set();
const RANK = { off: 0, poor: 1, fair: 2, good: 3 };
const NEIGHBOURS = [[0, 0], [1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
// A short tone from the page itself, for when the system notification is muted or hidden. Each kind of news has its own shape:
// falling for bad news, falling three times for a dead zone about to start, rising for good news, two even notes for information.
let audio = null;
const TONES = { bad: [[784, .12], [523, .24]], soon: [[784, .1], [587, .1], [392, .32]], good: [[523, .1], [659, .1], [784, .26]], info: [[880, .12], [880, .14]] };
function beep(name) {
if (!audio) return;
let t = audio.currentTime;
for (const [f, d] of TONES[name] || TONES.info) {
const o = audio.createOscillator(), g = audio.createGain();
o.type = 'sine'; o.frequency.value = f;
g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(.25, t + .02); g.gain.linearRampToValueAtTime(0, t + d);
o.connect(g).connect(audio.destination); o.start(t); o.stop(t + d + .02);
t += d + .05;
}
}
// Which alert kinds are on, kept in the browser.
const GROUP = { drop: 'deadzone', 'drop-soon': 'deadzone', offline: 'offline', 'eta-back': 'back', back: 'back', slower: 'slow', faster: 'faster', 'faster-ahead': 'faster', 'bw-low': 'bandwidth', 'bw-high': 'bandwidth', 'arrive-10': 'arrive', 'arrive-2': 'arrive', delay: 'delay' };
const alertsOn = Object.assign({ deadzone: true, offline: true, back: true, slow: true, faster: true, bandwidth: true, stop: true, arrive: true, delay: true, sound: true }, store.get('netmap-alerts') || {});
let titleFlash = '';
function notify(kind, title, body, gap = 180000) {
const group = GROUP[kind] || (kind.startsWith('stop-') || kind.startsWith('leg-') ? 'stop' : kind.startsWith('change-') ? 'arrive' : kind);
if (kind !== 'test' && !alertsOn[group]) return;
if (Date.now() - (notified[kind] || 0) < gap) return;
notified[kind] = Date.now();
// The page's own record, tone and title come first; the system notification is extra and needs permission.
const sticky = ['drop', 'drop-soon', 'offline', 'back', 'eta-back', 'arrive-2'].includes(kind);
$('alerts-last').textContent = `Last alert ${hhmm(Date.now())}: ${title}. ${body}`;
const tone = ['drop', 'drop-soon', 'offline', 'slower', 'bw-low', 'delay'].includes(kind) ? 'bad' : ['eta-back', 'arrive-10', 'arrive-2'].includes(kind) || kind.startsWith('stop-') ? 'warn' : '';
const toast = Object.assign(document.createElement('div'), { className: `toast ${tone}`, role: 'status' });
toast.append(Object.assign(document.createElement('b'), { textContent: title }), Object.assign(document.createElement('span'), { textContent: body }));
const dismiss = () => { toast.classList.add('leaving'); setTimeout(() => toast.remove(), 320); };
toast.onclick = dismiss;
$('toasts').prepend(toast);
setTimeout(dismiss, sticky ? 60000 : 20000);
titleFlash = title;
setTimeout(() => { if (titleFlash === title) titleFlash = ''; render(); }, 20000);
render();
if (alertsOn.sound) beep(kind === 'drop-soon' ? 'soon' : tone === 'bad' ? 'bad' : tone === 'warn' ? 'info' : 'good');
// The panel reports what became of the system banner, so a missing one can be traced to the browser or to macOS.
const report = text => { $('alerts-last').textContent += ` ${text}`; };
if (!canNotify()) return report(Notification.permission === 'denied' ? 'No system banner: notifications are blocked for this page.' : 'No system banner: notifications not allowed yet.');
try {
const n = new Notification(title, { body, tag: kind, requireInteraction: sticky, icon: `icon-${tone || 'good'}.png` });
let shown = false;
n.onshow = () => { shown = true; report('System banner shown.'); };
n.onerror = () => report('System banner failed: the browser could not display it. Check System Settings, Notifications, and that the browser is allowed there.');
setTimeout(() => { if (!shown) report('The browser never reported the banner as shown. On macOS, check System Settings, Notifications for the browser, and Focus.'); }, 3000);
} catch (e) { report(`System banner error: ${e.message}`); }
}
// Speedtest by Ookla open data: a 610 m grid of measured mobile speed for Finland, the baseline wherever own trips have nothing.
let ookla = null;
const tileScript = document.createElement('script');
tileScript.src = 'data/fi-mobile.js';
tileScript.onload = () => { ookla = new Map(window.NETMAP_TILES.map(([q, d, l, t]) => [q, { d, l, t }])); drawBaseline(); drawMasts(); forecast(); };
document.head.appendChild(tileScript);
function tileXY(lat, lon, z = 16) {
const n = 2 ** z, s = Math.sin(lat * Math.PI / 180);
return [Math.floor((lon + 180) / 360 * n), Math.floor((.5 - Math.log((1 + s) / (1 - s)) / (4 * Math.PI)) * n)];
}
function quadkey(x, y) { let v = 0; for (let i = 15; i >= 0; i--) v = v * 4 + (((x >> i) & 1) | (((y >> i) & 1) << 1)); return v; }
function tileBounds(x, y, z = 16) {
const n = 2 ** z, lon = i => i / n * 360 - 180, lat = j => Math.atan(Math.sinh(Math.PI * (1 - 2 * j / n))) * 180 / Math.PI;
return [[lat(y + 1), lon(x)], [lat(y), lon(x + 1)]];
}
const tileQuality = o => o.l < 150 && o.d >= 5 ? 'good' : o.l < 400 && o.d >= 1 ? 'fair' : 'poor';
// Only a fifth of the tiles along a rural line hold tests, so the nearest tested tile stands in: as is within 1.2 km,
// one step worse out to 3 km, and no signal beyond that, since nobody has managed a test within 3 km of the track.
const WORSE = { good: 'fair', fair: 'poor', poor: 'poor' };
function ooklaAt(lat, lon) {
if (!ookla) return null;
const [x, y] = tileXY(lat, lon);
for (let r = 0; r <= 5; r++) {
let best = null;
for (let dx = -r; dx <= r; dx++) for (let dy = -r; dy <= r; dy++) {
if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;
const o = ookla.get(quadkey(x + dx, y + dy));
if (o && (!best || o.t > best.t)) best = o;
}
if (best) return r <= 2 ? tileQuality(best) : WORSE[tileQuality(best)];
}
return 'off';
}
// Own hexes win; the track can run a kilometre or two off the straight line between stops, so the surrounding ring counts too.
function coverageAt(lat, lon) {
const [q, r] = hexOf(lat, lon);
let best = null;
for (const [dq, dr] of NEIGHBOURS) {
const h = hexes.get((q + dq) + ',' + (r + dr));
if (h && h.n >= 10 && (!best || h.n > best.n)) best = h;
}
if (best) {
const m = best.rtts.length ? median(best.rtts) : null;
return best.off / best.n > .5 || m === null ? 'off' : quality({ ok: true, rtt: m });
}
return ooklaAt(lat, lon);
}
// Speedtest tiles along the trip's track, drawn faintly under the hexes.
function drawBaseline() {
baseLayer.clearLayers();
if (!ookla || !track.length) return;
const seen = new Set();
for (const [lat, lon] of track) {
const [x, y] = tileXY(lat, lon), k = quadkey(x, y);
if (seen.has(k)) continue;
seen.add(k);
const o = ookla.get(k);
if (o) L.rectangle(tileBounds(x, y), { stroke: false, fillColor: COLORS[tileQuality(o)], fillOpacity: .16, interactive: false }).addTo(baseLayer);
}
}
function aheadPath(step = 500, max = 60000, from = lastPos) {
if (!from) return [];
const out = [];
if (track.length) {
let d = 0, nextAt = 0, prev = L.latLng(from);
for (let i = trackIndexNear(from); i < Math.min(track.length, trackEnd) && d < max; i++) {
const cur = L.latLng(track[i]), len = prev.distanceTo(cur);
while (nextAt <= d + len && nextAt < max) {
const f = len ? (nextAt - d) / len : 0;
out.push({ lat: prev.lat + (cur.lat - prev.lat) * f, lon: prev.lng + (cur.lng - prev.lng) * f, d: nextAt });
nextAt += step;
}
d += len; prev = cur;
}
return out;
}
const now = Date.now();
const coords = stops.filter(s => s.t > now).map(s => stations.find(x => x.code === s.code)).filter(Boolean).map(s => L.latLng(s.lat, s.lon));
if (!coords.length) return [];
const line = [L.latLng(from), ...coords];
let d = 0;
for (let i = 1; i < line.length && d < max; i++) {
const a = line[i - 1], b = line[i], len = a.distanceTo(b);
for (let t = 0; t < len && d + t < max; t += step) {
const f = t / len;
out.push({ lat: a.lat + (b.lat - a.lat) * f, lon: a.lng + (b.lng - a.lng) * f, d: d + t });
}
d += len;
}
return out;
}
function forecast() {
const el = $('forecast');
const path = aheadPath();
if (!path.length) { el.textContent = ''; return; }
const kmh = speeds.length ? median(speeds) : 90;
const mins = m => {
const v = Math.round(m / (kmh * 1000 / 60));
return v < 1 ? 'under a minute' : v < 60 ? `about ${v}min` : `about ${hours(Math.floor(v / 60))}, ${v % 60}min`;
};
// Distance tells little on a train; time at the current speed is the useful number, distance comes after it.
const span = m => `${mins(m)}, ${Math.round(m / 1000)} km`;
const ahead = path.map(p => ({ ...p, c: coverageAt(p.lat, p.lon) }));
const known = ahead.filter(p => p.c);
// Own hexes, from this and earlier trips, outrank the Speedtest baseline wherever they exist.
const ownAhead = known.filter(p => { const [q, r] = hexOf(p.lat, p.lon); return NEIGHBOURS.some(([dq, dr]) => (hexes.get((q + dq) + ',' + (r + dr))?.n || 0) >= 10); }).length > known.length / 2;
// Hexes from this trip only reach a couple of km ahead; a real forecast needs earlier trips on the line.
const now = Date.now(), reach = known.length ? known.at(-1).d : 0;
if (reach < 5000) {
const next = stops.find(s => s.t > now);
const drops = points.filter((p, i) => p.t > now - 1800000 && !p.ok && points[i - 1]?.ok).length;
const parts = [];
if (next) parts.push(`Next stop ${next.name} in about ${Math.max(1, Math.round((next.t - now) / 60000))}min.`);
if (drops) parts.push(`${drops} ${drops === 1 ? 'drop' : 'drops'} in the last 30min.`);
el.textContent = parts.join(' ');
return;
}
const last = points.at(-1), cur = !last?.ok ? 'off' : quality(last);
const say = (lead, strong, tail = '') => { el.replaceChildren(lead, Object.assign(document.createElement('b'), { textContent: strong }), tail); };
if (cur === 'off') {
const back = known.find(p => p.d >= 500 && RANK[p.c] >= RANK.poor);
if (!back) return say('No coverage logged for the next ', span(path.at(-1).d), '.');
say('Connection should be back in ', mins(back.d), ownAhead ? ', going by your earlier trips.' : ', going by Speedtest data.');
notify('eta-back', 'Connection expected back', `In ${mins(back.d)}, based on earlier trips.`, 600000);
return;
}
// A dead zone is at least two consecutive offline samples, about a kilometre of track.
const i = ahead.findIndex((p, k) => p.c === 'off' && ahead[k + 1]?.c === 'off');
if (i >= 0 && ahead[i].d < 20000) {
let j = i;
while (ahead[j + 1] && ahead[j + 1].c !== null && ahead[j + 1].c === 'off') j++;
const length = ahead[j].d - ahead[i].d + 500;
say('Dead zone in ', mins(ahead[i].d), `, lasting ${mins(length)}${ownAhead ? ', measured on your earlier trips' : ', from Speedtest data'}.`);
const inMin = ahead[i].d / (kmh * 1000 / 60);
if (inMin <= 1) notify('drop-soon', 'Dead zone in under a minute', `Lasts ${mins(length)}. Save your work.`, 600000);
else if (inMin <= 3) notify('drop', 'Dead zone ahead', `Starts in ${mins(ahead[i].d)} and lasts ${mins(length)}.`, 600000);
return;
}
if (cur === 'poor') {
const faster = known.find(p => RANK[p.c] >= RANK.fair);
if (faster) {
if (faster.d / (kmh * 1000 / 60) <= 2) notify('faster-ahead', 'Faster connection ahead', `In ${mins(faster.d)}.`, 600000);
return say('Faster connection in ', mins(faster.d), '.');
}
}
say(`${ownAhead ? 'Your earlier trips show' : 'Speedtest data shows'} a steady connection for the next `, span(reach), '.');
}
function watchSpeedUp(p) {
if (!p.ok) { poorSince = null; return; }
const q = quality(p);
if (q === 'poor') {
poorSince ??= p.t;
if (p.t - poorSince > 30000) notify('slower', 'Connection is slow', `Latency ${p.rtt} ms for half a minute.`, 300000);
return;
}
if (q === 'good' && poorSince && p.t - poorSince > 60000) notify('faster', 'Connection is faster', `Latency down to ${p.rtt} ms.`);
poorSince = null;
}
// Load the tiles along the route ahead while online, so the map keeps working in dead zones.
// Tiles for offline use: the whole journey once per trip at zooms 8-13, and the view one zoom in and out on every move.
const TILE = (z, x, y) => `https://basemaps.cartocdn.com/rastertiles/dark_all/${z}/${x}/${y}${L.Browser.retina ? '@2x' : ''}.png?key=${CARTO_KEY}`;
const tileQueue = [], tileSeen = new Set();
let tilesLoading = 0;
function queueTile(z, x, y) {
const k = `${z}/${x}/${y}`;
if (tileSeen.has(k)) return;
tileSeen.add(k);
tileQueue.push([z, x, y]);
}
function pumpTiles() {
// Six at a time, so the downloads never crowd out the probe on a thin link.
while (tilesLoading < 6 && tileQueue.length && online) {
const [z, x, y] = tileQueue.shift(), img = new Image();
tilesLoading++;
img.onload = img.onerror = () => { tilesLoading--; setTimeout(pumpTiles, 50); };
img.src = TILE(z, x, y);
}
}
function tileOf(lat, lon, z) { const n = 2 ** z; return [Math.floor((lon + 180) / 360 * n), Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * n)]; }
function prefetchJourney() {
if (!CARTO_KEY || !trip) return;
const lines = [track, ...Object.values(legTracks)].filter(l => l?.length);
for (const leg of trip.legTimes || []) if (leg?.codes) lines.push(leg.codes.map(c => stations.find(x => x.code === c)).filter(Boolean).map(s => [s.lat, s.lon]));
for (const line of lines) for (let i = 0; i < line.length; i += 3) {
const [lat, lon] = line[i];
for (let z = 8; z <= 13; z++) {
const [x, y] = tileOf(lat, lon, z), r = z >= 12 ? 1 : 0;
for (let dx = -r; dx <= r; dx++) for (let dy = -r; dy <= r; dy++) queueTile(z, x + dx, y + dy);
}
}
pumpTiles();
}
function prefetchView() {
if (!CARTO_KEY) return;
const b = map.getBounds(), z0 = map.getZoom();
for (const z of [z0 - 1, z0 + 1]) {
if (z < 5 || z > 15) continue;
const [x0, y0] = tileOf(b.getNorth(), b.getWest(), z), [x1, y1] = tileOf(b.getSouth(), b.getEast(), z);
if ((x1 - x0 + 1) * (y1 - y0 + 1) > 120) continue;
for (let x = x0; x <= x1; x++) for (let y = y0; y <= y1; y++) queueTile(z, x, y);
}
pumpTiles();
}
map.on('moveend', prefetchView);
function prefetchTiles() {
if (!CARTO_KEY) return;
const z = map.getZoom(), n = 2 ** z, want = [];
for (const p of aheadPath(1000, 150000)) {
const x = Math.floor((p.lon + 180) / 360 * n);
const y = Math.floor((1 - Math.log(Math.tan(p.lat * Math.PI / 180) + 1 / Math.cos(p.lat * Math.PI / 180)) / Math.PI) / 2 * n);
for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) {
const k = `${z}/${x + dx}/${y + dy}`;
if (!prefetched.has(k)) { prefetched.add(k); want.push(k); }
}
}
for (const k of want.slice(0, 60)) {
const [, x, y] = k.split('/');
new Image().src = tiles.getTileUrl(Object.assign(L.point(+x, +y), { z }));
}
// Leftovers go out on later ticks, 60 at a time.
want.slice(60).forEach(k => prefetched.delete(k));
}
function drawRoute() {
routeLayer.clearLayers();
const now = Date.now(), next = stops.find(s => s.t > now);
const pts = stops.map(s => ({ ...s, at: stations.find(x => x.code === s.code) })).filter(s => s.at);
const line = { weight: 3, lineCap: 'round', interactive: false };
// The same check for the train being ridden: a partial trail would draw a stub, so the stops are joined instead.
const trailOk = track.length && pts.length >= 2 && L.latLng(track[trackIndexNear([pts[0].at.lat, pts[0].at.lon])]).distanceTo([pts[0].at.lat, pts[0].at.lon]) < 2000 && L.latLng(track[trackIndexNear([pts.at(-1).at.lat, pts.at(-1).at.lon])]).distanceTo([pts.at(-1).at.lat, pts.at(-1).at.lon]) < 2000;
if (trailOk) {
const start = pts.length >= 2 ? trackIndexNear([pts[0].at.lat, pts[0].at.lon]) : 0;
trackEnd = pts.length >= 2 ? trackIndexNear([pts.at(-1).at.lat, pts.at(-1).at.lon]) + 1 : track.length;
L.polyline(track.slice(start, trackEnd), { ...line, weight: 2, color: '#93a6b5', opacity: .45 }).addTo(routeLayer);
const i = lastPos ? trackIndexNear(lastPos) : start;
L.polyline([...(lastPos ? [lastPos] : []), ...track.slice(i, trackEnd)], { ...line, color: '#eef3f6', opacity: .8 }).addTo(routeLayer);
} else if (pts.length >= 2) {
// Until the track has loaded, dashed straight lines between stops stand in for it.
const upcoming = pts.filter(s => s.t > now).map(s => [s.at.lat, s.at.lon]);
L.polyline(pts.map(s => [s.at.lat, s.at.lon]), { ...line, color: '#93a6b5', opacity: .5, dashArray: '1 9' }).addTo(routeLayer);
if (upcoming.length) L.polyline([...(lastPos ? [lastPos] : []), ...upcoming], { ...line, color: '#eef3f6', opacity: .8, dashArray: '1 9' }).addTo(routeLayer);
}
pts.forEach((s, i) => {
const end = i === 0 || i === pts.length - 1, isNext = s === pts.find(p => p.code === next?.code);
const passed = s.t <= now && !end;
L.circleMarker([s.at.lat, s.at.lon], {
radius: end ? 7 : isNext ? 6 : 5, color: '#eef3f6', weight: end || isNext ? 3 : 2,
fillColor: '#0d1b26', fillOpacity: 1, opacity: passed ? .5 : 1
}).bindTooltip(`${s.name} ${hhmm(s.t)}`, {
permanent: true, direction: 'right', offset: [8, 0],
className: `stop-label${end ? ' end' : ''}${isNext ? ' next' : ''}${passed ? ' passed' : ''}`
}).addTo(routeLayer);
});
// Connecting trains still ahead: their line dashed and dimmer, with every stop and the change stations named.
for (let j = (trip?.leg ?? 0) + 1; j < (trip?.legs.length ?? 0); j++) {
const lt = trip.legTimes?.[j], at = (lt?.codes || [trip.legs[j].from, trip.legs[j].to]).map((c, k) => { const st = stations.find(x => x.code === c); return st && { ...st, t: lt?.times?.[k] }; }).filter(Boolean);
if (at.length < 2) continue;