-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk.html
3523 lines (3022 loc) · 109 KB
/
k.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>
<!--suppress JSUnresolvedFunction, JSUnresolvedVariable, HtmlFormInputWithoutLabel -->
<html lang="">
<head>
<meta charset="utf-8">
<title>Kartta</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no,width=device-width">
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&setLang=en' async defer ></script>
<!-- see: https://social.msdn.microsoft.com/Forums/en-US/bd8fe277-c0cf-4764-9fea-c2817451e7f3/problems-with-search-and-directions-with-bing-maps-when-setlangfi?forum=bingmaps -->
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.2/jquery.ui.touch-punch.min.js"></script>
<!-- <script src="js/CanvasPushpinModule.js"></script> -->
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.10.3.custom.min.css">
<script src="js/jquery.layout-latest.min.js"></script>
<!-- <script src="js/CanvasPushpinModule.js"></script> -->
<script src="https://rawcdn.githack.com/nextapps-de/winbox/0.2.0/dist/winbox.bundle.js"></script>
<style>
.hide {
display: none;
}
.wb-body {
right: 0;
top: 15px;
overflow: unset;
}
.wb-icon {
height: 15px;
}
.wb-title {
line-height: 15px;
}
</style>
<script type="text/javascript">
const options = {
email: "",
id: "",
logname: "",
interval: "5000",
usersTofollow: "",
send: false,
readGPS: true,
resend: false,
follow: false,
followMe: false,
showTime: true,
selectNewPin: true,
useDummyRect: false,
preventSleep: true,
smallRaport: false,
drawLogLine: false,
HCenter: true,
showAccuracy: true,
extra: false,
tpR: "0",
hasWakeLock: false,
useComps: false,
useCompsWindow: false,
};
let namedComponents = {};
/* View in fullscreen
* https://www.w3schools.com/howto/howto_js_fullscreen.asp
*/
function openFullscreen(elem) {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.webkitRequestFullscreen) { /* Safari */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { /* IE11 */
elem.msRequestFullscreen();
}
}
function setAutoComp(comp, name, value) {
comp[name] = value;
localStorage.setItem("acomp." + comp.name +"." + name, JSON.stringify(value));
}
function getAutoComp(comp, name, def, f) {
const s = localStorage.getItem("acomp." + comp.name +"." + name);
if (s===null) {
setAutoComp(comp, name, def);
return def;
}
let value = JSON.parse(s);
if (f) value = f(value);
return value
}
const getSpeed = function(comp, position) {
return position.coords.speed * 3.6;
}
const getAlt = function(comp, position) {
return position.coords.altitude;
}
const getDir = function(comp, position) {
return position.coords.heading;
}
const clearTrip = function (comp) {
setAutoComp(comp, "distSum", 0);
comp.lastPos = undefined;
localStorage.removeItem("acomp.Trip.lastPos");
comp.value = 0;
comp.span.innerText = "0.000";
}
const getTrip = function(comp, position) {
let coord = {latitude: position.coords.latitude, longitude: position.coords.longitude};
if (!startstop.checked) {
setAutoComp(comp, "lastPos", coord);
if ( comp.temp === undefined ) {
comp.temp = getAutoComp(comp, "distSum", 0);
return comp.temp;
}
return null;
}
let old = comp.lastPos;
if (old === undefined) {
old = getAutoComp(comp, "lastPos", coord);
}
const d = WGS84_distance(coord, old);
// componentsList["Temp"].span.innerText = d + " " + JSON.stringify(old);
let distSum = comp.distSum;
if (distSum === undefined) {
distSum = getAutoComp(comp, "distSum", 0);
}
if (d < 0.005) return distSum;
distSum += d;
setAutoComp(comp, "distSum", distSum);
setAutoComp(comp, "lastPos", coord);
return distSum;
}
const clearElap = function(comp) {
setAutoComp(comp, "elapZero", (new Date()).getTime());
setAutoComp(comp, "elapSum", 0);
}
const startCounters = function(start) {
let trip = namedComponents["Trip"];
let elap = namedComponents["Elap"];
if (elap) {
if (start) setAutoComp(elap, "elapZero", (new Date()).getTime());
else setAutoComp(elap, "elapSum", elap.sum);
}
}
const msToHMS = function(ms) {
const h = Math.floor(ms / 1000 / 60 / 60);
ms -= h* 1000 * 60 *60;
const m = Math.floor(ms / 1000 / 60);
ms -= m* 1000 * 60;
const s = Math.floor(ms / 1000);
return h + ":" + d2(m) + ":" + d2(s);
}
const getElap = function(comp, now) {
if (!startstop.checked) {
if ( comp.temp !== undefined) return null;
comp.temp = getAutoComp(comp, "elapSum", 0);
return msToHMS(comp.temp);
}
let old = comp.elapZero;
if (old === undefined) {
// old = getAutoComp(comp, "elapZero", now, value => new Date(value));
old = getAutoComp(comp, "elapZero", now.getTime());
}
// let diff = now.getTime() - old.getTime();
let nowt = now.getTime();
let diff = nowt - old;
const elapSum = getAutoComp(comp, "elapSum", 0);
diff += elapSum;
comp.sum = diff;
return msToHMS(diff);
}
const getTime = function(comp, now) {
const time = now.getHours() + ":" + d2(now.getMinutes()) + ":" + d2(now.getSeconds());
return time;
}
const componentsList = {
"Speed": {inUse: true, label: "Nopeus", unit: "km/h", font: "50px", back: "", len: 5, des: 1, f: getSpeed, type: 0},
"Trip": {inUse: true, label: "Matka", unit: "km", font: "40px", back: "", len:-4, des: 3, f: getTrip, type: 0, click: clearTrip},
"Alt": {inUse: true, label: "Korkeus", unit: "m", font: "30px", back: "", len: 4, des: 0, f: getAlt, type: 0},
"Dir": {inUse: true, label: "Suunta", unit: "deg", font: "20px", back: "", len: 3, des: 0, f: getDir, type: 0},
"Elap": {inUse: true, label: "Aika", unit: "aika", font: "20px", back: "", len: 3, des: -1, f: getElap, type: 1, click: clearElap},
"Time": {inUse: false, label: "Kello", unit: "", font: "20px", back: "", len: 3, des: -1, f: getTime, type: 1},
// "Temp": {inUse: true, label: "Temp", unit: "temp", font: "10px", back: "rgba(255, 255, 255, 0.6)", len: 3, des: -1, f: null, type: 2},
}
let geocomponents = [];
let timecomponents = [];
// Ks: https://github.com/richtr/NoSleep.js/blob/master/src/index.js
// The wake lock sentinel.
if ('wakeLock' in navigator) { options.hasWakeLock = true; }
let wakeLock = null;
// Function that attempts to request a screen wake lock.
// async // IE11 does not like async, but we manage without it using then and teh fact that this is never called in ie
function requestWakeLock() {
// alert('Start Wake Lock 2');
endWakeLock();
if (document.visibilityState === "hidden") return;
try {
// noinspection JSUnresolvedVariable
// wakeLock = await navigator.wakeLock.request('screen'); // does not work on ie
// wakeLock.addEventListener('release', function() {/* alert('Screen Wake Lock was released'); */ });
// alert('Screen Wake Lock is active');
navigator.wakeLock.request('screen').then(function(wl) {
wakeLock = wl;
wakeLock.addEventListener('release', function() {
// alert('Screen Wake Lock was released'); */
});
document.addEventListener('visibilitychange', handleVisibilityChange);
// alert('Screen Wake Lock is active');
});
} catch (err) {
alert(err.name + err.message);
}
}
if ('wakeLock' in navigator) {
options.hasWakeLock = true;
}
function handleVisibilityChange() {
if (wakeLock !== null && document.visibilityState === 'visible') {
requestWakeLock();
}
}
function startWakeLock() {
// alert('Start Wake Lock 1');
requestWakeLock();
}
function endWakeLock() {
if ( !wakeLock ) return;
wakeLock.release();
document.removeEventListener('visibilitychange', handleVisibilityChange);
wakeLock = null;
// alert('Wake Lock released');
}
function checkSleep() {
if ( options.preventSleep && options.hasWakeLock ) { startWakeLock(); }
if ( !options.preventSleep ) { endWakeLock(); }
}
function isChecked(name) {
return document.getElementById(name).checked;
}
$(document).ready(function () {
//$('body').layout({ applyDemoStyles: true });
initPage();
$("#menu").menu();
const routeDiv = $("#routeDiv");
const routeRaport = $("#routeRaport");
// noinspection JSValidateTypes
routeDiv.draggable({handle: ".move"});
routeDiv.resizable();
// noinspection JSValidateTypes
routeRaport.draggable({handle: ".move"});
routeRaport.resizable();
$('#editPinLoc').keypress(function(e){
if(e.keyCode === 13) {
$('#buttonAddPin').click();
return false;
}
});
// $(".dragable").draggableTouch();
closeNav();
readComponents();
checkShowComponents();
adjustComponents();
});
</script>
<script type="text/javascript">
jQuery(window).bind('beforeunload', function(){
return 'my text';
});
function goodbye(e) {
if (!e) { // noinspection JSDeprecatedSymbols
e = window.event;
}
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
//e.stopPropagation works in Firefox.
if (e.stopPropagation ) {
e.stopPropagation();
e.preventDefault();
}
const confirmationMessage = 'Haluatko lopettaa?'; //This is displayed on the dialog;
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage;
}
window.onbeforeunload=goodbye;
function getUrlVars()
{
let vars = [], hash;
const hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (let i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
const params = getUrlVars();
let map = null;
// let canvasLayer;
let directionsManager = null;
// const geoLocationProvider = null;
let tilelayer;
// const redIcon = "css/pin2/red.png";
const blueIcon = "css/pin2/blue.png";
const blueSelIcon = "css/pin2/blueSel.png";
const greenIcon = "css/pin2/green.png";
const greenSelIcon = "css/pin2/greenSel.png";
const greenDotIcon = "css/pin2/blackGreenDot.png";
const greenDotSelIcon = "css/pin2/blackGreenDotSel.png";
const redDotIcon = "css/pin2/blackRedDot.png";
const redDotSelIcon = "css/pin2/blackRedDotSel.png";
let currentPosPin = null;
let hitPin = null;
const followPinList = {};
const followPolylineList = {};
const followLocationsList = {};
const myLineVertices = [];
let myPolyline;
let trackList = null;
// noinspection JSUnusedGlobalSymbols
function GetMap() {
// Microsoft.Maps.loadModule('Microsoft.Maps.Themes.BingTheme',{ callback: ContinueGetMap });
// noinspection JSUnresolvedVariable,JSUnresolvedFunction
Microsoft.Maps.loadModule("Microsoft.Maps.SpatialMath", function () {
ContinueGetMap();
});
}
function ContinueGetMap() {
// Initialize the map
const pzoom = parseInt(params["zoom"]) || parseInt(localStorage.zoom) || 8;
const lon = params["lon"] || localStorage.lon || 25.75;
const lat = params["lat"] || localStorage.lat || 62.25;
const load = params["load"] || localStorage.load || "";
const route = params["route"] || localStorage.route || "";
const froute = params["froute"] || localStorage.froute || "";
const opens = params["open"] || "";
// noinspection JSUnresolvedVariable,JSUnresolvedFunction
map = new Microsoft.Maps.Map("#mapDiv",{
credentials:"Ao_g6EJt65LD09k5BdCLMyDSNnfnLtKjKkrDKTDCp4IvIEyldy5RlHr5gDd6JJQu",
culture: 'fi', homeRegion: 'FI',
zoom: pzoom,
mapTypeId: Microsoft.Maps.MapTypeId.road,
// mapTypeId: Microsoft.Maps.MapTypeId.mercator,
center:new Microsoft.Maps.Location(lat,lon)
});
// noinspection JSUnresolvedFunction,JSUnresolvedVariable
map.setView({ labelOverlay: Microsoft.Maps.LabelOverlay.hidden });
map.setOptions({disableStreetside: true})
// Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded, culture: 'fi', homeRegion: 'FI', theme: new Microsoft.Maps.Themes.BingTheme() });
// noinspection JSUnresolvedVariable
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', directionsModuleLoaded);
const tileSource = new Microsoft.Maps.TileSource({uriConstructor: getTilePath});
tilelayer = new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: 1 });
// map.entities.push(tilelayer);
const origo = new Microsoft.Maps.Location(0, 0);
currentPosPin = newPin(origo,false,"I",greenDotIcon,greenDotSelIcon);
hitPin = newPin(origo,true,"H",redDotIcon,redDotSelIcon);
Microsoft.Maps.Events.addHandler(map,'click',mapHit);
Microsoft.Maps.Events.addHandler(map,'viewchange',mapMove);
// Microsoft.Maps.Events.addHandler(map,'mousemove',mapHit); // experiment how pin follows mouse
let mapName = localStorage.getItem("mapName") || "Bing Maps normal";
let paramMapName = params["mapName"];
if ( paramMapName !== undefined ) mapName = paramMapName;
SelectMapMode(mapName);
const cb = $('#combobox')[0];
trackList = $('#tracklog')[0];
for (let i = 0; i<cb.options.length; i++) {
if ( cb.options[i].text === mapName ) {
cb.selectedIndex = i;
break;
}
}
let i = 1;
while ( true ) {
let p = params["p" + i] || false;
if ( !p ) break;
p = decodeURIComponent(p) || "";
addPinAt(p);
i++;
}
// geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map); // not any more in V8
// Get the user's current location
// myPolyline.setOptions({strokeThickness: 3, strokeColor: "orange"});
showCurrentPosition();
if ( load ) {
document.getElementById("editURLTrack").value = load.replaceAll(",", "\n");
AutoGrowTextArea(document.getElementById("editURLTrack"));
handleURLTrack();
}
if ( route ) {
document.getElementById("editURLRoute").value = route.replaceAll(",", "\n");
AutoGrowTextArea(document.getElementById("editURLRoute"));
handleURLRoute(froute);
}
// noinspection PointlessBooleanExpressionJS
if ( false && froute ) {
forceRoute(froute);
}
checkGeoLocation();
if ( opens ) {
const ops = opens.split(",");
for (let i in ops) {
openDiv(ops[i].trim());
}
}
}
function findMyPlace() {
const center = currentPosPin.getLocation();
map.setView({center:center});
}
let mapmode;
function copyToUrl() {
let tr = document.getElementById("editURLTrack").value.trim().replaceAll("\n", ",");
if ( tr !== "" ) tr = "&load="+tr;
let ro = document.getElementById("editURLRoute").value.trim().replaceAll("\n", ",");
if ( ro !== "" ) ro = "&route="+ro;
const pos = map.getCenter();
const url = "k.html?" +
"lat=" + pos.latitude.toFixed(5) +
"&lon=" + pos.longitude.toFixed(5) +
"&zoom=" + map.getZoom() +
"&mapName=" + mapmode +
tr + ro;
history.replaceState("object or string", "Title",url);
}
function copyRouteToUrl() {
const url = "k.html?" +
"zoom=" + map.getZoom() +
"&mapName=" + mapmode +
"&from=" + editFrom.value +
"&to=" + editTo.value +
"";
history.replaceState("object or string", "Title",url);
}
let mouseDown = false;
function mapHit(e) {
if ( mouseDown ) { mouseDown = false; return; }
if (e.targetType !== "map") return;
const point = new Microsoft.Maps.Point(e.getX(), e.getY());
const loc = e.target.tryPixelToLocation(point);
setHitPinLoc(loc);
DisplayLocPin(hitPin);
if ( isChecked("autoAddToRoute")) addToRoute();
}
let dst;
function setHitPinLoc(loc) {
hitPin.setLocation(loc);
calcDistance();
}
let selectedPin = null;
function calcDistance() {
if ( !selectedPin ) return;
if ( !hitPin ) return;
const d = WGS84_distance(selectedPin.getLocation(), hitPin.getLocation());
if (!dst) dst = $("#distance");
// dst.css( "border" , "3px solid red" );
dst[0].innerText = "" + d.toFixed(3) + " km";
}
function mapMove() {
mouseDown = true;
const pos = map.getCenter();
localStorage.lon = pos.longitude;
localStorage.lat = pos.latitude;
localStorage.zoom = map.getZoom();
if ( options.HCenter ) {
setHitPinLoc(map.getCenter());
DisplayLocPin(hitPin);
}
}
const belectro = {
link: "https://tanger.belectro.fi/tiles/mmltopo/v9/256/{0}/{2}/{1}?ref=7f2d",
ok: false,
init: function () {
if (this.ok) return;
this.ok = true;
$.ajax({
url: "https://www.mit.jyu.fi/demowww/cyclo/bbark.php",
success: function (data) {
const bbarkObj = JSON.parse(data);
let url = bbarkObj.base_map_groups[0].maps[0].url;
url = url.replace("{W}", "256");
url = url.replace("{Z}", "{0}");
url = url.replace("{Y}", "{2}");
url = url.replace("{X}", "{1}");
belectro.link = url;
},
async: false
})
}
};
// noinspection CheckImageSize
const mapModes = {
"Bing Maps normal" : { f:function(tile) {
return String.format("http://ecn.t1.tiles.virtualearth.net/tiles/r{0}?g=1135",TileXYToQuadKey(tile));
}, c:""},
"Bing Maps aerial" : { f:function(tile) {
return String.format("https://ecn.t1.tiles.virtualearth.net/tiles/h{0}?g=1135",TileXYToQuadKey(tile));
}, c:""},
"Google street" : { f:function(tile) { return String.format("https://mt1.google.com/vt/lyrs=m&z={0}&x={1}&y={2}",tile.zoom ,tile.x, tile.y ); },
c:'(c) <a href="http://maps.google.com/help/terms_maps.html" target="_blank">Google Maps</a>'},
"Google satellite" : { f:function(tile) { return String.format("https://mt1.google.com/vt/lyrs=y&z={0}&x={1}&y={2}",tile.zoom ,tile.x, tile.y ); },
c:'(c) <a href="http://maps.google.com/help/terms_maps.html" target="_blank">Google Maps</a>'},
// "Google Street" : { f:function(tile) { tile = nokiaConvert(tile); return String.format("https://maps.googleapis.com/maps/api/staticmap?center={1},{2}&zoom={0}&size=256x256&key=AIzaSyCpXjAoV19MUbpGd6e6YD9IketR2Gu-tqc",tile.zoom ,tile.x, tile.y); }, c:""},
// "Google satellite" : { f:function(tile) { tile = nokiaConvert(tile); return String.format("https://maps.googleapis.com/maps/api/staticmap?center={1},{2}&zoom={0}&size=256x256&key=AIzaSyCpXjAoV19MUbpGd6e6YD9IketR2Gu-tqc&maptype=hybrid",tile.zoom ,tile.x, tile.y); }, c:""},
// "Nokia" : { f:function(tile) { tile = nokiaConvert(tile); return String.format("http://m.nok.it/?app_id=_peU-uCkp-j8ovkzFGNU&app_code=gBoUkAMoxoqIWfxWA5DuMQ&h=256&w=256&ctr={1},{2}&z={0}&t=0&nord",tile.zoom ,tile.x, tile.y); }, c:""},
// "MapQuest" : { f:function(tile) { return String.format("http://otile1.mqcdn.com/tiles/1.0.0/map/{0}/{1}/{2}.png",Clip(tile.zoom,0,19) ,tile.x, tile.y); },
// c:'(c) <a href="http://info.mapquest.com/terms-of-use/" target="_blank">MapQuest</a>'},
"OpenStreet" : { f:function(tile) { return String.format("https://tile.openstreetmap.org/{0}/{1}/{2}.png",tile.zoom,tile.x,tile.y); },
c:'(c) <a href="http://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>'},
"OpenCycle" : //{ f:function(tile) { return String.format("http://a.tile.opencyclemap.org/cycle/{0}/{1}/{2}.png",tile.zoom ,tile.x, tile.y ); },
{ f:function(tile) { return String.format("https://tile.thunderforest.com/cycle/{0}/{1}/{2}.png?apikey=4e1589f40d3049469a043e2ec917dc88",tile.zoom ,tile.x, tile.y ); },
c:'(c) <a href="http://www.opencyclemap.org/docs/" target="_blank">OpenCycleMap</a>'},
"Landscape" : { f:function(tile) { return String.format("https://tile.thunderforest.com/landscape/{0}/{1}/{2}.png?apikey=4e1589f40d3049469a043e2ec917dc88",tile.zoom ,tile.x, tile.y ); },
c:'(c) <a href="http://www.opencyclemap.org/docs/" target="_blank">OpenCycleMap</a>'},
"Transport" : { f:function(tile) { return String.format("https://tile.thunderforest.com/transport/{0}/{1}/{2}.png?apikey=4e1589f40d3049469a043e2ec917dc88",tile.zoom ,tile.x, tile.y ); },
c:'(c) <a href="http://www.opencyclemap.org/docs/" target="_blank">OpenCycleMap</a>'},
"Outdoors" : { f:function(tile) { return String.format("https://tile.thunderforest.com/outdoors/{0}/{1}/{2}.png?apikey=4e1589f40d3049469a043e2ec917dc88",tile.zoom ,tile.x, tile.y ); },
c:'(c) <a href="http://www.opencyclemap.org/docs/" target="_blank">OpenCycleMap</a>'},
"Kapsi peruskartta" : { f:function(tile) { return String.format("http://tiles.kartat.kapsi.fi/peruskartta/{0}/{1}/{2}.jpg",tile.zoom ,tile.x, tile.y); },
c:'(c) <a href="http://www.maanmittauslaitos.fi/avoindata_lisenssi_versio1_20120501" target="_blank">Maanmittauslaitos</a>'},
"Kapsi Tausta" : { f:function(tile) { return String.format("http://tiles.kartat.kapsi.fi/taustakartta/{0}/{1}/{2}.jpg",tile.zoom ,tile.x, tile.y); },
c:'(c) <a href="http://www.maanmittauslaitos.fi/avoindata_lisenssi_versio1_20120501" target="_blank">Maanmittauslaitos</a>'},
"Kapsi Ilma" : { f:function(tile) { return String.format("http://tiles.kartat.kapsi.fi/ortokuva/{0}/{1}/{2}.jpg",tile.zoom ,tile.x, tile.y); },
c:'(c) <a href="http://www.maanmittauslaitos.fi/avoindata_lisenssi_versio1_20120501" target="_blank">Maanmittauslaitos</a>'
},
"b-bark SuomiTopo" : { f:function(tile) {
return String.format(belectro.link, tile.zoom, tile.x, tile.y);
},
c:'<span>Render:</span> <a href="https://www.b-bark.com" target="_blank"><img style="vertical-align:middle" src="css/b_bark_logo.png" width="20%" height="20%" alt=""/></a><br />(c) <a href="http://www.maanmittauslaitos.fi/avoindata_lisenssi_versio1_20120501" target="_blank">Maanmittauslaitos</a><br />',
i: belectro.init },
"DeLorme World Base" : { f:function(tile) { return String.format("https://server.arcgisonline.com/ArcGIS/rest/services/Specialty/DeLorme_World_Base_Map/MapServer/tile/{0}/{2}/{1}",tile.zoom ,tile.x, tile.y); },
c:'(c) <a href="http://www.esri.com/legal/software-license" target="_blank">ArgGIS</a>'},
"World Imagery" : { f:function(tile) { return String.format("https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{0}/{2}/{1}",tile.zoom ,tile.x, tile.y);},
c:'(c) <a href="http://www.esri.com/~/media/Files/Pdfs/legal/pdfs/e204_e300.pdf" target="_blank">ArgGIS</a>'},
"Ilmailu merged" : { f:function(tile) {
const airac = "1806";
return String.format('https://snapshots.openflightmaps.org/live/' + airac + '/tiles/world/noninteractive/epsg3857/merged/256/latest/{0}/{1}/{2}.png', tile.zoom, tile.x, tile.y);
},
c:'(c) <a href="https://openflightmaps.org/live/ef-finland/" target="_blank">openflightmaps.org</a>'},
"Ilmailu aero" : { f:function(tile) {
const airac = "1806";
return String.format('https://snapshots.openflightmaps.org/live/' + airac + '/tiles/world/noninteractive/epsg3857/aero/256/latest/{0}/{1}/{2}.png',tile.zoom ,tile.x, tile.y);
},
c:'(c) <a href="https://openflightmaps.org/live/ef-finland/" target="_blank">openflightmaps.org</a>'},
/*
"Ilmailu base" : { f:function(tile) {
var airac = "1806";
var url = String.format('https://snapshots.openflightmaps.org/live/' + airac + '/tiles/world/noninteractive/epsg3857/base/256/latest/{0}/{1}/{2}.png',tile.zoom ,tile.x, tile.y);
return url},
c:'(c) <a href="https://openflightmaps.org/live/ef-finland/" target="_blank">openflightmaps.org</a>'},
*/
};
function SelectMapMode(mode) {
const mm = mapModes[mode];
if ( mm === undefined ) return;
const logo = $(".logo");
logo.empty();
mapmode = mode;
// map.entities.remove(tilelayer);
// map.layers.remove(tilelayer);
map.layers.clear();
if ( mapmode !== "Bing Maps normal") {
// map.entities.push(tilelayer);
map.layers.insert(tilelayer);
map.setOptions( { mapTypeId: Microsoft.Maps.MapTypeId.mercator, allowHidingLabelsOfRoad : true } );
map.setView({ labelOverlay: Microsoft.Maps.LabelOverlay.hidden });
} else {
map.setOptions( { mapTypeId: Microsoft.Maps.MapTypeId.road, allowHidingLabelsOfRoad : false } );
map.setView({ labelOverlay: Microsoft.Maps.LabelOverlay.visible });
}
logo.append(mm.c);
if (typeof mm.i !== 'undefined') {
mm.i();
}
mapfunction = mm.f;
localStorage.setItem("mapName",mode);
}
// Simulation of C# string.Format, only {n} works.
if (!String.format) {
String.format = function(format) {
const args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
// Converts tile XY coordinates into a QuadKey at a specified level of detail.
function TileXYToQuadKey(tile) {
let quadKey = "";
for (let i = tile.zoom; i > 0; i--) {
let digit = '0';
const mask = 1 << (i - 1);
if ((tile.x & mask) !== 0) {
digit++;
}
if ((tile.y & mask) !== 0) {
digit++;
digit++;
}
quadKey += digit;
}
return quadKey;
}
function Clip(n, minValue, maxValue) {
if ( n < minValue ) return minValue;
if ( maxValue < n ) return maxValue;
return n;
}
// Convert Pixel map position to latitude/longitude
function PixelXYToLatLong(pixelX, pixelY, tile) {
const mapSize = 256 << tile.zoom;
const x = (Clip(pixelX, 0, mapSize - 1) / mapSize) - 0.5;
const y = 0.5 - (Clip(pixelY, 0, mapSize - 1) / mapSize);
tile.x = 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI;
tile.y = 360 * x; // tarkista kumminko päin
return tile;
}
// noinspection JSUnusedGlobalSymbols
function nokiaConvert(tile) {
tile.zoom = Clip(tile.zoom,0,20);
return PixelXYToLatLong(256 * tile.x + 128, 256 * tile.y + 128,tile);
}
function tileToWMSRect(tile) {
const mapSize = 256 << tile.zoom;
const pixelX = 256 * tile.x + 128;
const pixelY = 256 * tile.y + 128;
const x1 = (Clip(pixelX - 128, 0, mapSize - 1) / mapSize) - 0.5;
const y1 = 0.5 - (Clip(pixelY+128, 0, mapSize - 1) / mapSize);
const x2 = (Clip(pixelX+128, 0, mapSize - 1) / mapSize) - 0.5;
const y2 = 0.5 - (Clip(pixelY-128, 0, mapSize - 1) / mapSize);
return {
x1 : 90 - 360 * Math.atan(Math.exp(-y1 * 2 * Math.PI)) / Math.PI,
y1 : 360 * x1,
x2 : 90 - 360 * Math.atan(Math.exp(-y2 * 2 * Math.PI)) / Math.PI,
y2 : 360 * x2
};
}
let extra = params["extra"];
if ( !extra ) extra = getOptionValue("extra");
if ( extra ) {
mapModes["Merikartta"] = { f:function(tile) {
const rect = tileToWMSRect(tile);
return String.format("https://kartta.liikennevirasto.fi/meriliikenne//dgds/wms_ip/merikartta?VERSION=1.1.1&REQUEST=GetMap&WIDTH=256&HEIGHT=256&FORMAT=image/jpeg&SRS=EPSG:4326&BBOX={1},{0},{3},{2}&LAYERS=cells",rect.x1,rect.y1,rect.x2,rect.y2); },
c:'(c) <a href="https://portal.liikennevirasto.fi/sivu/www/f/liikenneverkko/merikartat" target="_blank">Liikennevirasto</a>'};
setOption("extra", true);
}
mapmode = "Bing map normal";
mapfunction = mapModes[mapmode];
function getTilePath(tile) {
// noinspection UnnecessaryLocalVariableJS
const url = mapfunction(tile);
//console.log(url);
return url;
}
function directionsModuleLoaded()
{
// Initialize the location provider
// geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map); // not anymore in V8
// Get the user's current location
showCurrentPosition();
if ( params["to"] ) {
if ( params["from"] ) findDriving();
}
}
function Ellipsoid(name, a, invf){
/* constructor */
this.name=name
this.a=a
this.invf=invf
}
const ells = [
new Ellipsoid("WGS84", 6378.137 / 1.852, 298.257223563),
new Ellipsoid("FAI sphere", 6371.0 / 1.852, 1000000000.)
];
function getEllipsoid(selection){
// document.spheroid.major_radius.value=ells[selection.selectedIndex+1].a*1.852
// document.spheroid.inverse_f.value=ells[selection.selectedIndex+1].invf
return ells[selection.selectedIndex];
}
function atan2(y,x) {
let out;
if (x <0) { out= Math.atan(y/x)+Math.PI;}
if ((x >0) && (y>=0)){ out= Math.atan(y/x);}
if ((x >0) && (y<0)) { out= Math.atan(y/x)+2*Math.PI;}
if ((x===0) && (y>0)) { out= Math.PI/2;}
if ((x===0) && (y<0)) { out= 3*Math.PI/2;}
if ((x===0) && (y===0)) {
//alert("atan2(0,0) undefined")
out= 0.
}
return out
}
function WGS84_distance(p1,p2) {
const selection = {selectedIndex: 0};
const m = Math.PI / 180;
return crsdist_ell(p1.latitude*m,p1.longitude*m,p2.latitude*m,p2.longitude*m,getEllipsoid(selection));
}
function crsdist_ell(glat1,glon1,glat2,glon2,ellipse){
// glat1 initial geodetic latitude in radians N positive
// glon1 initial geodetic longitude in radians E positive
// glat2 final geodetic latitude in radians N positive
// glon2 final geodetic longitude in radians E positive
const a = ellipse.a
const f = 1/ellipse.invf
//alert("a="+a+" f="+f)
let r, tu1, tu2, cu1, su1, cu2, s1, b1, f1;
let x, sx, cx, sy, cy, y, sa, c2a, cz, e, c, d;
const EPS = 0.00000000005;
let s;
let iter = 1;
const MAXITER = 100;
if ((glat1+glat2===0.) && (Math.abs(glon1-glon2)===Math.PI)){
alert("Course and distance between antipodal points is undefined")
glat1=glat1+0.00001 // allow algorithm to complete
}
if ( glat1===glat2 && (glon1===glon2 || Math.abs(Math.abs(glon1-glon2)-2*Math.PI) < EPS) ) {
//alert("Points 1 and 2 are identical- course undefined")
return 0.0; // don't care???
// noinspection UnreachableCodeJS
let out = new MakeArray(0)
out.d = 0
out.crs12 = 0
out.crs21 = Math.PI
return out
}
r = 1 - f
tu1 = r * Math.tan (glat1)
tu2 = r * Math.tan (glat2)
cu1 = 1. / Math.sqrt (1. + tu1 * tu1)
su1 = cu1 * tu1
cu2 = 1. / Math.sqrt (1. + tu2 * tu2)
s1 = cu1 * cu2
b1 = s1 * tu2
f1 = b1 * tu1
x = glon2 - glon1
d = x + 1 // force one pass
while ((Math.abs(d - x) > EPS) && (iter < MAXITER))
{
iter=iter+1
sx = Math.sin (x)
// alert("sx="+sx)
cx = Math.cos (x)
tu1 = cu2 * sx
tu2 = b1 - su1 * cu2 * cx
sy = Math.sqrt(tu1 * tu1 + tu2 * tu2)
cy = s1 * cx + f1
y = atan2 (sy, cy)
sa = s1 * sx / sy
c2a = 1 - sa * sa
cz = f1 + f1
if (c2a > 0.)
cz = cy - cz / c2a
e = cz * cz * 2. - 1.
c = ((-3. * c2a + 4.) * f + 4.) * c2a * f / 16.
d = x
x = ((e * cy * c + cz) * sy * c + y) * sa
x = (1. - c) * x * f + glon2 - glon1
}
x = Math.sqrt ((1 / (r * r) - 1) * c2a + 1)
x +=1
x = (x - 2.) / x
c = 1. - x
c = (x * x / 4. + 1.) / c
d = (0.375 * x * x - 1.) * x
x = e * cy
s = ((((sy*sy*4.-3.)*(1.-e-e)*cz*d/6.-x)*d/4.+cz)*sy*d+y)*c*a*r
return s*1.852;
/*
let faz, baz;
faz = modcrs(atan2(tu1, tu2))
baz = modcrs(atan2(cu1 * sx, b1 * cx - su1 * cu2) + Math.PI)
out=new MakeArray(0)
out.d=s
out.crs12=faz
out.crs21=baz
if (Math.abs(iter-MAXITER)<EPS){
alert("Algorithm did not converge")
}
return out
*/
}
let zoom;
function showCurrentPosition()
{
if ( currentPosPin == null ) return;
zoom = map.getZoom();
/*
geoLocationProvider.getCurrentPosition({
enableHighAccuracy:true,
showAccuracyCircle:options.showAccuracy,
successCallback:displayCenter,
updateMapView:false,
//errorCallback: function(object) { alert('Error callback invoked, error code ' + object.errorCode); }
});
*/
// getLocation();
}
/*
var locationStarted = false;
function getLocation() {
if ( locationStarted ) return;
locationStarted = true;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayCenter, errorCallBack, {enableHighAccuracy: true});
} else {
setError("Geolocation is not supported by this browser.");
}
}
*/
const geo_options = {
enableHighAccuracy: true,
maximumAge: 500,
timeout: 27000
};
let watcher = null;
function getGeoLocation() {
if ( watcher ) return;
if (navigator.geolocation) {
watcher = navigator.geolocation.watchPosition(displayCurrentPosition, errorCallBack, geo_options);
} else {
setError("Geolocation is not supported by this browser.");
}
}
function startGeoLocation(enable) {
if ( watcher ) navigator.geolocation.clearWatch(watcher);
watcher = null;
if ( enable ) getGeoLocation();
}
function checkGeoLocation() {
startGeoLocation(document.getElementById("readGPS").checked);
}
/*
function setCookie(cname,cvalue,exdays) {
const d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
const expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires; // + ";SameSite=None;";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
*/
const timers = {
follow : { t:null,f:getfollow,interval:1000 },
showPosition : { t:null, f:showCurrentPosition,interval:1000},
send : { t:null,f:sendPosition,interval:5000 },
resend : { t:null,f:sendPosition,interval:200000 },
showTime: { t:null,f:setTimeCompsValues,interval:1000 },
};
function checkTimer(timer, clear) {
// if ( timer=="send" && !options.sendPos) return;
const tim = timers[timer];
if ( options[timer] && !clear)
tim.t = setInterval(function(){ tim.f(); }, tim.interval);
else
clearInterval(tim.t);
}
let sending = false;
let lastGPSCoord;
function sendPosition() {
// checkTimer("send",true);
// checkTimer("resend",true);
clearError();
// getLocation();
if ( options.send ) {
if ( lastGPSCoord )