-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.html
1000 lines (872 loc) · 33 KB
/
map.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
<html>
<head>
<meta charset="utf-8" />
<title>Ski Touring Planning Map</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.10.3/math.min.js"></script>
<link rel="stylesheet" href="./dist/MarkerCluster.css" />
<link rel="stylesheet" href="./dist/MarkerCluster.Default.css" />
<link rel="stylesheet" href="./dist/leaflet-search.css" />
<!-- For Geocoding -->
<link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
<!-- For GPX displaying -->
<script src="./dist/gpx.min.js"></script>
<!-- For Routing -->
<link rel="stylesheet" href="./dist/leaflet-routing-machine.css" />
<script src="./dist/leaflet-routing-machine.js"></script>
<script src="./dist/L.Routing.OpenRouteService.js"></script>
<script src="./dist/L.Routing.Brouter.js"></script>
<script src="./dist/polyline.js"></script>
<script src="./dist/leaflet-controls-routing.js"></script> <!-- for the dropdown menu -->
<link rel="stylesheet" href="./dist/leaflet-controls-routing.css"> <!-- for the dropdown menu -->
<!-- Right Click Menu -->
<link rel="stylesheet" href="./dist/menu.css" />
<script src="./dist/menu.js"></script>
<!-- For Elevation graph -->
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="./dist/leaflet.elevation-0.0.4-d3v4.css" />
<script src="./dist/leaflet.elevation-0.0.4-d3v4.src.js"></script>
<!-- For control buttons -->
<link rel="stylesheet" href="./dist/easy-button.css" />
<script src="./dist/easy-button.js"></script>
<!-- Bootstrap icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<script src="./dist/leaflet.markercluster-src.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://unpkg.com/[email protected]/osmtogeojson.js"></script>
<script src="./dist/querystring.js"></script>
<script src="./dist/leaflet-search.js"></script>
<meta charset=utf-8>
<style>
#map {
width: 100%;
height: 100%;
position: absolute;
}
#wait {
margin-left: 25%;
margin-top: 15%;
padding: 20px;
width: 50%;
height: 50%;
min-height: 100px;
background-color: #adaaa1ee;
z-index: 100000;
position: absolute;
}
#legend-slope {
display: block;
z-index: 100000;
position: absolute;
bottom: 5;
right: 5;
pointer-events: none;
opacity: .85;
height: 200px;
}
.elevation{
z-index: 10000;
pointer-events: all;
}
.leaflet-top, .leaflet-bottom {
pointer-events: all;
}
.leaflet-touch .leaflet-control-layers-toggle{
width: 30px;
height: 30px;
}
body{
margin: 0px;
}
</style>
</head>
<body>
<!-- Right Click Menu -->
<div id="menu">
<a href="#" onclick="startHere(); return false;">
Start Here<span></span>
</a>
<a href="#" onclick="endHere(); return false;">
End here<span></span>
</a>
<hr>
<a href="#" onclick="createMarkerUrl(); return false;">
Create Marker <span></span>
</a>
<a href="#" onclick="copyLocation(); return false;">
Copy Location <span></span>
</a>
<hr>
<a href="#">
Close
</a>
<!-- <img src="./images/pin-icon-start.png" />Copy Location <span>Ctrl + ?!</span> -->
</div>
<!-- Fork me on github -->
<a href="https://github.com/Mael-Le-Garrec/ski_touring_map"><img style="position: absolute; top: 0; right: 0; border: 0; z-index:1000;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
<div id="map"></div>
<!-- Slope legend overlay -->
<img src="https://download.openslopemap.org/LegendeOpenSlopeMap.png" id="legend-slope">
<!-- Let's put an overlay on top of the map to tell the user to wait for the huts to load -->
<div id="wait">
<center style="margin-top: 20%;">
<h2>Loading Points of Interest</h2>
<img src="dist/img/loading.gif">
<p>Points of Interest to be loaded:<br> tourism=hut, tourism=wilderness_hut, tourism=viewpoint</p>
</center>
</div>
<script type="text/javascript">
// helper function to get a time in hours / min / sec instead of millisecs
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + "h " + minutes + "m " + seconds + "." + milliseconds + "s";
}
// -------------------------------------------------------------
// Add a function to get into the clipboard the current location
function copyLocation(e)
{
var pos = cursorLat + " " + cursorLng;
navigator.clipboard.writeText(pos).then(function() {}, function() {});
}
// -------------------------------------------------------------
// Define our base tiles: we'll be using the OSM winter map
var outdoorWinterStr = 'https://w3.outdooractive.com/map/v1/png/osm_winter/{z}/{x}/{y}/t.png?project=api-dev-oa';
var outdoorSummerStr = 'https://w3.outdooractive.com/map/v1/png/osm/{z}/{x}/{y}/t.png?project=api-dev-oa';
var opentopoStr = 'https://a.tile.opentopomap.org/{z}/{x}/{y}.png'
// It's useful to have the pistes to know where it's easy to ride
// We'll take them from opensnowmap
var pistesStr = 'http://tiles.opensnowmap.org/pistes/{z}/{x}/{y}.png';
// Highly inclined slopes are dangerous, it's nice to have a map of those
var slopesStr = 'https://tileserver1.openslopemap.org/OSloOVERLAY_LR_All_16/{z}/{x}/{y}.png';
function layerUrl(key, layer, format) {
if (format == null)
format = "image/jpeg"
return "https://wxs.ign.fr/" + key
+ "/geoportail/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&"
+ "LAYER=" + layer + "&STYLE=normal&TILEMATRIXSET=PM&"
+ "TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=" + format;
}
var ign_tiles_v2 = L.tileLayer(
layerUrl(
"essentiels", "GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2", "image/png"
),
{attribution: '© <a href="http://www.ign.fr/">IGN</a>'}
);
var ign_tiles = L.tileLayer(
layerUrl(
"gt1694g3zyh9h0k9qujff1v2", "GEOGRAPHICALGRIDSYSTEMS.MAPS"
),
{attribution: '© <a href="http://www.ign.fr/">IGN</a>'}
);
var ign_slopes = L.tileLayer(
layerUrl(
"altimetrie", "GEOGRAPHICALGRIDSYSTEMS.SLOPES.MOUNTAIN", 'image/png'
),
{attribution: '© <a href="http://www.ign.fr/">IGN</a>',
opacity: 0.5,
}
);
var ign_aviation = L.tileLayer(
layerUrl(
"gt1694g3zyh9h0k9qujff1v2", "GEOGRAPHICALGRIDSYSTEMS.MAPS.SCAN-OACI"
),
{attribution: '© <a href="http://www.ign.fr/">IGN</a>',
opacity: 0.5,
maxZoom: 11,
minZoom: 6,
}
);
// Background tiles for outdoor active
var outdoorSummer_tiles = L.tileLayer(outdoorSummerStr,
{
type: 'map',
maxZoom: 17,
minZoom: 2,
opacity: 0.7,
});
var outdoorWinter_tiles = L.tileLayer(outdoorWinterStr,
{
type: 'map',
maxZoom: 17,
minZoom: 2,
opacity: 0.7,
});
// Background tiles for OpenTopoMap
var opentopo_tiles = L.tileLayer(opentopoStr,
{
type: 'map',
maxZoom: 17,
minZoom: 2,
opacity: 0.7,
});
// Background tiles for 4uMaps, good for hiking
var foruMapsStr = "https://tileserver.4umaps.com/{z}/{x}/{y}.png"
var foruMaps_tiles = L.tileLayer(foruMapsStr,
{
type: 'map',
maxZoom: 17,
minZoom: 2,
opacity: 0.7,
});
// Google Satelite maps
var googleStr = 'http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}'
googleSat_tiles = L.tileLayer(googleStr,
{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
// Regular OSM
var osmStr = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osm_tiles = L.tileLayer(osmStr, {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
});
// Steepeness
var slopes_tiles = L.tileLayer(slopesStr,
{
type: 'map',
maxZoom: 16,
minZoom: 2,
opacity: 0.25,
});
// Pistes
var pistes_tiles = L.tileLayer(pistesStr,
{
type: 'map',
maxZoom: 18,
minZoom: 11,
opacity: 1,
});
// Add all those tiles to a dict we'll use later to be able to switch on
// and off the layers
var baseMaps = {
"OpenTopoMap": opentopo_tiles,
"4uMaps": foruMaps_tiles,
"OutdoorActive Summer": outdoorSummer_tiles,
"OutdoorActive Winter": outdoorWinter_tiles,
"OpenStreetMap": osm_tiles,
"IGN": ign_tiles,
"IGN v2": ign_tiles_v2,
"IGN Aviation": ign_aviation,
"Satellite": googleSat_tiles,
}
var overlayMaps = {
"Slopes": slopes_tiles,
"IGN Slopes": ign_slopes,
"Ski Pistes": pistes_tiles,
}
// Create an array for the default overlays to show
var defaultOverlays = ["Slopes", "Ski Pistes"];
var defaultOverlaysTiles = [];
for (const [key, value] of Object.entries(overlayMaps)) {
if (defaultOverlays.includes(key))
defaultOverlaysTiles.push(value);
}
// ------------------------------------------------------------
// Finally, the map object with our base tiles and the different layers
// Get the location in the URL if any
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var lng = urlParams.get('lng');
var lat = urlParams.get('lat');
var zoom = urlParams.get('z');
if (lat && lng)
var center = [lat, lng];
var map = L.map('map', {
center: (center) ? center : L.latLng(46, 5.2),
zoom: (zoom) ? zoom : 6,
layers: [opentopo_tiles].concat(defaultOverlaysTiles),
});
// Add an event handler to change the querystring when the basemap is changed
map.on('baselayerchange', onBaseAdd);
function onBaseAdd(e){
var overlayName = e['name'];
var newUrl = UpdateQueryString('basemap', overlayName);
history.pushState({}, null, newUrl);
}
var activeLayers = []; // populated after Huts definition
// Add event handlers when the overlays are ticked or unticked
map.on('overlayadd', onOverlayAdd);
function onOverlayAdd(e){
// Add the overlay to our list keeping track of them
if (activeLayers.includes(e['name']))
return;
activeLayers.push(e['name']);
// Update the URI
var overlayNames = activeLayers;
var params = encodeURIComponent(JSON.stringify(overlayNames));
var newUrl = UpdateQueryString('overlays', params);
history.pushState({}, null, newUrl);
}
// Add event handlers when the overlays are ticked or unticked
map.on('overlayremove', onOverlayRemove);
function onOverlayRemove(e){
// Add the overlay to our list keeping track of them
activeLayers.splice(activeLayers.indexOf(e['name']), 1);
// Update the URI
var overlayNames = activeLayers;
var params = encodeURIComponent(JSON.stringify(overlayNames));
var newUrl = UpdateQueryString('overlays', params);
history.pushState({}, null, newUrl);
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Whenever the map moves, update the URL
map.on('moveend', function (){
var mapCenter = map.getCenter();
var mapZoom = map.getZoom();
var newUrl = UpdateQueryString('z', mapZoom);
history.pushState({}, null, newUrl);
var newUrl = UpdateQueryString('lat', mapCenter.lat);
history.pushState({}, null, newUrl);
var newUrl = UpdateQueryString('lng', mapCenter.lng);
history.pushState({}, null, newUrl);
}
);
// ------------------------------------------------------------
// ------------------------------------------------------------
// Store the position of the cursor
var cursorLat;
var cursorLng;
var cursorLatLng;
const Coordinates = L.Control.extend({
onAdd: map => {
const container = L.DomUtil.create("div");
map.addEventListener("mousemove", e => {
cursorLat = e.latlng.lat;
cursorLng = e.latlng.lng;
cursorLatLng = e.latlng;
});
return container;
}
});
map.addControl(new Coordinates({position: "bottomleft" }));
// ------------------------------------------------------------
var orangeIcon = L.icon({
iconUrl: 'images/marker-icon-orange.png',
iconAnchor: [12, 40],
popupAnchor: [3, -45]
});
// ------------------------------------------------------------
// Check if we got a market in the URL for pointing stuff out
var listMarkers = new Array();
function createMarkerUrl(position, popup, notAddToUri)
{
// if the position isn't supplied, assume it's the cursor
if (!position)
position = [cursorLat, cursorLng];
var markerObj = new L.marker(position, {icon: orangeIcon}).addTo(map);
// Add a popup
//if (!popup || popup == "")
// popup = "Marker created by user";
var popupFinal = '<a href="#" onClick="removeOpenMarker()">Remove marker</a><br>'
if (popup)
popupFinal += popup;
markerObj.bindPopup(popupFinal);
// Update the URI
if (popup)
var marker = new Array(position[0], position[1], popup);
else
var marker = new Array(position[0], position[1]);
var markersUrl = JSON.parse(urlParams.get('markers'));
if (!markersUrl)
markersUrl = new Array();
listMarkers.push(marker);
if (!notAddToUri)
{
markersUrl.push(marker);
var strMarkers = encodeURI(JSON.stringify(markersUrl));
var newUrl = UpdateQueryString('markers', strMarkers);
history.pushState({}, null, newUrl);
}
}
// Get the data from the URI
var markersUrl = JSON.parse(urlParams.get('markers'));
if (markersUrl)
{
for (var markerPoint of markersUrl)
{
var markerPos = markerPoint.slice(0, 2);
var markerPopup = markerPoint.slice(2)[0];
createMarkerUrl(markerPos, markerPopup, true);
}
}
// Add a callback to store the current open marker
var currentOpenMarker;
map.on('popupopen', function(e) {
currentOpenMarker = e.popup._source;
});
// function to remove marker
function removeOpenMarker()
{
// remove the marker from the URI
var markersUrl = JSON.parse(urlParams.get('markers'));
var index = null; // Index to remove
var found = false;
var i;
for (i = 0; i < listMarkers.length; i++)
{
var markerPoint = listMarkers[i];
var lat = currentOpenMarker.getLatLng().lat;
var lng = currentOpenMarker.getLatLng().lng;
if (markerPoint[0] == lat && markerPoint[1] == lng)
{
index = i;
found = true;
break;
}
}
if (found)
listMarkers.splice(i, 1);
// Update the map
var strMarkers = encodeURI(JSON.stringify(listMarkers));
var newUrl;
if (listMarkers.length != 0)
newUrl = UpdateQueryString('markers', strMarkers);
else
newUrl = UpdateQueryString('markers', null);
history.pushState({}, null, newUrl);
// and from the map
map.removeLayer(currentOpenMarker);
currentOpenMarker = null;
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Define the function that queries certain POIs and displays them
function get_poi(poi, iconPOI, show, maxPoi, layer)
{
$.getJSON(poi, function (osmDataAsJson) {
var resultAsGeojson = osmtogeojson(osmDataAsJson);
var resultLayer = L.geoJson(resultAsGeojson, {
style: function (feature) {
return {color: "#ff0000"};
},
pointToLayer: function (feature, latlng) {
var name = feature.properties.tags.name;
name = (name) ? name : null;
return L.marker(latlng, {icon: iconPOI, title: feature.properties.tags.name});
},
filter: function (feature, layer) {
var isPolygon = (feature.geometry) && (feature.geometry.type !== undefined) && (feature.geometry.type === "Polygon");
if (isPolygon) {
feature.geometry.type = "Point";
var polygonCenter = L.latLngBounds(feature.geometry.coordinates[0]).getCenter();
feature.geometry.coordinates = [ polygonCenter.lat, polygonCenter.lng ];
}
return true;
},
onEachFeature: function (feature, layer) {
var popupContent = "";
popupContent = popupContent + "<dt>@id</dt><dd>" + feature.properties.type + "/" + feature.properties.id + "</dd>";
var keys = Object.keys(feature.properties.tags);
keys.forEach(function (key) {
poiKeys.add(key);
popupContent = popupContent + "<dt>" + key + "</dt><dd>" + feature.properties.tags[key] + "</dd>";
});
popupContent = popupContent + "</dl>"
layer.bindPopup(popupContent);
}
})
// Add our markers to the map and the layer group
resultLayer.addTo(layer);
// Disable the waiting div after the two loaded JSON
var counter = parseInt(document.getElementById("wait").getAttribute('counter'));
if (!counter)
counter = 0;
if (counter == (maxPoi - 1))
document.getElementById("wait").remove();
else
{
document.getElementById("wait").setAttribute("counter", counter + 1);
}
});
}
// Define icons for out huts
var viewpointIcon = L.icon({
iconUrl: 'images/viewpoint.png',
iconSize: [25, 25],
iconAnchor: [16, 25],
popupAnchor: [0, -28]
});
var paraglidingIcon = L.icon({
iconUrl: 'images/paraglider.png',
iconSize: [25, 25],
iconAnchor: [16, 25],
popupAnchor: [0, -28]
});
var houseIcon = L.icon({
iconUrl: 'images/house.png',
iconSize: [25, 25],
iconAnchor: [16, 25],
popupAnchor: [0, -28]
});
var hutIcon = L.icon({
iconUrl: 'images/hut.png',
iconSize: [25, 25],
iconAnchor: [16, 25],
popupAnchor: [0, -28]
});
var peakIcon = L.icon({
iconUrl: 'images/peak.png',
iconSize: [25, 25],
iconAnchor: [16, 25],
popupAnchor: [0, -28]
});
// Define some for the GPX tracks and routing
var startIcon = L.icon({
iconUrl: 'images/pin-icon-start.png',
iconAnchor: [10, 25],
popupAnchor: [0, -28]
});
var endIcon = L.icon({
iconUrl: 'images/pin-icon-end.png',
iconAnchor: [10, 25],
popupAnchor: [0, -28]
});
// ------------------------------------------------------------
// Define a layer group for the search function
var poiLayers = L.layerGroup();
var viewpointLayer = L.layerGroup();
var paraglidingLayer = L.layerGroup();
var poiKeys = new Set();
// Get the alpine huts and the wilderness huts
var maxPoi = 2
get_poi("json/alpine_hut.json", houseIcon, true, maxPoi, poiLayers);
get_poi("json/wilderness_hut.json", hutIcon, true, maxPoi, poiLayers);
//get_poi("json/viewpoint.json", viewpointIcon, true, maxPoi, viewpointLayer);
//get_poi("json/peak.json", peakIcon, false);
get_poi("json/paragliding.json", paraglidingIcon, true, maxPoi, paraglidingLayer);
// Add the search bar for addresses
L.Control.geocoder({'placeholder': 'Search for locations'}).setPosition('topleft').addTo(map);
// And add a search bar for the huts
L.control.search({
layer: poiLayers,
initial: false,
textPlaceholder: 'Search for huts',
propertyName: 'title',
buildTip: function(text, val) {
return '<a href="#">' + text + '</a>';
}
}).addTo(map);
// Add a button to switch everything on/off
overlayMaps['Huts'] = poiLayers;
overlayMaps['Paragliding'] = paraglidingLayer;
//overlayMaps['Viewpoints'] = viewpointLayer;
// ------------------------------------------------------------
// Look for GPX tracks and add them to the map
// Only show them if asked (gpx=1)
var showGpx = JSON.parse(urlParams.get('showGpx'));
var fileNames = new Array();
var gpxTracks = L.layerGroup()
$.ajax({
url: "./dist/gpx/",
success: function(data){
$(data).find("td > a").each(function(){
if ($(this).attr("href").endsWith(".gpx"))
{
var gpx = "./dist/gpx/" + $(this).attr("href"); // URL to your GPX file or the GPX itself
var fileName = decodeURI($(this).attr("href"));
var tracks = new L.GPX(gpx, {
async: true,
marker_options: {
startIconUrl: 'images/pin-icon-start.png',
endIconUrl: 'images/pin-icon-end.png',
shadowUrl: 'images/pin-shadow.png',
wptIconUrls: {
'': '',
},
popupAnchor: [0, -50],
},
}).on('loaded', function(e) {
var gpx = e.target
var keys = ["File Name", "Distance", "Total Time", "Start", "End", "Elevation +", "Elevation -", "Max Altitude", "Min Altitude"];
var funcs = [fileName,
(gpx.get_distance() / 1000).toFixed(2) + " km",
msToTime(gpx.get_total_time()),
gpx.get_start_time().toUTCString(),
gpx.get_end_time().toUTCString(),
(gpx.get_elevation_gain()).toFixed(0) + " m",
(gpx.get_elevation_loss()).toFixed(0) + " m",
(gpx.get_elevation_max()).toFixed(0) + " m",
(gpx.get_elevation_min()).toFixed(0) + " m",
];
var popupContent = "";
keys.forEach((key, index) => {
popupContent = popupContent + "<dt>" + key + "</dt><dd>" + funcs[index] + "<dd>";
});
gpx.bindPopup(popupContent);
});
tracks.addTo(gpxTracks);
}
});
}
});
overlayMaps['GPX'] = gpxTracks;
// Add a control for all those layers
var control_layer = L.control.layers(baseMaps, overlayMaps, {position: 'topleft'}).addTo(map);
// If there's an indication on which map to use, take it
var mapSelection = urlParams.get('basemap');
if (Object.keys(baseMaps).indexOf(mapSelection) > -1)
{
map.removeLayer(opentopo_tiles);
baseMaps[mapSelection].addTo(map);
}
// Add the huts to the defaultOverlays
defaultOverlays.push("Huts");
var l = defaultOverlays;
for (var i = 0; i < defaultOverlays.length; i++)
activeLayers.push(l[i]);
// If there's an indication on which overlay layers to use
// First remove all of them and then add the ones we have
var overlaySelection = JSON.parse(urlParams.get('overlays'));
if (!overlaySelection)
overlaySelection = defaultOverlays;
for (var key of defaultOverlays)
{
map.removeLayer(overlayMaps[key]);
}
for (var i = 0; i < overlaySelection.length; i++)
{
overlayMaps[overlaySelection[i]].addTo(map);
}
// --------------------------------------------------------------------------
// Create markers depending on the type of marker: end or start of the route?
function createMarker(i, waypoint, n)
{
var icon = new L.Icon.Default();
var title = '';
if (i == 0)
{
icon = startIcon;
title = "Start";
}
if (i == n-1)
{
icon = endIcon;
title = "End";
}
if (!title)
title = "Via " + i;
var marker = L.marker(waypoint.latLng, {
icon: icon,
title: title,
draggable: true,
});
var popup = '<a href="#" onClick="removeWaypoint(' + i + ')">Remove waypoint</a>';
var popup = popup + '<br><br><a href="#" onClick="invertRoute()">Invert Route</a>';
marker.bindPopup(popup);
return marker;
}
// Add the possibility to remove the waypoint via the popup
function removeWaypoint(waypoint)
{
// Remove at index 'waypoint' one element
control.spliceWaypoints(waypoint, 1);
}
// Add the possibility to invert the route
function invertRoute()
{
var wp = control.getWaypoints().reverse();
control.setWaypoints(wp);
}
// Add the routing feature itself
var geocoder = L.Control.Geocoder.nominatim();
var openRouteService = new L.Routing.openrouteservice('5b3ce3597851110001cf624802f67373a031434889627fc550c9671f');
var brouterWalking = new L.Routing.brouter('hiking-beta', '');
var brouterCycling = new L.Routing.brouter('fastbike', '');
// Define the routers and a default one: the first
var routers = new Array(openRouteService, brouterWalking, brouterCycling);
var router = routers[0];
var plan = new L.Routing.Plan([], {
createMarker: createMarker,
addWaypoints: true,
geocoder: geocoder,
routeur: router,
});
var lineOptions = {styles: [{color: 'black', opacity: 0.15, weight: 9}, {color: 'white', opacity: 0.8, weight: 6}, {color: 'red', opacity: 1, weight: 3}]};
var control = L.Routing.control({
routeWhileDragging: false,
geocoder: geocoder,
router: router,
plan: plan,
lineOptions: lineOptions,
summaryTemplate: `
<h2>{name}</h2><h3>{distance}, {time}</h3>
<h3><ul>
<li>E+: {elevation} m</li>
<li>Total E+: {PositiveElevation} m</li>
<li>Total E-: {NegativeElevation} m</li>
<li>Max Length E+: {maxLenElevation} m</li>
<li>Max Length E-: {minLenElevation} m</li>
<li>Δ : {topElevation} m</li>
</ul>
<center>
<input type="button" value="Export to GPX" onclick="exportGPX()">
</center>
</h3>
`
}).addTo(map);
// ------------------------------------------------------------
// Add a control to change the router
var dictRouters = {'OpenRouteService Walking': [routers[0], 'walking_man.png'],
'Brouter Walking': [routers[1], 'walking_man.png'],
'Brouter Cycling': [routers[2], 'bike.png'],
}
var routingCtrl = new RoutingControl(dictRouters, control, routers[0]);
routingCtrl.addTo(map);
// ------------- NOT USED ANYMORE
var toggle = L.easyButton({
states: [
{
stateName: 'brouter-router',
icon: '<img style="width:130%; margin-left:-3px; margin-top:2px;" src="./dist/img/brt.png">',
title: 'Click to Use Brouter Router',
onClick: function(_control) {
_control.state('openrouteservice-router');
var waypoints = control.getWaypoints();
router = routers[1];
control.setRouter(router);
control.setWaypoints(waypoints);
},
},
{
stateName: 'openrouteservice-router',
icon: '<img style="width:130%; margin-left:-3px; margin-top:2px;" src="./dist/img/ors.png">',
title: 'Click to Use OpenRouteService Router',
onClick: function(_control) {
_control.state('brouter-router');
var waypoints = control.getWaypoints();
router = routers[0];
control.setRouter(router);
control.setWaypoints(waypoints);
}
},
]
});
//toggle.addTo(map);
// ------------- NOT USED ANYMORE
// ------------------------------------------------------------
// Waypoints via URL
function updateWaypointUrl()
{
var waypoints = control.getWaypoints();
var waypointsUrl = []
for (var i = 0; i < waypoints.length; i++)
{
if (waypoints[i].latLng)
{
var array = Array(waypoints[i].latLng.lat, waypoints[i].latLng.lng);
waypointsUrl.push(array);
var newUrl = UpdateQueryString('waypoints', encodeURIComponent(JSON.stringify(waypointsUrl)));
history.pushState({}, null, newUrl);
// Update Router as well
newUrl = UpdateQueryString('router', encodeURIComponent(JSON.stringify(routingCtrl.getCurrentRouterName())));
history.pushState({}, null, newUrl);
}
}
}
control.getPlan().addEventListener("waypointsspliced", e => {
updateWaypointUrl();
});
control.getPlan().addEventListener("waypointschanged", e => {
updateWaypointUrl();
});
var waypoints = urlParams.get('waypoints');
if (waypoints)
{
var points = JSON.parse(waypoints);
for (var i = 0; i < points.length; i++)
if (i < 2)
control.spliceWaypoints(i, 1, new L.latLng(points[i]));
else
control.spliceWaypoints(i, 0, new L.latLng(points[i]));
}
// ------------------------------------------------------------
var routerUri = JSON.parse(urlParams.get('router'));
if (routerUri)
{
// Check the router given actually exists
if (Object.keys(dictRouters).includes(routerUri))
{
// Get the element and click on it. I don't want to code properly.
var div = document.getElementsByClassName("leaflet-control-layers-custom-toggle")[0];
div = div.parentNode.getElementsByTagName("section")[0].getElementsByTagName("div")[0];
var input;
var span;
// Look for the element we need
for (var i = 0; i < div.children.length; i++)
{
input = div.children[i].children[0].children[0];
span = div.children[i].children[0].children[1].textContent.trim();
if (span == routerUri)
{
input.click();
break;
}
}
}
}
// ------------------------------------------------------------
// Functions to add the current position to the geocoder and start routing
function startHere()
{
var pos = cursorLat + " " + cursorLng;
control.spliceWaypoints(0, 1, cursorLatLng);
}
function endHere()
{
var pos = cursorLat + " " + cursorLng;
control.spliceWaypoints(control.getWaypoints().length - 1, 1, cursorLatLng);
}
// ------------------------------------------------------------
// Add the elevation once it's done routing
var el = L.control.elevation({
position: "bottomleft",
});
function addElevation()
{
var coordinates = control.getCoordinates();
el.clear();
var geojson = {"name":"NewFeatureType",
"type":"FeatureCollection",
"features": [
{"type": "Feature",
"geometry": {"type": "LineString",
"coordinates":[]
},
"properties": null
}
]
}
var elevations = control.getElevations();
for (var i = 0; i < coordinates.length; i++)
geojson['features'][0]['geometry']['coordinates'].push(new Array(coordinates[i].lng, coordinates[i].lat, elevations[i]));
var gjl = L.geoJson(geojson,{
onEachFeature: el.addData.bind(el)
});
el.addTo(map);
}
control.addEventListener("routeselected", e => {
addElevation();
});
// ------------------------------------------------------------
// Add a button to export the GPX track
function exportGPX()
{
var baseUrl = "https://brouter.de/brouter?lonlats=";
var waypoints = control.getWaypoints();
for (var i = 0; i < waypoints.length; i++)
baseUrl += waypoints[i].latLng.lng + ',' + waypoints[i].latLng.lat + "|";
baseUrl += "&profile=hiking-beta&alternativeidx=0&format=gpx&exportWaypoints=1";
window.location.href = baseUrl;
}
</script>
</body>
</html>