-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrouting.js
More file actions
1521 lines (1370 loc) · 55.6 KB
/
Copy pathrouting.js
File metadata and controls
1521 lines (1370 loc) · 55.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*===========================================================================*/
// Routing in North America
// Sample map by ThinkGeo
//
// 1. ThinkGeo Cloud API Key
// 2. Map Control Setup
// 3. ThinkGeo Map Icon Fonts
// 4. Routing Setup
// 5. Routing Features Handler Setup
// 6. Result Rendering
// 7. Error Event Handlers
// 8. UI control setup
// 9. Derive the Custom Class Drag
// 10. Event Listeners
/*===========================================================================*/
/*---------------------------------------------*/
// 1. ThinkGeo Cloud API Key
/*---------------------------------------------*/
// First, let's define our ThinkGeo Cloud API key, which we'll use to
// authenticate our requests to the ThinkGeo Cloud API. Each API key can be
// restricted for use only from a given web domain or IP address. To create your
// own API key, you'll need to sign up for a ThinkGeo Cloud account at
// https://cloud.thinkgeo.com.
const apiKey = 'WPLmkj3P39OPectosnM1jRgDixwlti71l8KYxyfP2P0~';
/*---------------------------------------------*/
// 2. Map Control Setup
/*---------------------------------------------*/
// Here's where we set up our map. We're going to create layers, styles,
// and define our initial view when the page first loads.
// In this custom object, we're going to define eight styles:
// 1. The appearance of the start point icon.
// 2. The appearance of the end point icon.
// 3. The appearance of the waypoint icon.
// 4. The appearance of the route line.
// 5. The appearance of the route line halo.
// 6. The appearance of the line of start point to snap point.
// 7. The appearance of the radius circle when hovering the segment route.
// 8. The appearance of the arrow when clicking the target segment route.
const styles = {
start: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.9],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
opacity: 1,
crossOrigin: 'Anonymous',
src: '../image/starting.png'
})
}),
end: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.9],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
opacity: 1,
crossOrigin: 'Anonymous',
src: '../image/ending.png'
})
}),
mid: new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
fill: new ol.style.Fill({
color: [255, 255, 255, 19]
}),
stroke: new ol.style.Stroke({
color: [29, 93, 48, 1],
width: 6
})
})
}),
line: new ol.style.Style({
stroke: new ol.style.Stroke({
width: 6,
color: [34, 109, 214, 0.9]
})
}),
line_halo: new ol.style.Style({
stroke: new ol.style.Stroke({
width: 10,
lineCap: 'round',
color: [34, 109, 214, 1]
})
}),
walkLine: new ol.style.Style({
stroke: new ol.style.Stroke({
width: 2,
lineDash: [5, 3],
color: [34, 109, 214, 1]
})
}),
resultRadius: new ol.style.Style({
image: new ol.style.Circle({
radius: 15,
fill: new ol.style.Fill({
color: [255, 102, 0, 0.4]
}),
stroke: new ol.style.Stroke({
color: [255, 102, 0, 0.8],
width: 1
})
})
}),
arrowLine: new ol.style.Style({
stroke: new ol.style.Stroke({
color: [10, 80, 18, 1],
width: 6
})
})
};
// Now we'll create the base layer for our map. The base layer uses the ThinkGeo
// Cloud Maps Vector Tile service to display a detailed street map. For more
// info, see our wiki:
// https://wiki.thinkgeo.com/wiki/thinkgeo_cloud_maps_vector_tiles
const lightLayer = new ol.mapsuite.VectorTileLayer('https://cdn.thinkgeo.com/worldstreets-styles/3.0.0/light.json', {
apiKey: apiKey,
layerName: 'light'
});
// Create a default view for the map when it starts up.
const view = new ol.View({
// Center the map on the United States and start at zoom level 3.
center: ol.proj.fromLonLat([-96.7962, 42.79423]),
maxResolution: 40075016.68557849 / 512,
progressiveZoom: false,
zoom: 3,
minZoom: 2,
maxZoom: 19
});
// This function will create and initialize our interactive map.
// We'll call it later when our POI icon font has been fully downloaded,
// which ensures that the POI icons display as intended.
let map;
let vectorSource;
let curCoord;
// Define a name space: app.
let app = {};
const initializeMap = () => {
map = new ol.Map({
renderer: 'webgl',
loadTilesWhileAnimating: true,
loadTilesWhileInteracting: true,
// Add our previously-defined ThinkGeo Cloud Vector Tile layer to the map.
layers: [lightLayer],
// States that the HTML tag with id="map" should serve as the container for our map.
target: 'map',
view: view,
// Add an interaction to map that allows drag point icons.
interactions: ol.interaction.defaults().extend([new app.Drag()])
});
addRoutingLayer();
mobileCompatibility();
// Add a "pointermove" listener to map which is when the pointer is moving over the start, end and mid point, the cursor should be "pointer" appearance.
map.on('pointermove', function (e) {
if (e.dragging) {
return;
}
const pixel = map.getEventPixel(e.originalEvent);
const options = {
// Only find feature on the routing layer not the base vector tile layer.
layerFilter: function (layer) {
if (layer instanceof ol.layer.VectorTile) {
return false;
}
return true;
}
};
const hit = map.hasFeatureAtPixel(pixel, options);
let cursor = false;
if (hit) {
const features = map.getFeaturesAtPixel(pixel, options);
features.some((feature) => {
let featureName = feature.get('name');
if (featureName === 'start' || featureName === 'end' || featureName === 'mid') {
cursor = true;
return true;
}
});
} else {
cursor = false;
}
map.getTargetElement().style.cursor = cursor ? 'pointer' : '';
});
};
// Do some compatibility on mible and IOS client.
const mobileCompatibility = () => {
let u = navigator.userAgent;
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
let left, top;
let clientWidth = document.documentElement.clientWidth;
let clientHeight = document.documentElement.clientHeight;
const contextmenu = document.querySelector('#ol-contextmenu');
const insTip = document.querySelector('#instruction-tip');
let timeOutEvent;
const contextWidth = 165;
const contextHeight = 127;
// Show the right click context menu on different platform.
if (isiOS) {
map.getViewport().addEventListener('gesturestart', function (e) {
clearTimeout(timeOutEvent);
timeOutEvent = 0;
return false;
});
map.getViewport().addEventListener('touchstart', function (e) {
e.preventDefault();
if (e.touches.length != 1) {
clearTimeout(timeOutEvent);
timeOutEvent = 0;
return false;
}
timeOutEvent = setTimeout(function () {
if (e.touches.length == 1) {
timeOutEvent = 0;
left =
e.changedTouches[0].clientX + contextWidth > clientWidth ?
clientWidth - contextWidth - 3 :
e.changedTouches[0].clientX;
top =
e.changedTouches[0].clientY + contextHeight > clientHeight ?
clientHeight - contextHeight - 13 :
e.changedTouches[0].clientY;
contextmenu.style.left = left + 'px';
contextmenu.style.top = top + 'px';
let point = map.getEventCoordinate(e);
curCoord = point;
hideOrShowContextMenu('show');
insTip.classList.add('gone');
}
}, 500);
});
map.getViewport().addEventListener('touchend', function (event) {
clearTimeout(timeOutEvent);
if (timeOutEvent != 0) {
hideOrShowContextMenu('hide');
}
return false;
});
map.getViewport().addEventListener('touchmove', function (event) {
clearTimeout(timeOutEvent);
timeOutEvent = 0;
return false;
});
} else {
map.getViewport().addEventListener('contextmenu', (e) => {
hideOrShowContextMenu('show');
insTip.classList.add('gone');
left = e.clientX + contextWidth > clientWidth ? clientWidth - contextWidth - 3 : e.clientX;
top =
e.clientY + contextmenu.offsetHeight > clientHeight ?
clientHeight - contextmenu.offsetHeight - 1 :
e.clientY;
contextmenu.style.left = left + 'px';
contextmenu.style.top = top + 'px';
let point = map.getEventCoordinate(e);
curCoord = point;
});
}
// Show the mobile instruction tip on Android and IOS, and show pc tip on PC.
if (isiOS || isAndroid) {
document.querySelector('.mobile-tip').classList.remove('hide');
} else {
document.querySelector('.pc-tip').classList.remove('hide');
}
};
// Create the routing layer and add it to map.
const addRoutingLayer = () => {
vectorSource = new ol.source.Vector();
let routingLayer = new ol.layer.Vector({
source: vectorSource,
layerName: 'routing'
});
map.addLayer(routingLayer);
};
/*---------------------------------------------*/
// 3. ThinkGeo Map Icon Fonts
/*---------------------------------------------*/
// Finally, we'll load the Map Icon Fonts using ThinkGeo's WebFont loader.
// The loaded Icon Fonts will be used to render POI icons on top of the map's
// background layer. We'll initalize the map only once the font has been
// downloaded. For more info, see our wiki:
// https://wiki.thinkgeo.com/wiki/thinkgeo_iconfonts
WebFont.load({
custom: {
families: ['vectormap-icons'],
urls: ['https://cdn.thinkgeo.com/vectormap-icons/2.0.0/vectormap-icons.css'],
testStrings: {
'vectormap-icons': '\ue001'
}
},
// The "active" property defines a function to call when the font has
// finished downloading. Here, we'll call our initializeMap method.
active: initializeMap
});
/*---------------------------------------------*/
// 4. Routing Setup
/*---------------------------------------------*/
// At this point we'll built up the methods and functionality that will
// actually perform the routing using the ThinkGeo Cloud and then
// display the results on the map.
// We use thinkgeocloudclient.js, which is an open-source Javascript SDK for making
// request to ThinkGeo Cloud Service. It simplifies the process of the code of request.
// We need to create the instance of Routing client and authenticate the API key.
const routingClient = new tg.RoutingClient(apiKey);
// Get some items which we'll use to judge if we should perform the routing service or show error tips.
const findRoute = (showError, notClearAll) => {
if (!notClearAll) {
vectorSource.clear();
}
hideOrShowResultBox('hide');
const points = getAllPoints();
const inputsCount = document.querySelectorAll('.point input');
if (points && points.length >= 2 && inputsCount.length === points.length) {
// Add the point which is not added to map.
const pointsLength = points.length;
points.forEach((point, index) => {
if (pointsLength - 1 === index) {
type = 'end';
} else if (0 === index) {
type = 'start';
} else {
type = 'mid';
}
addPointFeature(type, point);
});
performRouting();
} else if (showError) {
showErrorTip('Please input correct coordinates!');
}
};
// This method performs the actual routing using the ThinkGeo Cloud.
// By passing the coordinates of the map location, we can
// get back a the route message as we send the request. For more details, see our wiki:
// https://wiki.thinkgeo.com/wiki/thinkgeo_cloud_routing
const performRouting = () => {
const points = getAllPoints();
const inputsCount = document.querySelectorAll('.point input');
if (points && points.length >= 2 && inputsCount.length === points.length) {
hideErrorTip();
document.querySelector('.loading').classList.remove('hide');
const options = {
turnByTurn: true,
srid: 3857
};
const callback = (status, response) => {
const result = document.querySelector('#result');
if (status === 200) {
result.classList.remove('error-on-mobile');
document.querySelector('.loading').classList.add('hide');
hideOrShowResultBox('show');
handleResponse(response);
} else {
hideOrShowResultBox('show');
document.querySelector('.loading').classList.add('hide');
document.querySelector('#total').innerHTML = '';
if (document.body.clientWidth <= 767) {
result.classList.add('error-on-mobile');
}
if (status === 400) {
const data = response.data;
let message = '';
Object.keys(data).forEach((key) => {
message = message + data[key] + '<br />';
});
result.querySelector('#boxes').innerHTML = `<div class="error-message">${message}</div>`;
} else if (status === 401 || status === 410 || status === 404) {
result.querySelector('#boxes').innerHTML = `<div class="error-message">${response.error
.message}</div>`;
} else if (status === 'error') {
errorLoadingTile();
} else {
result.querySelector('#boxes').innerHTML = `<div class="error-message">Request failed.</div>`;
}
}
};
const points_ = points.map((point) => {
return {
x: point[0],
y: point[1]
};
});
routingClient.getRoute(points_, callback, options);
}
};
// Handle the response when we get the route result from server.
const handleResponse = (res) => {
const data = res.data;
const routes = data.routes[0];
generateBox(routes);
const waypointsCoord = data.waypoints.map(item => [item.coordinate.x, item.coordinate.y]);
addWalkLinesFeatures(waypointsCoord);
};
// Get the coordinates array from the input attribute -- data-origin.
const getCoordFromDataOrigin = (dataOriginValue) => {
let value = dataOriginValue.split(',');
if (value.length === 2) {
return [Number(value[0]), Number(value[1])];
} else {
return [];
}
};
// Get all the input points coordinates from the input group.
const getAllPoints = () => {
let points = [];
const allInputs = document.querySelectorAll('.point input');
allInputs.forEach((input) => {
const value = input.getAttribute('data-origin');
value ? points.push(getCoordFromDataOrigin(value)) : null;
});
return points;
};
/*---------------------------------------------*/
// 5. Routing Features Handler Setup
/*---------------------------------------------*/
// This step we create several method for you to operate the features on the routing layer.
// Since all the preparation have been done, we need to do have some method to handle the
// features we have added to the map.
// Add point feature to map by passing the point name and coordinates.
const addPointFeature = (name, coord) => {
if (name === 'start') {
removeFeatureByName(name);
} else if (name === 'end') {
removeFeatureByName(name);
}
let feature = new ol.Feature({
geometry: new ol.geom.Point(coord),
name: name
});
feature.setStyle(styles[name]);
vectorSource.addFeatures([feature]);
};
// Add the route line feature by passing the line wkt data from what we get from response.
const addRouteFeature = (wkt) => {
const format = new ol.format.WKT();
const routeFeature = format.readFeature(wkt);
routeFeature.set('name', 'line');
routeFeature.setStyle([styles.line, styles.line_halo]);
vectorSource.addFeature(routeFeature);
};
// Add the lines from the point we start from to the nearest route.
const addWalkLinesFeatures = (waypointsCoord) => {
let features = [];
const points = getAllPoints();
points.forEach((point, index) => {
const feature = new ol.Feature({
geometry: new ol.geom.LineString([point, waypointsCoord[index]]),
name: 'line'
});
features.push(feature);
});
vectorSource.addFeatures(features);
};
// Add a radius circle the segment point where we hovering from.
const addResultRadius = (coord) => {
removeFeatureByName('resultRadius');
let center = coord;
let resultRadiusFeature = new ol.Feature({
geometry: new ol.geom.Point(center),
name: 'resultRadius'
});
resultRadiusFeature.setStyle(styles.resultRadius);
vectorSource.addFeature(resultRadiusFeature);
};
// Add the arrow icon when we zoom in to which segment route we click.
const addArrow = (penultCoord, lastCoord) => {
removeFeatureByName('arrow');
let feature = new ol.Feature({
geometry: new ol.geom.Point(lastCoord),
name: 'arrow'
});
const dx = lastCoord[0] - penultCoord[0];
const dy = lastCoord[1] - penultCoord[1];
const rotation = Math.atan2(dy, dx);
const arrowStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
crossOrigin: 'Anonymous',
src: '../image/arrow.png',
rotateWithView: true,
rotation: -rotation
})
});
feature.setStyle(arrowStyle);
vectorSource.addFeature(feature);
};
// Add the arrow line when we zoom in to which segment route we click.
const addTurnLine = (penultCoord, lastCoord, lineSecondCoord) => {
let feature = new ol.Feature({
geometry: new ol.geom.LineString([penultCoord, lastCoord, lineSecondCoord]),
name: 'line'
});
feature.setStyle(styles.arrowLine);
vectorSource.addFeature(feature);
};
// Remove a point feature by passing the coordinates.
const removeFeatureByCoord = (coord) => {
const features = vectorSource.getFeatures();
features.some((feature) => {
if (feature.getGeometry().getCoordinates().toString() === coord) {
vectorSource.removeFeature(feature);
return true;
}
});
};
// Remove the point or line features by passing the feature name.
const removeFeatureByName = (featureName) => {
if (vectorSource) {
const features = vectorSource.getFeatures();
for (let i = 0, l = features.length; i < l; i++) {
let feature = features[i];
if (feature.get('name') === featureName) {
vectorSource.removeFeature(feature);
}
}
}
};
// Get the feature by feature's name.
const getFeatureByName = (name) => {
let feature_;
vectorSource.getFeatures().some((feature) => {
if (feature.get('name') === name) {
feature_ = feature;
return true;
}
});
return feature_;
};
/*---------------------------------------------*/
// 6. Result Rendering
/*---------------------------------------------*/
// Since all we have got the result from server, we need to show the result in the left sidebar box.
// Calculate the coordinates what we use to draw the arrow lines by passing the two coordinates.
const lerp = (firstCoord, secondCoord) => {
var resolution = view.getResolution();
var x1 = firstCoord[0];
var y1 = firstCoord[1];
var x2 = secondCoord[0];
var y2 = secondCoord[1];
var length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) / resolution;
var x, y;
if (length > 50) {
var interpolate = 50 / length;
var x = ol.math.lerp(x1, x2, interpolate);
var y = ol.math.lerp(y1, y2, interpolate);
return [x, y];
}
return secondCoord;
};
// Format the distance and duration data from what we get from response.
const formatDistanceAndDuration = (distance, duration) => {
let distance_;
let duration_;
if (distance >= 1000) {
distance_ = distance / 1000;
distance_ = Math.round(distance_ * 10) / 10;
distance_ = new Intl.NumberFormat().format(distance_);
distance_ = distance_ + 'km';
} else {
distance_ = Math.round(distance * 10) / 10;
distance_ = distance_ + 'm';
}
if (duration > 60) {
let hours = parseInt(duration / 60);
let min = Math.round(duration % 60);
hours = new Intl.NumberFormat().format(hours);
duration_ = `${hours}h ${min}min`;
} else {
duration_ = Math.round(duration * 10) / 10;
duration_ = `${duration_}min`;
}
return {
distance: distance_,
duration: duration_
};
};
// Create the sidebar result container and inner items once we have got the response from server.
const generateBox = (routes) => {
let lastLinePoint;
let firstLinePoint;
const lineWkt = routes.geometry;
let segments = routes.segments;
let count = 0;
let distance = Math.round(routes.distance * 100) / 100;
let duration = Math.round(routes.duration * 100) / 100;
let format = formatDistanceAndDuration(distance, duration);
let warnings;
if (routes.warnings) {
let str = ``;
Object.keys(routes.warnings).map((key) => {
str += `${routes.warnings[key]} `;
});
warnings = `<p class="warnings">${str} </p> `;
} else {
warnings = '';
}
let boxesDom = document.querySelector('#boxes');
let totalDom = document.querySelector('#total');
let total = `<span class='format-distance'>${format.distance}</span>
<span class='format-duration'>${format.duration}</span>
${warnings}
<button id='menu'></button>
<button id='closeMenu'></button>
`;
totalDom.innerHTML = total;
boxesDom.innerHTML = '';
addRouteFeature(lineWkt);
let lastLinePenultCoord = [];
let lastLineLastCoord = [];
let isTurn = true;
let polylineCoords = [];
if (segments) {
let segments_ = segments
.map((item) => {
let polyline = item.geometry;
let polylineCoord = polyline.split('(')[1].split(')')[0].split(',');
let secondPointFromStart = findSecondPointFromStart(polylineCoord);
return secondPointFromStart ? item : false;
})
.filter((item) => item);
segments_.forEach((item) => {
count++;
let polyline = item.geometry;
let polylineCoord = polyline.split('(')[1].split(')')[0].split(',');
let secondPointFromStart = findSecondPointFromStart(polylineCoord);
let secondPointFromEnd = findSecondPointFromEnd(polylineCoord);
let startCoord = polylineCoord[0];
polylineCoords.push(polylineCoord);
let instruction = item.instruction;
const maneuverType = item.maneuverType;
let format = formatDistanceAndDuration(item.distance, item.duration);
distance = format.distance;
duration = format.duration;
let className;
let warnStr;
if (item.isToll) {
warnStr = '<span class="warnings-small ">Toll road</span>';
} else {
warnStr = '';
}
isTurn = true;
switch (maneuverType) {
case 'turn-left':
className = `left`;
break;
case 'sharp-left':
className = `sharp_left`;
break;
case 'slightly-left':
className = `slight_left`;
break;
case 'turn-right':
className = `right`;
break;
case 'sharp-right':
className = `sharp_right`;
break;
case 'slightly-right':
className = `slight_right`;
break;
case 'straight-on':
className = `straight_on`;
isTurn = false;
break;
case 'u-turn':
className = `turn-back`;
break;
case 'start':
className = `start`;
isTurn = false;
break;
case 'stop':
className = `end`;
isTurn = false;
break;
case 'roundabout':
className = `around_circle_straight`;
break;
}
let boxInnerDom =
count !== segments_.length ?
`<span class="direction-wrap" ><i class="direction ${className}"></i></span><span title='${instruction}' class="instruction">${instruction}</span>
<span class="distance">${distance}</span><span class="duration">${duration}</span>${warnStr}` :
`<span class="direction-wrap" ><i class="direction ${className}"></i></span><span class="instruction endPoint">${instruction}</span>`;
let boxDom = document.createElement('DIV');
boxDom.className = 'box';
boxDom.id = count;
if (count === 1) {
firstLinePoint = startCoord.split(' ');
firstLinePoint = [+firstLinePoint[0], +firstLinePoint[1]];
let penult = secondPointFromEnd;
penultPoint = penult.split(' ');
penultPoint = [+penultPoint[0], +penultPoint[1]];
let last = polylineCoord[polylineCoord.length - 1];
lastPoint = last.split(' ');
lastPoint = [+lastPoint[0], +lastPoint[1]];
lastLinePenultCoord = penult;
lastLineLastCoord = last;
let penult_ = polylineCoord[0];
penult_ = penult_.split(' ');
let last_ = polylineCoord[1];
let lastPoint_ = last_.split(' ');
lastPoint_ = [+lastPoint_[0], +lastPoint_[1]];
}
if (count === segments_.length) {
let endCoord = polylineCoord[polylineCoord.length - 1];
lastLinePoint = endCoord.split(' ');
lastLinePoint = [+lastLinePoint[0], +lastLinePoint[1]];
boxDom.setAttribute('coord', endCoord);
} else {
boxDom.setAttribute('coord', startCoord);
}
if (count >= 2) {
boxDom.setAttribute('lastLinePenultCoord', lastLinePenultCoord);
boxDom.setAttribute('lastLineLastCoord', lastLineLastCoord);
isTurn && boxDom.setAttribute('lineSecondCoord', secondPointFromStart);
let penult = secondPointFromEnd;
penultPoint = penult.split(' ');
penultPoint = [+penultPoint[0], +penultPoint[1]];
let last = polylineCoord[polylineCoord.length - 1];
lastPoint = last.split(' ');
lastPoint = [+lastPoint[0], +lastPoint[1]];
lastLinePenultCoord = penult;
lastLineLastCoord = last;
}
boxDom.setAttribute('instruction', instruction);
boxDom.innerHTML = boxInnerDom;
boxesDom.appendChild(boxDom);
});
} else {
// The two points are too close to find the route, so there are no segments. We need to add start point and end point in the result box.
let boxInnerDomStart = `<span class="direction-wrap" ><i class="direction start"></i></span><span title="Start" class="instruction">Start</span>
<span class="distance">0 km</span><span class="duration">0 min</span>`;
let boxInnerDomEnd = `<span class="direction-wrap" ><i class="direction end"></i></span><span title="End" class="instruction">End</span>
<span class="distance">0 km</span><span class="duration">0 min</span>`;
let boxDomStart = document.createElement('DIV');
let boxDomEnd = document.createElement('DIV');
boxDomStart.className = 'box';
boxDomEnd.className = 'box';
boxDomStart.innerHTML = boxInnerDomStart;
boxDomEnd.innerHTML = boxInnerDomEnd;
boxDomStart.setAttribute('coord', getAllPoints()[0].join(' '));
boxDomEnd.setAttribute('coord', getAllPoints()[getAllPoints().length - 1].join(' '));
boxesDom.appendChild(boxDomStart);
boxesDom.appendChild(boxDomEnd);
}
if (document.body.clientWidth <= 767) {
const result = document.getElementById('result');
result.style.height = 36 + 'px';
const menu = document.getElementById('menu');
const closeMenu = document.getElementById('closeMenu');
menu.addEventListener('click', () => {
result.style.height = 240 + 'px';
result.style.overflowY = 'auto';
menu.style.display = 'none';
closeMenu.style.display = 'inline-block';
});
closeMenu.addEventListener('click', () => {
result.style.height = 36 + 'px';
result.style.overflow = 'hidden';
closeMenu.style.display = 'none';
menu.style.display = 'inline-block';
});
}
};
// In order to draw the arrow or arrow line on the turn point, we need to find the points what we need.
const findSecondPointFromStart = (coordinates) => {
for (let i = 0; i < coordinates.length - 1; i++) {
if (coordinates[i + 1] != coordinates[i]) {
return coordinates[i + 1];
}
}
return false;
};
const findSecondPointFromEnd = (coordinates) => {
for (let i = coordinates.length - 1; i > 0; i--) {
if (coordinates[i - 1] != coordinates[i]) {
return coordinates[i - 1];
}
}
return false;
};
/*---------------------------------------------*/
// 7. Error Event Handlers
/*---------------------------------------------*/
// These events allow you to perform custom actions when
// a map tile encounters an error while loading.
const errorLoadingTile = () => {
const errorModal = document.querySelector('#error-modal');
if (errorModal.classList.contains('hide')) {
// Show the error tips when Tile loaded error.
errorModal.classList.remove('hide');
}
};
const setLayerSourceEventHandlers = (layer) => {
let layerSource = layer.getSource();
layerSource.on('tileloaderror', function () {
errorLoadingTile();
});
};
setLayerSourceEventHandlers(lightLayer);
// When you are ready to perform a routing request, but some input boxes are empty. Then we'll show the
// input error tip, after 3000ms, we'l hide the error tip automatically.
let timer;
const showErrorTip = (content) => {
if (timer) {
clearTimeout(timer);
}
const tip = document.querySelector('#input-error');
tip.querySelector('p').innerHTML = content;
tip.classList.add('show');
timer = setTimeout(function () {
tip.classList.remove('show');
}, 3000);
};
const hideErrorTip = () => {
document.querySelector('#input-error').classList.remove('show');
};
/*---------------------------------------------*/
// 8. UI control setup
/*---------------------------------------------*/
// Get the last node from a collection nodes by passing the DOM selector.
const getLastNodeBySelector = (selector) => {
const inputs = document.querySelectorAll(selector);
return inputs[inputs.length - 1];
};
// When we click the clear item in the context menu, we'll mak all the input empty using this method.
const clearInputBox = () => {
const inputs = document.querySelectorAll('.point input');
inputs.forEach((input) => {
input.setAttribute('data-origin', '');
input.value = '';
});
};
// When there are results, show the result box, otherwise, hide the result box.
const hideOrShowResultBox = (visible) => {
const sidebar = document.querySelector('.sidebar');
if (visible === 'show') {
sidebar.classList.remove('empty');
resetSidebarHeight();
} else {
sidebar.classList.add('empty');
}
}
// Since add or delete the input box, the result box height will automatically
// change. Here, we use this method to refresh the result sidebar height.
const resetSidebarHeight = () => {
const resultSidebar = document.querySelector('.sidebar');
const topHeight = document.querySelector('.point').clientHeight + 30;
resultSidebar.style.top = `${topHeight}px`;
};
// When click the add point button or the item of add route in the context menu,
// we'll add an input box in the sidebar input group.
const addInputBox = (coord, readonly) => {
const inputs = document.querySelectorAll('#dragable-list input');
if (inputs.length === 10) {
showErrorTip('No more than 10 points.');
return;
}
removeFeatureByName('line');
removeFeatureByName('arrow');
hideOrShowResultBox('hide');
const lastPoint = getLastNodeBySelector('#dragable-list li');
const lastInput = lastPoint.querySelector('input');
const parent = document.querySelector('#dragable-list');
const newNode = document.createElement('li');
newNode.classList.add('via');
let dataOrigin;
let inputValue;
if (coord) {
dataOrigin = coord;
let coord_ = new ol.proj.toLonLat(coord);
inputValue = [coord_[1].toFixed(8), coord_[0].toFixed(8)];
} else {
dataOrigin = lastInput.getAttribute('data-origin');
inputValue = lastInput.value;
lastInput.value = '';
lastInput.setAttribute('data-origin', '');
}
let attr = '';
if(readonly){
attr = 'readonly';
}
newNode.innerHTML = `
<i class="drag"></i><label></label>
<input value="${inputValue}" data-origin="${dataOrigin}" placeholder="To" ${attr}/>
<span class=""></span>
<a class="closer"></a>`;
parent.insertBefore(newNode, lastPoint);
};
// Hide or show the context menu when we click or right click the map.
const hideOrShowContextMenu = (style) => {
let contextmenu = document.querySelector('#ol-contextmenu');
switch (style) {
case 'hide':
contextmenu.classList.add('hide');
break;
case 'show':