-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap-script.js
1588 lines (1359 loc) · 62.9 KB
/
map-script.js
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
const Version = '0.9.1 (2024-07-28)'
//Sample GPX as string for debugging purposes
const GPXDebug = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' +
'<gpx xmlns="https://www.topografix.com/GPX/1/1" creator="Nicks" version="1.1" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.topografix.com/GPX/1/1 https://www.topografix.com/GPX/1/1/gpx.xsd">\n' +
'<trk><name>GPX Debug Tracks</name>\n' +
'<trkseg>\n' +
'<trkpt lat="49.19648" lon="6.87825"></trkpt>\n' +
'<trkpt lat="49.19652" lon="6.8781"></trkpt>\n' +
'<trkpt lat="49.1966" lon="6.87799"></trkpt>\n' +
'<trkpt lat="49.19615" lon="6.87726"></trkpt>\n' +
'<trkpt lat="49.19494" lon="6.87891"></trkpt>\n' +
'<trkpt lat="49.19494" lon="6.87892"></trkpt>\n' +
'</trkseg>\n' +
'<trkseg>\n' +
'<trkpt lat="49.18578" lon="6.93061"></trkpt>\n' +
'<trkpt lat="49.18577" lon="6.93061"></trkpt>\n' +
'<trkpt lat="49.18578" lon="6.93084"></trkpt>\n' +
'<trkpt lat="49.18632" lon="6.93772"></trkpt>\n' +
'<trkpt lat="49.18648" lon="6.93912"></trkpt>\n' +
'<trkpt lat="49.18646" lon="6.9393"></trkpt>\n' +
'<trkpt lat="49.18643" lon="6.93948"></trkpt>\n' +
'<trkpt lat="49.18638" lon="6.93959"></trkpt>\n' +
'<trkpt lat="49.18543" lon="6.94096"></trkpt>\n' +
'<trkpt lat="49.18388" lon="6.943"></trkpt>\n' +
'<trkpt lat="49.18271" lon="6.9446"></trkpt>\n' +
'<trkpt lat="49.18035" lon="6.94773"></trkpt>\n' +
'<trkpt lat="49.1799" lon="6.9486"></trkpt>\n' +
'<trkpt lat="49.17887" lon="6.95088"></trkpt>\n' +
'</trkseg>\n' +
'</trk>\n' +
'</gpx>';
//************* */
//Global variables
var waypoints = [];
var markers = [];
var markerGroup = L.layerGroup();
var OSMDataLayer = L.layerGroup();
var OSMDataMarkers = L.markerClusterGroup({
spiderfyOnMaxZoom: false,
showCoverageOnHover: false,
zoomToBoundsOnClick: false
});
var routeCoords = [];
let routePolyline = null;
var OSMDataHidden = true;
var buttonDisplayOSMData;
var OSMDataDateTime;
var routingProfile = "bike";
//************* */
//Map layers
var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'});
var googleHybrid = L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']});
var googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']});
var googleTerrain = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']});
var IGN = L.tileLayer('https://wxs.ign.fr/essentiels/geoportail/wmts?service=WMTS&request=GetTile&version=1.0.0&tilematrixset=PM&tilematrix={z}&tilecol={x}&tilerow={y}&layer=GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2&format=image/png&style=normal', {
minZoom: 0,
maxZoom: 18,
tileSize: 256});
var map = L.map('map', {
center: [49, 6.9],
zoom: 10,
zoomControl: false,
contextmenu: true,
contextmenuWidth: 180,
contextmenuItems: [{
text: 'Démarrer Streetview ici',
callback: StartStreetview
},
{
text: 'Ajouter point d\'itinéraire',
callback: AddWaypoint
},
{
text: 'Ajouter marqueur',
callback: AddMarker
}],
layers: [osm]});
var baseMaps = {
"OpenStreetMap": osm,
"Google Hybrid": googleHybrid,
"Google Streets": googleStreets,
"Google Terrain": googleTerrain,
"IGN": IGN
};
var layerControl = L.control.layers(baseMaps).addTo(map);
L.control.zoom({
position: 'topright'
}).addTo(map);
markerGroup.addTo(map);
//************************************ */
//Controls *************************** */
// Custom control with buttons
var CustomControl = L.Control.extend({
options: {
position: 'topleft',
},
onAdd: function(map) {
var container = L.DomUtil.create('div', 'custom-control-container');
var buttonImportGPX = L.DomUtil.create('button', 'custom-control-button2', container);
buttonImportGPX.innerHTML = 'Importer fichier GPX';
buttonImportGPX.onclick = function() {
document.getElementById('gpx-input').click();
};
var buttonDownloadGPX = L.DomUtil.create('button', 'custom-control-button2', container);
buttonDownloadGPX.innerHTML = 'Télécharger fichier GPX';
buttonDownloadGPX.onclick = function() {
var filename = 'GPX_' + getCurrentDateTimeFormated() + '.gpx';
downloadTrack(filename, 'text/csv;encoding:utf-8');
};
var buttonImportProject = L.DomUtil.create('button', 'custom-control-button', container);
buttonImportProject.innerHTML = 'Importer projet';
buttonImportProject.onclick = function() {
document.getElementById('project-input').click();
};
var buttonDownloadProject = L.DomUtil.create('button', 'custom-control-button', container);
buttonDownloadProject.innerHTML = 'Télécharger projet';
buttonDownloadProject.onclick = function() {
var filename = 'TWP_' + getCurrentDateTimeFormated() + '.twp';
downloadProject(filename, 'text/csv;encoding:utf-8');
};
buttonDisplayOSMData = L.DomUtil.create('button', 'custom-control-button', container);
buttonDisplayOSMData.innerHTML = 'Afficher données OSM';
buttonDisplayOSMData.onclick = function() {
displayOSMData();
};
var buttonDownloadOSMData = L.DomUtil.create('button', 'custom-control-button', container);
buttonDownloadOSMData.innerHTML = 'Télécharger données OSM';
buttonDownloadOSMData.onclick = function() {
downloadOSMData('OSM_Data.xml');
};
var buttonAbout = L.DomUtil.create('button', 'custom-control-button', container);
buttonAbout.innerHTML = 'Infos';
buttonAbout.onclick = function() {
showInfo();
};
return container;
},
onRemove: function(map) {
// Cleanup when removed
}
});
// Add the custom control to the map
(new CustomControl()).addTo(map);
// Information Control
var InfoControl = L.Control.extend({
options: {
position: 'bottomright'
},
onAdd: function (map) {
var cheminDistance = 0;
var cheminTime = '0:00';
var secondDistance = 0;
var secondTime = '0:00';
var principDistance = 0;
var principTime = '0:00';
var fastDistance = 0;
var fastTime = '0:00';
var totalDistance = 0;
var totalTime = '0:00';
var container = L.DomUtil.create('div', 'info-container');
container.innerHTML = '<div><label for="mode-select">Type routage: </label>' +
'<select id="mode-select"><option value="bike">Tout-terrain</option><option value="car">Voiture</option></select></div>' +
'<h4>Distance - Temps</h4>' +
'<p>Chemins: <span id="dist-path-value">' + cheminDistance + '</span> km - <span id="time-path-value">' + cheminTime + '</span><br />' +
'Routes secondaires: <span id="dist-second-value">' + secondDistance + '</span> km - <span id="time-second-value">' + secondTime + '</span><br />' +
'Routes principales: <span id="dist-princip-value">' + principDistance + '</span> km - <span id="time-princip-value">' + principTime + '</span><br />' +
'Voies rapides: <span id="dist-fast-value">' + fastDistance + '</span> km - <span id="time-fast-value">' + fastTime + '</span><br /></p>' +
'<p><strong>Total: <span id="dist-total-value">' + totalDistance + '</span> km - <span id="time-total-value">' + totalTime + '</span></strong></p>';
//container.appendChild(ctx);
return container;
}
});
// Ajouter le contrôle personnalisé à la carte
map.addControl(new InfoControl());
document.getElementById('mode-select').addEventListener('change', function(event)
{
routingProfile = event.target.value;
});
// Geo Search Bar
var geocoder = L.Control.geocoder({
defaultMarkGeocode: false,
})
.on('markgeocode', function(e) {
var bbox = e.geocode.bbox;
var poly = L.polygon([
bbox.getSouthEast(),
bbox.getNorthEast(),
bbox.getNorthWest(),
bbox.getSouthWest()
]);
map.fitBounds(poly.getBounds());
})
.addTo(map);
// Geolocalization
L.control.locate({
position: "topright",
strings:{title:"Position actuelle"},
showPopup : false
}).addTo(map);
//************************************ */
// Buttons
// Import GPX Button
document.getElementById('gpx-input').addEventListener('change', function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var gpxContent = e.target.result;;
new L.GPXHelper(gpxContent, {
marker_options : {
addStartEndIcons: true,
wptIconUrl : 'res/marker-i-50x50_Violet.png',
iconSize: [30, 30],
iconAnchor: [15, 30]
},
polyline_options : {
color: '#a00af7', //Violet
weight: 3
}
}).on('loaded', function(e) {
var gpx = e.target;
map.fitBounds(gpx.getBounds());
layerControl.addOverlay(gpx, gpx.get_name() + " (" + "Violet" + ")");
}).addTo(map);
};
reader.readAsText(file);
});
// Download GPX Button
var downloadTrack = function (fileName, mimeType) {
var coord = [];
if(routeCoords.length !== 0)
{
for(let i = 0; i < routeCoords.length; i++) {
for (let j = 0; j < routeCoords[i].coords.length; j++)
coord.push(routeCoords[i].coords[j]);
}
}
else
console.log("no routes to export");
var timestamp = new Date().toLocaleString('en-GB');
gpxcontent = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n<gpx xmlns="https://www.topografix.com/GPX/1/1" creator="Nicks" version="1.1" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.topografix.com/GPX/1/1 https://www.topografix.com/GPX/1/1/gpx.xsd">\n';
for (var i = 0; i < markers.length; i++) {
gpxcontent += '<wpt lat="' + markers[i].lat + '" lon="' + markers[i].lng + '">\n\t<name></name>\n\t<desc></desc>\n</wpt>\n';
}
if(coord.length !== 0) {
gpxcontent += "<trk>\n\t<name>" + timestamp + "</name>\n";
gpxcontent += "\t<trkseg>\n";
for (var i = 0; i < coord.length; i++) {
gpxcontent += '\t<trkpt lat="' + coord[i].lat + '" lon="' + coord[i].lng + '"></trkpt>\n';
}
gpxcontent += '\t</trkseg>\n</trk>\n';
}
gpxcontent += "</gpx>";
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([gpxcontent], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([gpxcontent], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(gpxcontent); // only this mime type is supported
}
}
// Import Project Button
document.getElementById('project-input').addEventListener('change', function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var filecontent = e.target.result;
var parser = new DOMParser();
setTimeout(function()
{
parseFile(parser.parseFromString(filecontent, "text/xml"));
});
}
reader.readAsText(file);
})
var parseFile = function(file)
{
var layers = [];
// parse markers
el = file.getElementsByTagName('marker');
for (i = 0; i < el.length; i++) {
var ll = new L.LatLng(
el[i].getAttribute('lat'),
el[i].getAttribute('lon'));
var nameEl = el[i].getElementsByTagName('name');
var name = nameEl.length > 0 ? nameEl[0].textContent : '';
var descEl = el[i].getElementsByTagName('desc');
var desc = descEl.length > 0 ? descEl[0].textContent : '';
var marker = {"latlng": ll};
AddMarker(marker);
}
var routeCoords = file.getElementsByTagName('rte');
var data = [];
for (i = 0; i < routeCoords.length; i++)
{
var routeCoord = routeCoords[i];
var segments = routeCoord.getElementsByTagName('rteseg');
for (j = 0; j < segments.length; j++)
{
var distance = parseFloat(segments[j].getAttribute('distance'));
var road_class = segments[j].getAttribute('road_class');
var surface = segments[j].getAttribute('surface');
var el = segments[j].getElementsByTagName('rtept');
if (!el.length) return [];
var coords = [];
var elev = [];
for (var i = 0; i < el.length; i++)
{
var ll = new L.LatLng(
el[i].getAttribute('lat'),
el[i].getAttribute('lon'));
coords.push(ll);
elev.push(parseFloat(el[i].getAttribute('ele')));
}
data.push({"coords" : coords, "elevation" : elev, "distance" : distance, "road_class" : road_class, "surface" : surface});
if(j === 0)
{
var wpt = {"latlng": coords[0]};
AddWaypoint(wpt);
}
else if(j === segments.length - 1)
{
var wpt = {"latlng": coords[0]};
AddWaypoint(wpt, data[data.length - 2]);
wpt = {"latlng": coords[coords.length - 1]};
AddWaypoint(wpt, data[data.length - 1]);
var topleft = data[0].coords[0];
var bottomright = data[data.length - 1].coords[data[data.length - 1].coords.length - 1];
map.fitBounds([topleft, bottomright]);
}
else
{
var wpt = {"latlng": coords[0]};
AddWaypoint(wpt, data[data.length - 2]);
}
}
}
}
// Download Project Button
var downloadProject = function (fileName, mimeType)
{
var timestamp = new Date().toLocaleString('en-GB');
fileContent = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n<twp>\n';
for (var i = 0; i < markers.length; i++) {
fileContent += '<marker lat="' + markers[i].lat.toPrecision(6) + '" lon="' + markers[i].lng.toPrecision(6) + '">\n\t<name></name>\n\t<desc></desc>\n</marker>\n';
}
if(routeCoords.length !== 0) {
fileContent += '<rte>\n';
for(let i = 0; i < routeCoords.length; i++)
{
fileContent += '\t<rteseg distance="' + routeCoords[i].distance + '" road_class="' + routeCoords[i].road_class + '" surface="' + routeCoords[i].surface + '">\n';
for (let j = 0; j < routeCoords[i].coords.length; j++)
fileContent += '\t\t<rtept lat="' + routeCoords[i].coords[j].lat + '" lon="' + routeCoords[i].coords[j].lng + '" ele="' + routeCoords[i].elevation[j] + '"></rtept>\n';
fileContent += '\t</rteseg>\n';
}
fileContent += '</rte>\n';
}
fileContent += '</twp>';
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([gpxcontent], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([fileContent], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(fileContent); // only this mime type is supported
}
}
//************************************ */
//Load database files
var gpx = GPXDebug; // GPX as string used for debugging
// Sections Autorisées/praticable par tout temps => DB - Tout Schuss (Vert)
// Sections Autorisées/praticable par temps sec uniquement => DB - Ça glisse! (Orange)
// Sections Tolérées => DB - Tolérées (Rouge)
// Sections Interdites => DB - Verboten! (Noir)
var fileArray = [
["tracks/db/OK_Anytime.gpx", "#159917"],
["tracks/db/OK_OnlyDry.gpx", "#f2ab11"],
["tracks/db/Tolerated.gpx", "#f70a0a"],
["tracks/db/Verboten.gpx", "#000000"]
];
for (const file of fileArray) {
new L.GPXHelper(file[0], {
polyline_options : {color: file[1], weight: 7, interactive: false}
}).on('loaded', function(e) {
var gpx = e.target;
layerControl.addOverlay(gpx, gpx.get_name());
}).addTo(map);
}
//Add Markers
new L.GPXHelper("tracks/db/Markers.gpx", {
marker_options : {
wptIconUrl : 'res/marker-i-50x50_Orange.png',
iconSize: [30, 30],
iconAnchor: [15, 30]
}
}).on('loaded', function(e) {
}).addTo(map);
/*new L.GPX(gpx, {async: true, gpx_options:{ joinTrackSegments: false}}).on('loaded', function(e) {
var gpx = e.target;
layerControl.addOverlay(gpx, gpx.get_name());
}).addTo(map);*/
/*new L.GPXHelper(GPXDebug, {
polyline_options : {color: "#159917"}
}).on('loaded', function(e) {
var gpx = e.target;
layerControl.addOverlay(gpx, gpx.get_name());
}).addTo(map);*/
// Attendre que les overlays soient chargés
setTimeout(function() {
// Accédez aux éléments DOM des étiquettes de couche d'overlay
var overlayLabels = document.querySelectorAll('.leaflet-control-layers-overlays label');
// Changez les couleurs des étiquettes de couche d'overlay
for (let i = 0; i < fileArray.length; i++) {
overlayLabels[i].style.color = fileArray[i][1];
}
// Changez les couleurs d'autres couches d'overlay comme souhaité
}, 1000); // Attendre 1000 millisecondes (1 seconde) avant d'exécuter le code
//OSM Data
var file = "tracks/db/OSM_Data.xml";
var req = new window.XMLHttpRequest();
req.open('GET', file, true);
try {
req.overrideMimeType('text/xml'); // unsupported by IE
} catch(e) {}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if(req.status == 200)
{
//console.log(req.responseXML);
parseOSMDataFile(req.responseXML);
}
};
req.send(null);
function parseOSMDataFile(input)
{
var metadata = input.getElementsByTagName('metadata');
OSMDataDateTime = metadata[0].getAttribute('creationtime');
// Définir l'icône personnalisée pour les marqueurs de barrières
var customIcon = L.icon({
iconUrl: 'res/round_red_blk_light.png', // Chemin de l'image sur le serveur. src: https://icons8.com/icons/set/marker--static
iconSize: [20, 20], // Taille de l'icône [largeur, hauteur]
//iconAnchor: [0, 0], // Point d'ancrage de l'icône par rapport à son coin supérieur gauche
popupAnchor: [0, 0] // Point d'ancrage de la fenêtre contextuelle par rapport à l'icône
});
// Ajouter les barrières à la carte
var barriers = input.getElementsByTagName('barrier');
for (var i = 0; i < barriers.length; i++) {
var lat = barriers[i].getAttribute('lat');
var lon = barriers[i].getAttribute('lon');
var desc = barriers[i].getAttribute('desc');
var newMarker = L.marker([lat, lon], {
draggable: false,
icon: customIcon,
});
newMarker.bindPopup("<p><span style=\"text-decoration: underline;\"><strong>Barrière</strong></span>: " + desc + "</p>");
OSMDataMarkers.addLayer(newMarker);
}
// Ajouter les chemins à la carte en tant que polylignes
var ways = input.getElementsByTagName('way');
for (var i = 0; i < ways.length; i++) {
var waypts = ways[i].getElementsByTagName('waypt');
var coords = [];
for (var j = 0; j < waypts.length; j++) {
var lat = waypts[j].getAttribute('lat');
var lon = waypts[j].getAttribute('lon');
coords.push([lat, lon]);
}
OSMDataMarkers.addLayer(L.polyline(coords, {
color: '#972B14', // Couleur de la ligne
weight: 5, // Épaisseur de la ligne
dashArray: '10, 10' // Alternance de traits rouges et espaces blancs
}));
}
}
//************************************ */
// Google StreetView
function StartStreetview (e) {
let lat = e.latlng.lat.toPrecision(8);
let lon = e.latlng.lng.toPrecision(8);
window.open("https://maps.google.com/maps?q=&layer=c&cbll=" + lat + "," + lon + "&cbp=11,0,0,0", "_blank");
}
//************************************ */
// Routing
//Demo version with OSM Demo servers. Use it for some debugging tasks
/*var routeControl = L.Routing.control({
createMarker: function() { return null; },
lineOptions : { addWaypoints: false,
styles: [{color: 'black', opacity: 0.15, weight: 9}, {color: 'white', opacity: 0.8, weight: 6}, {color: 'blue', opacity: 1, weight: 2}] }
}).addTo(map);
routeControl.getRouter().options.profile = 'foot';
var routeControl = L.Routing.control({
router: L.Routing.graphHopper('939a6776-5fa7-4366-be32-1c53dd09de4f', {
urlParameters: {
vehicle: 'foot'
}
}),
createMarker: function() { return null; },
lineOptions : { addWaypoints: false,
styles: [{color: 'black', opacity: 0.15, weight: 9}, {color: 'white', opacity: 0.8, weight: 6}, {color: 'blue', opacity: 1, weight: 2}] }
}).addTo(map);
routeControl.hide();*/
function AddWaypoint (e, routeCoordsData) {
var iconPath = "";
if(waypoints.length === 0) //premier waypoint
iconPath = "res/pin-icon-start.png";
else
iconPath = "res/pin-icon-end.png";
var customIcon = L.icon({
iconUrl: iconPath, // Chemin de l'image sur le serveur. src: https://icons8.com/icons/set/marker--static
iconSize: [30, 30], // Taille de l'icône [largeur, hauteur]
iconAnchor: [15, 30], // Point d'ancrage de l'icône par rapport à son coin supérieur gauche
popupAnchor: [-3, -30] // Point d'ancrage de la fenêtre contextuelle par rapport à l'icône
});
var newMarker = new L.marker(e.latlng, {
draggable: 'true',
icon: customIcon,
contextmenu: true,
contextmenuItems: [{
text: 'Supprimer point d\'itinéraire',
callback: DeleteWaypoint,
index: 0
}, {
separator: true,
index: 1
}]
}).addTo(markerGroup);
newMarker
.on('dragend', dragEndWaypointHandler);
let lat = e.latlng.lat.toPrecision(8);
let lng = e.latlng.lng.toPrecision(8);
waypoints.push({"ID": newMarker._leaflet_id, "lat": lat, "lng": lng, "LFMarker": newMarker});
//console.log("Waypoint with ID " + newMarker._leaflet_id + " added to array");
if(waypoints.length > 2) //on modifie l'icone du marquer pour qu'il devienne un point à la place du marqueur de fin d'itinéraire
{
customIcon = L.icon({
iconUrl: "res/dot-icon.png", // Chemin de l'image sur le serveur. src: https://icons8.com/icons/set/marker--static
iconSize: [20, 20], // Taille de l'icône [largeur, hauteur]
iconAnchor: [9, 12], // Point d'ancrage de l'icône par rapport à son coin supérieur gauche
});
var SndLastMarker = waypoints[waypoints.length - 2].LFMarker;
SndLastMarker.setIcon(customIcon);
}
if (waypoints.length > 1)
{
if(routeCoordsData !== undefined)
{
routeCoords.push({"WPStartID" : waypoints[waypoints.length - 2].ID, "WPEndID" : waypoints[waypoints.length - 1].ID, "coords" : routeCoordsData.coords, "elevation" : routeCoordsData.elevation, "distance" : routeCoordsData.distance, "road_class" : routeCoordsData.road_class, "surface" : routeCoordsData.surface});
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
}
else
{
var wps = [];
wps.push({"lat" : waypoints[waypoints.length - 2].lat, "lng" : waypoints[waypoints.length - 2].lng});
wps.push({"lat" : waypoints[waypoints.length - 1].lat, "lng" : waypoints[waypoints.length - 1].lng});
GetRouteCoords(wps)
.then(data => {
routeCoords.push({"WPStartID" : waypoints[waypoints.length - 2].ID, "WPEndID" : waypoints[waypoints.length - 1].ID, "coords" : data.points[0].coords, "elevation" : data.points[0].elev, "distance" : data.distance, "road_class" : data.road_class, "surface" : data.surface});
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
//correction de la position du marqueur pour être bien au milieu de la route:
var lastcoordsidx = routeCoords[routeCoords.length - 1].coords.length - 1;
var correctedCoords = routeCoords[routeCoords.length - 1].coords[lastcoordsidx];
newMarker.setLatLng(correctedCoords);
waypoints[waypoints.length - 1] = {"ID": newMarker._leaflet_id, "lat": correctedCoords.lat, "lng": correctedCoords.lng, "LFMarker": newMarker};
})
.catch(error => {
console.error('Erreur:', error);
//markerGroup.removeLayer(e.relatedTarget._leaflet_id);
//waypoints.splice(0, -1);
});
}
}
}
function DeleteWaypoint (e) {
var bLastWaypoint = false;
var bFirstWaypoint = false;
var ID = e.relatedTarget._leaflet_id;
markerGroup.removeLayer(ID);
const WPindex = waypoints.findIndex(p => p.ID == ID);
if(WPindex === 0)
bFirstWaypoint = true;
else if(WPindex === waypoints.length - 1)
bLastWaypoint = true;
waypoints.splice(WPindex, 1);
console.log("Waypoint with ID " + ID + " deleted.");
if(bFirstWaypoint)
{
routeCoords.shift();
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
customIcon = L.icon({
iconUrl: "res/pin-icon-start.png", // Chemin de l'image sur le serveur. src: https://icons8.com/icons/set/marker--static
iconSize: [30, 30], // Taille de l'icône [largeur, hauteur]
iconAnchor: [15, 30], // Point d'ancrage de l'icône par rapport à son coin supérieur gauche
});
waypoints[0].LFMarker.setIcon(customIcon);
}
else if(bLastWaypoint)
{
routeCoords.pop();
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
customIcon = L.icon({
iconUrl: "res/pin-icon-end.png", // Chemin de l'image sur le serveur. src: https://icons8.com/icons/set/marker--static
iconSize: [30, 30], // Taille de l'icône [largeur, hauteur]
iconAnchor: [15, 30], // Point d'ancrage de l'icône par rapport à son coin supérieur gauche
});
waypoints[waypoints.length - 1].LFMarker.setIcon(customIcon);
}
else
{
routeCoords.splice(WPindex, 1); //On supprime la route qui a pour point de départ le waypoint supprimé
if (waypoints.length > 1)
{
var wps = [];
wps.push({"lat" : waypoints[WPindex - 1].lat, "lng" : waypoints[WPindex - 1].lng});
wps.push({"lat" : waypoints[WPindex].lat, "lng" : waypoints[WPindex].lng});
GetRouteCoords(wps)
.then(data => {
routeCoords[WPindex-1] = {"WPStartID" : waypoints[WPindex - 1].ID, "WPEndID" : waypoints[WPindex].ID, "coords" : data.points[0].coords, "elevation" : data.points[0].elev, "distance" : data.distance, "road_class" : data.road_class, "surface" : data.surface};
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
})
.catch(error => {
console.error('Erreur:', error);
//markerGroup.removeLayer(e.relatedTarget._leaflet_id);
//waypoints.splice(0, -1);
});
}
else //Il ne reste plus qu'un marqueur sur la map -> on supprime la route
{
customIcon = L.icon({
iconUrl: "res/pin-icon-start.png", // Chemin de l'image sur le serveur. src: https://icons8.com/icons/set/marker--static
iconSize: [30, 30], // Taille de l'icône [largeur, hauteur]
iconAnchor: [15, 30], // Point d'ancrage de l'icône par rapport à son coin supérieur gauche
});
waypoints[0].LFMarker.setIcon(customIcon);
}
}
}
function dragEndWaypointHandler(e) {
var bLastWaypoint = false;
var bFirstWaypoint = false;
var ID = e.target._leaflet_id;
let lat = e.target._latlng.lat.toPrecision(8);
let lng = e.target._latlng.lng.toPrecision(8);
//console.log("Waypoint with ID " + ID + " dragged");
const WPindex = waypoints.findIndex(p => p.ID == e.target._leaflet_id);
waypoints[WPindex] = {"ID": ID, "lat": lat, "lng": lng, "LFMarker": e.target};
if(WPindex === 0)
bFirstWaypoint = true;
else if(WPindex === waypoints.length - 1)
bLastWaypoint = true;
if (waypoints.length > 1)
{
if(bFirstWaypoint)
{
var wps = [];
wps.push({"lat" : waypoints[WPindex].lat, "lng" : waypoints[WPindex].lng});
wps.push({"lat" : waypoints[WPindex + 1].lat, "lng" : waypoints[WPindex + 1].lng});
GetRouteCoords(wps)
.then(data => {
routeCoords[WPindex] = {"WPStartID" : waypoints[WPindex].ID, "WPEndID" : waypoints[WPindex + 1].ID, "coords" : data.points[0].coords, "elevation" : data.points[0].elev, "distance" : data.distance, "road_class" : data.road_class, "surface" : data.surface};
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
})
.catch(error => {
console.error('Erreur:', error);
//markerGroup.removeLayer(e.relatedTarget._leaflet_id);
//waypoints.splice(0, -1);
});
}
else if(bLastWaypoint)
{
var wps = [];
wps.push({"lat" : waypoints[WPindex - 1].lat, "lng" : waypoints[WPindex - 1].lng});
wps.push({"lat" : waypoints[WPindex].lat, "lng" : waypoints[WPindex].lng});
GetRouteCoords(wps)
.then(data => {
routeCoords[WPindex - 1] = {"WPStartID" : waypoints[WPindex - 1].ID, "WPEndID" : waypoints[WPindex].ID, "coords" : data.points[0].coords, "elevation" : data.points[0].elev, "distance" : data.distance, "road_class" : data.road_class, "surface" : data.surface};
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
})
.catch(error => {
console.error('Erreur:', error);
//markerGroup.removeLayer(e.relatedTarget._leaflet_id);
//waypoints.splice(0, -1);
});
}
else
{
var wps = [];
wps.push({"lat" : waypoints[WPindex - 1].lat, "lng" : waypoints[WPindex - 1].lng});
wps.push({"lat" : waypoints[WPindex].lat, "lng" : waypoints[WPindex].lng});
wps.push({"lat" : waypoints[WPindex + 1].lat, "lng" : waypoints[WPindex + 1].lng});
GetRouteCoords(wps)
.then(data => {
routeCoords[WPindex - 1] = {"WPStartID" : waypoints[WPindex - 1].ID, "WPEndID" : waypoints[WPindex].ID, "coords" : data.points[0].coords, "elevation" : data.points[0].elev, "distance" : data.distance, "road_class" : data.road_class, "surface" : data.surface};
routeCoords[WPindex] = {"WPStartID" : waypoints[WPindex].ID, "WPEndID" : waypoints[WPindex + 1].ID, "coords" : data.points[1].coords, "elevation" : data.points[1].elev, "distance" : data.distance, "road_class" : data.road_class, "surface" : data.surface};
UpdateRoutePolyline(routeCoords);
UpdateDistances(routeCoords);
//correction de la position du marqueur pour être bien au milieu de la route:
var correctedCoords = routeCoords[WPindex].coords[0];
e.target.setLatLng(correctedCoords);
waypoints[WPindex] = {"ID": ID, "lat": correctedCoords.lat, "lng": correctedCoords.lng, "LFMarker": e.target};
})
.catch(error => {
console.error('Erreur:', error);
//markerGroup.removeLayer(e.relatedTarget._leaflet_id);
//waypoints.splice(0, -1);
});
}
}
}
//*************************** */
function AddMarker (e) {
var customIcon = L.icon({
iconUrl: 'res/marker-i-50x50_Bleu.png', // Chemin de l'image sur le serveur. src: https://icons8.com/icons/set/marker--static
iconSize: [30, 30], // Taille de l'icône [largeur, hauteur]
iconAnchor: [15, 30], // Point d'ancrage de l'icône par rapport à son coin supérieur gauche
popupAnchor: [-3, -30] // Point d'ancrage de la fenêtre contextuelle par rapport à l'icône
});
var newMarker = new L.marker(e.latlng, {
draggable: true,
editable: true, // Permet l'édition de texte sur clic
icon: customIcon,
contextmenu: true,
contextmenuItems: [{
text: 'Supprimer marqueur',
callback: DeleteMarker,
index: 0
}, {
separator: true,
index: 1
}]
}).addTo(markerGroup);
newMarker
.on('dragend', dragEndMarkerHandler);
let lat = e.latlng.lat.toPrecision(8);
let lng = e.latlng.lng.toPrecision(8);
markers.push({"ID": newMarker._leaflet_id, "lat": e.latlng.lat, "lng": e.latlng.lng});
//console.log("Marker added. Markers array updated. ID: " + newMarker._leaflet_id + ", Lat: " + e.latlng.lat + ", Long: " + e.latlng.lng);
}
function DeleteMarker (e) {
//console.log("Marker deleted. ID: " + e.relatedTarget._leaflet_id + ", Lat: " + e.relatedTarget._latlng.lat + ", Long: " + e.relatedTarget._latlng.lat);
markerGroup.removeLayer(e.relatedTarget._leaflet_id);
const index = markers.findIndex(p => p.ID == e.relatedTarget._leaflet_id);
markers.splice(index, 1);
}
function dragEndMarkerHandler(e) {
//console.log("Draging of marker ended. ID is " + e.target._leaflet_id + ". New position is " + e.target._latlng.lat + "," + e.target._latlng.lng);
const index = markers.findIndex(p => p.ID == e.target._leaflet_id);
markers[index] = {"ID": e.target._leaflet_id, "lat": e.target._latlng.lat, "lng": e.target._latlng.lng};
//console.log("Markers array updated");
}
//*************************************/
//Implementation Routing Perso GraphHoper
function UpdateRoutePolyline(coordinates)
{
var coords = [];
for(var i = 0; i < coordinates.length; i++)
coords.push(coordinates[i].coords);
if (routePolyline !== null)
{
routePolyline.removeFrom(map);
routePolyline = null;
}
routePolyline = L.polyline(coords, {color: 'blue', opacity: 1, weight: 2}).addTo(map);
}
function GetRouteCoords(wps)
{
if(wps.lengh > 5)
{
alert("There are more than 5 waypoints. This is not acceptable for GraphHoper")
exit;
}
const apiKey = "939a6776-5fa7-4366-be32-1c53dd09de4f";
locs = [];
for(i = 0; i < wps.length; i++)
{
locs.push('point=' + wps[i].lat + ',' + wps[i].lng);;
}
var points = locs.join('&');
const apiUrl = `https://graphhopper.com/api/1/route?${points}&profile=${routingProfile}&key=${apiKey}&instructions=false&elevation=true&details=road_class&details=surface`;
//console.log(apiUrl);
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", apiUrl, true);
// Onload is called when response is fully loaded
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
const response = JSON.parse(xhr.responseText);
var RemainingCredits = xhr.getResponseHeader('X-RateLimit-Remaining');
var Cost = xhr.getResponseHeader('X-RateLimit-Credits');
//console.log('Crédits restants : ' + RemainingCredits);
//const coordinatesOld = DecodePolyline(response.paths[0].points); //Il ne devrait y avoir qu'un seul path dans la réponse!
const coordinates = DecodePath(response.paths[0].points, true); //Il ne devrait y avoir qu'un seul path dans la réponse!
//const snappedwpsOld = DecodePolyline(response.paths[0].snapped_waypoints);
const snappedwps = DecodePath(response.paths[0].snapped_waypoints, true);
var res = [];
var idx = 0;
var previdx = 0;
var found = false;
for(i = 0; i < snappedwps[0].length - 1; i++)
{
for(j = 0; j < coordinates[0].length; j++)
{
if(snappedwps[0][i+1].lat === coordinates[0][j].lat && snappedwps[0][i+1].lng === coordinates[0][j].lng)
{
idx = j;
found = true;
break;
}
}
if(found === false)
reject("Snapped waypoint non trouvé dans le tableau coordinates");
res.push({"coords" : coordinates[0].slice(previdx, idx + 1), "elev" : coordinates[1].slice(previdx, idx + 1)});
previdx = idx;
}
console.log(response.paths[0].details.road_class[0][2] + ", " + response.paths[0].details.surface[0][2]);
resolve({"points" : res, "distance" : response.paths[0].distance, "road_class" : response.paths[0].details.road_class[0][2], "surface" : response.paths[0].details.surface[0][2]});
} else
reject('Erreur lors de la requête:', xhr.statusText);
};