forked from milkboy/WME-ja
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWME-Junction-Angle-Info.js
More file actions
6256 lines (5729 loc) · 301 KB
/
Copy pathWME-Junction-Angle-Info.js
File metadata and controls
6256 lines (5729 loc) · 301 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
// ==UserScript==
// @name WME Junction Angle Info
// @description Show the angle between two connected (or selected) segments — experimental branch adding Junction Box and Path (far turn) support
// @namespace https://greasyfork.org/en/users/166843-wazedev
// @match *://*.waze.com/*editor*
// @exclude *://*.waze.com/user/editor*
// @exclude *://*.waze.com/editor/sdk/*
// @version 3.3.1
// @grant GM_xmlhttpRequest
// @grant GM_info
// @connect greasyfork.org
// @namespace https://greasyfork.org/scripts/35547-wme-junction-angle-info/
// @require https://greasyfork.org/scripts/24851-wazewrap/code/WazeWrap.js
// @require https://update.greasyfork.org/scripts/509664/WME%20Utils%20-%20Bootstrap.js
// @require https://cdn.jsdelivr.net/npm/@turf/turf@7/turf.min.js
// @author WazeDev / JS55CT
// @copyright 2026 JS55CT, 2018 seb-d59, 2016 Michael Wikberg <waze@wikberg.fi>
// @license CC-BY-NC-SA
// @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAA6pSURBVFhHrZkJcBNnlscbgjEZmHAYsHVZUrek7pbUuo9W674l65Z8WzbGxoAxhzNgcweMDeY0GLDHwYBhGCABTEwIOSaTZBIyye6mcjBJFTs7O5Xazc4ks7NbU7vJzjKVrc0+RVqwhWEC5NW/VFKr3//79fe+fv3JRrp2bjs00NfW3gqqSldojCqFVk4q8LK4z+a2kEosVRVIVnrL60KMU602SfnaohIaQR0zb/72428eNr7+n6/r14bBh2+ahaJCDMOcWk9ndOuFFdeQlrbF4USZ0aqlNDJKS8YrovXNNSa7PlEVSTdVK3REMGIDcbEiuU5c3hDhmgvA6PV3X8p5P2x89ecv6XIRWCX94bFVP//l+l9lhYikpTB8MOauW1y1pqN13ab26oZkrCLo9JuBZj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Wo+/1nZjh/f/hnEYx5Xe2Wxplh0ScyWsDqrXDKb1BA2OssdCo8yvCjkrw8kWxKhxWFr3GKvcNiTNpyWSA0EocEVeoWOMSi1GiReWRZJuGMpL+PQ+WMud8ihcxikeopDlPINJRxmenYwFjNNEpGr4NKXNYKoKoeoLPO/nNy3xqliMwvXYzILCSjQ9OQuiombKbcC2gzw0VET0AQXlbmq3fCtrdwOQJak1ZFyiFQoV8LhYlyUEKES8f8BmIA7Ka4NUW4AAAAASUVORK5CYII=
// ==/UserScript==
/**
* Copyright 2016 Michael Wikberg <waze@wikberg.fi>
* WME Junction Angle Info extension is licensed under a Creative Commons
* Attribution-NonCommercial-ShareAlike 3.0 Unported License.
* See README.md for full contributor history.
*
* Original author:
* 2013–2019 Michael Wikberg "milkboy" <waze@wikberg.fi>
* Core logic, architecture, Swedish & Finnish translations
*
* Contributions by:
* 2014 Paweł Pyrczak "tkr85" WME update compatibility fixes
* 2014 "AlanOfTheBerg" WME update compatibility fixes
* 2014 "berestovskyy" WME update compatibility fixes
* 2015 "FZ69617" Best-continuation (BC) logic fixes
* 2015 "wlodek76" Contributions
* 2016 Sergey Kuznetsov "WazeRus" Russian translation
* 2016 "MajkiiTelini" Czech translation
* 2016 "witoco" Latin-American Spanish translation
* 2017 "seb-d59" French translation; override instruction detection
* 2019 "Sapozhnik" Ukrainian translation
* "ccclxv" British English (UK) translation
* 2024 "g1220k" Contributions
* 2026 "JS55CT" V3.0.0 Current maintainer; SDK migration,
* V3.1.0 - 3.1.5 RoundAbout support, JB and Paths
* V3.2.0 Added Continuous scanning for problem angles
* * V3.3.0 Live Edit angle caculations
*/
/*global I18n, $, bootstrap, turf, getWmeSdk, SDK_INITIALIZED, GM_info, GM_xmlhttpRequest*/
(async function () {
'use strict';
// **************************************************************************************************************
// IMPORTANT: Update this when releasing a new version of script
// **************************************************************************************************************
const SHOW_UPDATE_MESSAGE = true;
const SCRIPT_VERSION_CHANGES = [
'Version 3.3.0:',
'Implement real-time marker updates during segment dragging',
'Experimental features released as "Advanced" options',
'Version 3.3.1: Small UI fix',
];
const SCRIPT_VERSION = GM_info.script.version.toString();
const DOWNLOAD_URL = 'https://update.greasyfork.org/scripts/35547/WME%20Junction%20Angle%20Info.user.js';
// ── Debug & execution state ───────────────────────────────────────────────
// Runtime flags and counters used across the module.
var junctionangle_debug = 1; // 0=off, 1=errors+warnings, 2=key decisions (function outcomes), 3=per-segment detail, 4=object dumps+internals — lower to 1 before release
var ja_last_restart = 0; // epoch ms timestamp — throttles auto-restart on stale data errors
var sdk; // WME SDK instance, assigned by bootstrap()
// ── Settings storage ──────────────────────────────────────────────────────
// ja_options holds all persisted user preferences (read/written via localStorage).
// ja_getOption() / ja_setOption() are the only safe accessors — they apply defaults
// and validate values against the ja_settings schema.
var ja_options = {};
// ── Cached data model properties ──────────────────────────────────────────
// Cached values from SDK to avoid redundant queries during module execution.
var ja_is_left_hand_traffic = false; // Cached from Countries.getAll()[0].isLeftHandTraffic (set during bootstrap)
// ── Map layer state ───────────────────────────────────────────────────────
// Shared state for the 'junction_angles' SDK map layer.
var ja_layer_created = false; // true once sdk.Map.addLayer() has returned
var ja_layer_visible = true; // mirrors the current Layer Switcher checkbox state
var ja_roundabout_points = []; // GeoJSON Points of RA markers placed this pass (collision detection)
var ja_current_features = []; // all features placed this render pass (overlap avoidance)
var ja_feature_counter = 0; // monotonic counter; features are named 'ja_' + (++ja_feature_counter)
// ── Marker position tracking (for local/far-turn overlap prevention) ─────────────────────────
// Maps to track marker positions during a render pass so local and far-turn markers can coordinate.
// Structure: map<nodeId, array<{bearing, distance}>>
// Reset each render pass at start of testSelectedItem().
var ja_local_markers_by_node = {}; // Local turn markers indexed by node, with bearings and distances
var ja_far_turn_bearings_by_node = {}; // Far-turn markers indexed by node, with bearings and distances
// ── UI state ──────────────────────────────────────────────────────────────
var ja_sidebar_tabPane = null; // SDK tab pane element — retained so setupHtml() can re-render it
// ── Continuous Scanning State (Phase 1: Cache + Event Infrastructure) ────────────────────
// Persistent cache survives across render passes (unlike ja_current_features which clears each pass)
var ja_continuous_cache = {}; // { nodeId: { timestamp, angles: [] } } — cross-render persistent
var ja_continuous_rendered = new Set(); // Track which angle markers already rendered to prevent duplicates
var ja_continuous_mode = false; // Feature flag: continuous scanning enabled/disabled
var ja_continuous_scan_timer = null; // Debounce timer (100ms, separate from ja_calculation_timer)
var ja_continuous_batch_index = 0; // Track progress in batch scan (for incremental processing)
var ja_nodes_all = []; // Copy of all viewport nodes (refreshed each scan start)
var ja_continuous_enabled = false; // Load from localStorage on init
var ja_continuous_needs_batching = []; // Nodes that need cache calculation (misses)
// ── Drag-Time Geometry Polling State (Real-time marker updates during segment drag) ──────────
// SVG polyline polling for immediate visual feedback while editing segment geometry
var ja_drag_geometry_polling_enabled = false; // Is polling active? Turns on when segment selected
var ja_drag_geometry_selected_segment_id = null; // Which segment are we polling? Set on selection
var ja_drag_geometry_last_coords = null; // Last known coordinates for change detection
var ja_drag_geometry_last_poll_time = 0; // Timestamp of last poll
var ja_drag_geometry_live_coords = null; // SVG coords for current render pass (used by testSelectedItem during drag)
var JA_DRAG_GEOMETRY_POLL_INTERVAL = 100; // milliseconds — poll SVG every 100ms during drag
// ── Angle classification thresholds ──────────────────────────────────────
// Waze routing instruction boundaries derived from map experiments and the Waze wiki.
var TURN_ANGLE = 45.5; // degrees — boundary between a Keep and a Turn instruction (wiki: 45.04°)
var U_TURN_ANGLE = 168.24; // degrees — boundary above which a turn is classified as a U-Turn
var GRAY_ZONE = 1.5; // degrees — margin around TURN_ANGLE to absorb measurement noise
// ── Timing configuration for continuous scanning ──────────────────────────
var BATCH_PROCESSING_DELAY = 50; // milliseconds — delay between incremental batch processing cycles
var CONTINUOUS_SCAN_DEBOUNCE = 100; // milliseconds — debounce window for coalescing rapid pan/zoom/edit events
var OVERLAPPING_ANGLE = 0.666; // degrees — two segments closer than this are treated as collinear
var MIN_ZOOM_LEVEL = 17; // hide all markers when zoomed out past this level
var PERPENDICULAR_TOLERANCE = 15; // degrees — tolerance for ±15° of perpendicular (90° multiple) in roundabouts and angle classification
var WAZE_PARALLELISM_TOLERANCE = 5; // degrees — parallelism threshold for A and C segments
var WAZE_MEDIAN_LENGTH_DEFAULT = 30; // meters — default median segment length for Waze U-turn qualification
var WAZE_MEDIAN_LENGTH_EXTENDED = 50; // meters — extended threshold with lane guidance on incoming segment
var WAZE_MEDIAN_LENGTH_THRESHOLD = 15; // meters — strict median threshold for optional Waze restriction (when setting is ON)
// Roundabout instruction thresholds (CCW angle ranges for normal roundabouts in right-hand traffic)
var ROUNDABOUT_INSTRUCTION_UTURN_THRESHOLD = 45; // < 45° or ≥ 315° → U-Turn
var ROUNDABOUT_INSTRUCTION_TURN_RIGHT_THRESHOLD = 135; // 45° – 135° → Turn Right (45 + 90)
var ROUNDABOUT_INSTRUCTION_CONTINUE_THRESHOLD = 225; // 135° – 225° → Continue (135 + 90)
var ROUNDABOUT_INSTRUCTION_TURN_LEFT_THRESHOLD = 315; // 225° – 315° → Turn Left (225 + 90)
// ── Routing instruction type enum ────────────────────────────────────────
// String keys stored in GeoJSON feature properties and matched by SDK styleRules predicates.
// BC = "best continuation" — Waze gives no spoken instruction for this turn.
// Override* variants are used when a turn has a manually set instruction opcode.
var ja_routing_type = {
BC: 'junction_none',
KEEP: 'junction_keep',
KEEP_LEFT: 'junction_keep_left',
KEEP_RIGHT: 'junction_keep_right',
TURN: 'junction_turn',
TURN_LEFT: 'junction_turn_left',
TURN_RIGHT: 'junction_turn_right',
EXIT: 'junction_exit',
EXIT_LEFT: 'junction_exit_left',
EXIT_RIGHT: 'junction_exit_right',
U_TURN: 'junction_u_turn',
PROBLEM: 'junction_problem',
NO_TURN: 'junction_no_turn',
NO_U_TURN: 'junction_no_u_turn',
ROUNDABOUT: 'junction_roundabout',
ROUNDABOUT_EXIT: 'junction_roundabout_exit',
OverrideBC: 'Override_none',
OverrideCONTINUE: 'Override_continue',
OverrideKEEP_LEFT: 'Override_keep_left',
OverrideKEEP_RIGHT: 'Override_keep_right',
OverrideTURN_LEFT: 'Override_turn_left',
OverrideTURN_RIGHT: 'Override_turn_right',
OverrideEXIT: 'Override_exit',
OverrideEXIT_LEFT: 'Override_exit_left',
OverrideEXIT_RIGHT: 'Override_exit_right',
OverrideU_TURN: 'Override_u_turn',
// ── Far turn types (experimental) ─────────────────────────────────────
// Far turns (isPathTurn or isJunctionBoxTurn) now use the same ja_routing_type values
// as regular node turns (BC, TURN, KEEP, etc.) — classified by ja_guess_routing_instruction
// using the instruction-firing angle (entry segment → first intermediate segment at entry node).
//
// The distinction between Path turns and JB turns is communicated via:
// • ja_is_far_turn: true on the GeoJSON feature properties → purple outline ring
//
// No separate PATH_TURN or JB_TURN type constants are needed. The two SDK flags are
// still used to identify far turns during processing in ja_draw_far_turn_markers():
// turn.isPathTurn === true → Path (FL2) far turn
// turn.isJunctionBoxTurn === true → Junction Box far turn
// Note: these two flags are mutually exclusive.
};
// ── Road type enum ────────────────────────────────────────────────────────
// Numeric road-type IDs matching WME data model values.
// Used by ja_is_primary_road(), ja_is_ramp(), and routing instruction prediction.
var ja_road_type = {
//Streets
NARROW_STREET: 22,
STREET: 1,
PRIMARY_STREET: 2,
//Highways
RAMP: 4,
FREEWAY: 3,
MAJOR_HIGHWAY: 6,
MINOR_HIGHWAY: 7,
//Other drivable
DIRT_ROAD: 8,
FERRY: 14,
PRIVATE_ROAD: 17,
PARKING_LOT_ROAD: 20,
//Non-drivable
WALKING_TRAIL: 5,
PEDESTRIAN_BOARDWALK: 10,
STAIRWAY: 16,
RAILROAD: 18,
RUNWAY: 19,
};
// ── Settings schema ───────────────────────────────────────────────────────
// Each entry describes one user-configurable option: the UI element type/id and
// the default value applied when no stored value exists or the stored value is invalid.
// Settings with a 'group' key are visually disabled when their parent checkbox is unchecked.
// ja_getOption() / ja_setOption() are the only safe accessors — never read ja_options directly.
var ja_settings = {
angleMode: { elementType: 'select', elementId: '_jaSelAngleMode', defaultValue: 'aDeparture', options: ['aAbsolute', 'aDeparture'] },
angleDisplay: { elementType: 'select', elementId: '_jaSelAngleDisplay', defaultValue: 'displayFancy', options: ['displayFancy', 'displaySimple'] },
angleDisplayArrows: { elementType: 'select', elementId: '_jaSelAngleDisplayArrows', defaultValue: '⇐⇒⇖⇗⇑', options: ['<><>', '⇦⇨⇦⇨⇧', '⇐⇒⇐⇒⇑', '←→←→↑', '⇐⇒⇖⇗⇑', '←→↖↗↑'] },
override: { elementType: 'checkbox', elementId: '_jaCbOverride', defaultValue: true, group: 'guess' },
overrideAngles: { elementType: 'checkbox', elementId: '_jaCboverrideAngles', defaultValue: false, group: 'override' },
guess: { elementType: 'checkbox', elementId: '_jaCbGuessRouting', defaultValue: true },
noInstructionColor: { elementType: 'color', elementId: '_jaTbNoInstructionColor', defaultValue: '#ffffff', group: 'guess' },
continueInstructionColor: { elementType: 'color', elementId: '_jaTbContinueInstructionColor', defaultValue: '#ffffff', group: 'guess' },
keepInstructionColor: { elementType: 'color', elementId: '_jaTbKeepInstructionColor', defaultValue: '#cbff84', group: 'guess' },
exitInstructionColor: { elementType: 'color', elementId: '_jaTbExitInstructionColor', defaultValue: '#6cb5ff', group: 'guess' },
turnInstructionColor: { elementType: 'color', elementId: '_jaTbTurnInstructionColor', defaultValue: '#4cc600', group: 'guess' },
uTurnInstructionColor: { elementType: 'color', elementId: '_jaTbUTurnInstructionColor', defaultValue: '#b66cff', group: 'guess' },
noTurnColor: { elementType: 'color', elementId: '_jaTbNoTurnColor', defaultValue: '#a0a0a0', group: 'guess' },
problemColor: { elementType: 'color', elementId: '_jaTbProblemColor', defaultValue: '#feed40', group: 'guess' },
roundaboutOverlayDisplay: { elementType: 'select', elementId: '_jaSelRoundaboutOverlayDisplay', defaultValue: 'rOverNever', options: ['rOverNever', 'rOverSelected', 'rOverAlways'] },
roundaboutOverlayColor: { elementType: 'color', elementId: '_jaTbRoundaboutOverlayColor', defaultValue: '#aa0000', group: 'roundaboutOverlayDisplay' },
roundaboutColor: { elementType: 'color', elementId: '_jaTbRoundaboutColor', defaultValue: '#ff8000', group: 'roundaboutOverlayDisplay' },
uTurnIncludeStreet: { elementType: 'checkbox', elementId: '_jaCbUTurnIncludeStreet', defaultValue: false },
uTurnIncludeParkingLot: { elementType: 'checkbox', elementId: '_jaCbUTurnIncludeParkingLot', defaultValue: false },
uTurnIncludePrivateRoad: { elementType: 'checkbox', elementId: '_jaCbUTurnIncludePrivateRoad', defaultValue: false },
wazeDoubleUTurnRestriction: { elementType: 'checkbox', elementId: '_jaCbWazeDoubleUTurnRestriction', defaultValue: true },
enableFarTurnJB: { elementType: 'checkbox', elementId: '_jaCbEnableFarTurnJB', defaultValue: false, group: 'experimental' },
enableFarTurnPath: { elementType: 'checkbox', elementId: '_jaCbEnableFarTurnPath', defaultValue: false, group: 'experimental' },
decimals: { elementType: 'number', elementId: '_jaTbDecimals', defaultValue: 2, min: 0, max: 2 },
pointSize: { elementType: 'number', elementId: '_jaTbPointSize', defaultValue: 12, min: 6, max: 20 },
// PHASE 4: Continuous Scanning Settings
continuousScanning: { elementType: 'checkbox', elementId: '_jaCbContinuousScanning', defaultValue: false, group: 'experimental' },
};
// ── Direction arrow character sets ────────────────────────────────────────
// Provides named accessors for the currently selected arrow character set.
// The actual character set string is stored in ja_options.angleDisplayArrows.
var ja_arrow = {
get: function (at) {
var arrows = ja_getOption('angleDisplayArrows');
return arrows[at % arrows.length];
},
left: function () {
return this.get(0);
},
right: function () {
return this.get(1);
},
left_up: function () {
return this.get(2);
},
right_up: function () {
return this.get(3);
},
up: function () {
return this.get(4);
},
};
/**
* Returns the current WME editor selection as a flat array of feature descriptors.
*
* Wraps sdk.Editing.getSelection() and maps each selected item to a plain object
* with { id, type } so callers do not need to interact with the SDK selection model
* directly. Filters to only segments and nodes (the only types JAI supports).
* Returns an empty array when nothing is selected or only unsupported types are selected.
*
* @returns {Array<{id: number, type: string}>} Selected segments/nodes, or [] if none.
*/
function getselfeat() {
var sel = sdk.Editing.getSelection();
if (!sel) {
return [];
}
// Only return segment and node selections — ignore all other types (bigJunction, venue, etc.)
var SUPPORTED_TYPES = { 'segment': true, 'node': true };
if (!SUPPORTED_TYPES[sel.objectType]) {
return [];
}
return sel.ids.map(function (id) {
return { type: sel.objectType, id: id };
});
}
/**
* Returns true if anything is currently selected in the editor.
*
* @returns {boolean} True if the selection is non-empty.
*/
function hasSelection() {
return getselfeat().length > 0;
}
/**
* Returns true if the given segment ID is currently selected in the editor.
*
* Uses getselfeat() to read the live selection state. Called during angle
* calculation to distinguish the incoming (selected) segment from other segments
* at a node so the correct departure angle can be identified.
*
* @param {number} segmentId - The segment ID to test.
* @returns {boolean} True if the segment is part of the current selection.
*/
function ja_is_segment_selected(segmentId) {
var sel = sdk.Editing.getSelection();
return sel != null && sel.objectType === 'segment' && sel.ids.indexOf(segmentId) !== -1;
}
/**
* Computes the base marker offset distance in meters for the current zoom level.
*
* The distance is looked up from a hard-coded table keyed by WME zoom level
* (13–22), then scaled by the configured decimal-places setting so that wider
* labels receive more spacing. Returns undefined at unsupported zoom levels and
* logs a warning.
*
* @returns {number} Base label distance in meters.
*/
function ja_compute_label_distance() {
var ja_label_distance;
switch (sdk.Map.getZoomLevel()) {
case 22:
ja_label_distance = 1.2;
break;
case 21:
ja_label_distance = 2.2;
break;
case 20:
ja_label_distance = 4.5;
break;
case 19:
ja_label_distance = 8;
break;
case 18:
ja_label_distance = 16;
break;
case 17:
ja_label_distance = 32;
break;
case 16:
ja_label_distance = 45;
break;
case 15:
ja_label_distance = 50;
break;
case 14:
ja_label_distance = 100;
break;
case 13:
ja_label_distance = 300;
break;
default:
ja_log('Unsupported zoom level: ' + sdk.Map.getZoomLevel() + '!', 1);
}
ja_label_distance *= 1 + 0.2 * parseInt(ja_getOption('decimals'));
ja_log('zoom: ' + sdk.Map.getZoomLevel() + ' -> distance: ' + ja_label_distance, 3);
return ja_label_distance;
}
/**
* Scans the given node list for roundabout (junction) membership and builds an
* entry/exit map.
*
* For each node, inspects connected segments for a non-null junctionId. When a
* junction is found, records the non-junction segment and node as the entry side
* (in_s / in_n). If the same junctionId is encountered a second time (second
* selected node on the same RA), the second node is recorded as the exit side
* (out_s / out_n). Also stores the junction geometry center point (p).
*
* @param {number[]} ja_nodes - Array of node IDs from the current selection.
* @returns {Object} Map of junctionId → { in_s, in_n, out_s, out_n, p }.
*/
function ja_find_roundabouts(ja_nodes) {
var ja_selected_roundabouts = {};
ja_nodes.forEach(function (node) {
var nodeObj = sdk.DataModel.Nodes.getById({ nodeId: node });
ja_log(nodeObj, 3);
var tmp_s = null,
tmp_n = null,
tmp_junctionID = null;
if (nodeObj == null || typeof nodeObj.connectedSegmentIds === 'undefined') {
return;
}
nodeObj.connectedSegmentIds.forEach(function (segment) {
ja_log(segment, 3);
var segObj = sdk.DataModel.Segments.getById({ segmentId: segment });
if (segObj != null && segObj.junctionId != null) {
ja_log('Roundabout detected: ' + segObj.junctionId, 3);
tmp_junctionID = segObj.junctionId;
} else {
tmp_s = segment;
tmp_n = node;
}
ja_log('tmp_s: ' + (tmp_s === null ? 'null' : tmp_s), 3);
});
ja_log('final tmp_s: ' + (tmp_s === null ? 'null' : tmp_s), 3);
if (tmp_junctionID === null) {
return;
}
if (ja_selected_roundabouts.hasOwnProperty(tmp_junctionID)) {
ja_selected_roundabouts[tmp_junctionID].out_s = tmp_s;
ja_selected_roundabouts[tmp_junctionID].out_n = node;
} else {
var tmp_junction = sdk.DataModel.Junctions.getById({ junctionId: tmp_junctionID });
ja_selected_roundabouts[tmp_junctionID] = {
in_s: tmp_s,
in_n: tmp_n,
out_s: null,
out_n: null,
p: tmp_junction ? tmp_junction.geometry : undefined,
};
}
});
return ja_selected_roundabouts;
}
/**
* Draws center-angle and ±N° deviation markers for all detected roundabouts.
*
* For each roundabout in the selection map: draws an optional circle overlay
* (rOverSelected mode), renders the triangle legs (in_n → center → out_n) as a
* LineString feature, calls ja_is_roundabout_normal() for its side effect of
* placing ±N° deviation markers at oblique exits, then places the center-angle
* marker colored per the specific entry→exit path angle (white = within ±PERPENDICULAR_TOLERANCE° of
* perpendicular; orange = non-normal).
*
* @param {Object} ja_selected_roundabouts - Map from ja_find_roundabouts().
* @param {number} ja_label_distance - Base marker offset distance in meters.
*/
function ja_draw_roundabout_markers(ja_selected_roundabouts, ja_label_distance) {
//Do some fancy painting for the roundabouts...
for (var tmp_roundabout in ja_selected_roundabouts) {
if (ja_selected_roundabouts.hasOwnProperty(tmp_roundabout)) {
// for...in always yields string keys; SDK requires a number type
var tmp_roundabout_id = parseInt(tmp_roundabout, 10);
ja_log(tmp_roundabout_id, 3);
ja_log(ja_selected_roundabouts[tmp_roundabout], 3);
//New roundabouts don't have coordinates yet..
if (typeof ja_selected_roundabouts[tmp_roundabout].p === 'undefined') {
continue;
}
// Entry-only selection (no exit node in selection): show all exits relative to entry
if (ja_selected_roundabouts[tmp_roundabout].out_n === null) {
ja_draw_roundabout_entry_exits(tmp_roundabout_id, ja_selected_roundabouts[tmp_roundabout].in_n, ja_label_distance);
continue;
}
// Roundabout arc selected: use the segment's entry node based on direction of travel.
// Show all exits from that entry — same view as selecting an entry segment connected at that node.
var _selfeat = getselfeat();
if (_selfeat.length === 1 && _selfeat[0].type === 'segment') {
var _selSeg = sdk.DataModel.Segments.getById({ segmentId: _selfeat[0].id });
if (_selSeg && _selSeg.junctionId !== null) {
// Determine entry node based on direction of travel (not geometric direction)
// isAtoB means traffic flows from fromNodeId to toNodeId; isBtoA means toNodeId to fromNodeId
var entryNodeForRA = _selSeg.isAtoB ? _selSeg.fromNodeId : _selSeg.toNodeId;
ja_log('[RA] Selected RA arc: isAtoB=' + _selSeg.isAtoB + ', isBtoA=' + _selSeg.isBtoA + ', entry node=' + entryNodeForRA, 2);
ja_draw_roundabout_entry_exits(tmp_roundabout_id, entryNodeForRA, ja_label_distance);
continue;
}
}
//Draw circle overlay for this roundabout
if (ja_getOption('roundaboutOverlayDisplay') === 'rOverSelected') {
ja_draw_roundabout_overlay(tmp_roundabout_id);
}
//Transform LonLat to actual layer projection
var tmp_roundabout_center = ja_coordinates_to_point(ja_selected_roundabouts[tmp_roundabout].p.coordinates);
var tmp_in_geom = sdk.DataModel.Nodes.getById({ nodeId: ja_selected_roundabouts[tmp_roundabout].in_n }).geometry;
var tmp_out_geom = sdk.DataModel.Nodes.getById({ nodeId: ja_selected_roundabouts[tmp_roundabout].out_n }).geometry;
var angle = ja_angle_between_points(tmp_in_geom, tmp_roundabout_center, tmp_out_geom);
//Draw the two legs of the triangle (in_n → center → out_n)
ja_add_feature({ type: 'LineString', coordinates: [tmp_in_geom.coordinates, tmp_roundabout_center.coordinates, tmp_out_geom.coordinates] }, { ja_type: 'arrow_line' });
// Call ja_is_roundabout_normal for its side effect: places ±N° deviation markers
// at any exit node that is more than 15° off perpendicular.
ja_is_roundabout_normal(tmp_roundabout_id, ja_selected_roundabouts[tmp_roundabout].in_n, ja_label_distance);
// Color the center marker based on THIS specific path's angle only.
// Per Waze: a roundabout can be normal for one entry and non-normal for another.
var ra_path_is_normal = ja_is_angle_normal(angle);
ja_add_feature(tmp_roundabout_center, {
angle: ja_round(angle) + '°',
ja_type: ra_path_is_normal ? ja_routing_type.BC : ja_routing_type.ROUNDABOUT,
});
}
}
}
/**
* Identifies short connector segments (≤30m, or ≤50m with lane guidance) that create
* double-turn or U-turn paths and returns an accumulator object for use during marker drawing.
*
* A double-turn occurs when a driver enters a short connector segment from one
* road and exits onto another road such that the combined heading change is near
* 180°. Waze may misclassify such paths; this function flags them as NO_U_TURN
* or PROBLEM so ja_draw_node_markers can render warning markers.
*
* Optional stricter Waze restriction: when the "Disable for <15m and ±5° parallel"
* setting is enabled, paths with median ≤15m and parallel arms are blocked.
*
* Only active in Departure angle mode when more than one node is selected.
*
* @param {number[]} ja_nodes - Array of selected node IDs.
* @returns {{data: Object, collect: Function, forEachItem: Function}} Accumulator.
*/
function ja_collect_double_turns(ja_nodes, allBigJunctions) {
/**
* Collect double-turn (inc. U-turn) segments info
*/
var doubleTurns = {
data: {}, //Structure: map<s_id, map<s_out_id, list<{s_in_id, angle, turn_type}>>>
farExitMarkers: [], //Markers to draw at the median's far exit node when an arm is selected
collect: function (s_id, s_in_id, s_out_id, angle, turn_type) {
ja_log('Collecting double-turn path from ' + s_in_id + ' to ' + s_out_id + ' via ' + s_id + ' with angle ' + angle + ' type: ' + turn_type, 2);
var info = this.data[s_id];
if (info === undefined) {
info = this.data[s_id] = {};
}
var list = info[s_out_id];
if (list === undefined) {
list = info[s_out_id] = [];
}
list.push({ s_in_id: s_in_id, angle: angle, turn_type: turn_type });
},
forEachItem: function (s_id, s_out_id, fn) {
var info = this.data[s_id];
if (info !== undefined) {
var list = info[s_out_id];
if (list !== undefined) {
list.forEach(function (item, i) {
fn(item, i);
});
}
}
},
};
//Loop through segments <=30 m (always qualifies) or 31-49 m with lane guidance on the incoming segment
if (ja_getOption('angleMode') === 'aDeparture' && ja_nodes.length > 1) {
getselfeat().forEach(function (selectedSegment) {
var segmentId = selectedSegment.id;
var segment = sdk.DataModel.Segments.getById({ segmentId: segmentId });
ja_log('Checking ' + segmentId + ' for double turns ...', 3);
var len = ja_segment_length(segment);
ja_log('Segment ' + segmentId + ' length: ' + len, 3);
if (!ja_is_uturn_qualifying_road(segment)) return;
// SUPPRESS LOCAL DOUBLE U-TURNS FOR ENTRY SEGMENTS CROSSING INTO JB
// When a segment crosses INTO a JB (one endpoint outside, one inside),
// JB far-turn logic (with U-TURN instructions) takes over. Local double-turn
// markers would duplicate the JB U-TURN marker.
var bjCrossing = ja_segment_crosses_bj_boundary(segment, allBigJunctions);
if (bjCrossing.crosses) {
ja_log('Skip double turns: ' + segmentId + ' crosses JB boundary', 3);
return; // Skip double-turn collection for this entry-to-JB segment
}
var fromNode = sdk.DataModel.Nodes.getById({ nodeId: segment.fromNodeId });
var toNode = sdk.DataModel.Nodes.getById({ nodeId: segment.toNodeId });
var lenRounded = Math.round(len);
if (lenRounded <= 49) {
var a_from = ja_getAngleMidleSeg(segment.fromNodeId, segment);
var a_to = ja_getAngleMidleSeg(segment.toNodeId, segment);
fromNode.connectedSegmentIds.forEach(function (fromSegmentId) {
if (fromSegmentId === segmentId) return;
var fromSegment = sdk.DataModel.Segments.getById({ segmentId: fromSegmentId });
if (!ja_is_uturn_qualifying_road(fromSegment)) return;
var from_a = ja_getAngle(segment.fromNodeId, fromSegment);
var from_angle = ja_angle_diff(from_a, a_from, false);
ja_log('Segment from ' + fromSegmentId + ' angle: ' + from_a + ', turn angle: ' + from_angle, 3);
toNode.connectedSegmentIds.forEach(function (toSegmentId) {
if (toSegmentId === segmentId) return;
var toSegment = sdk.DataModel.Segments.getById({ segmentId: toSegmentId });
if (!ja_is_uturn_qualifying_road(toSegment)) return;
var to_a = ja_getAngle(segment.toNodeId, toSegment);
var to_angle = ja_angle_diff(to_a, a_to, false);
ja_log('Segment to ' + toSegmentId + ' angle: ' + to_a + ', turn angle: ' + to_angle, 3);
var angle = Math.abs(to_angle - from_angle);
ja_log('Angle from ' + fromSegmentId + ' to ' + toSegmentId + ' is: ' + angle, 3);
// Path 1: fromSegment → segment → toSegment (A → B → C)
var hasLGFromToMedian = ja_segment_has_lane_guidance(fromSegmentId, fromNode.id, segmentId);
var turn_type_path1 = ja_classify_uturn_angle(angle, lenRounded, fromSegment, toSegment, fromNode.id, toNode.id, hasLGFromToMedian);
if (turn_type_path1 !== null) {
var useWazeRestriction = turn_type_path1 === ja_routing_type.NO_U_TURN;
// Collect if turns are allowed (same logic for both paths)
if (ja_is_turn_allowed(fromSegment, fromNode, segment) && ja_is_turn_allowed(segment, toNode, toSegment)) {
// When Waze restriction applies, always collect; otherwise check length/lane guidance
if (useWazeRestriction || lenRounded <= 30 || hasLGFromToMedian) {
doubleTurns.collect(segmentId, fromSegmentId, toSegmentId, angle, turn_type_path1);
}
}
}
// Path 2: toSegment → segment → fromSegment (C → B → A)
var hasLGToToMedian = ja_segment_has_lane_guidance(toSegmentId, toNode.id, segmentId);
var turn_type_path2 = ja_classify_uturn_angle(angle, lenRounded, toSegment, fromSegment, toNode.id, fromNode.id, hasLGToToMedian);
if (turn_type_path2 !== null) {
useWazeRestriction = turn_type_path2 === ja_routing_type.NO_U_TURN;
if (ja_is_turn_allowed(toSegment, toNode, segment) && ja_is_turn_allowed(segment, fromNode, fromSegment)) {
// When Waze restriction applies, always collect; otherwise check length/lane guidance
if (useWazeRestriction || lenRounded <= 30 || hasLGToToMedian) {
doubleTurns.collect(segmentId, toSegmentId, fromSegmentId, angle, turn_type_path2);
}
}
}
});
});
}
});
// Second pass: trigger double-turn detection when an entry/exit arm is selected.
// For each selected segment, look at its endpoint nodes for qualifying median neighbors.
// Skips any neighbor that is itself a selected segment (already handled by first loop).
var selectedIds = {};
getselfeat().forEach(function (s) {
selectedIds[s.id] = true;
});
getselfeat().forEach(function (selectedSegment) {
var armId = selectedSegment.id;
var armSeg = sdk.DataModel.Segments.getById({ segmentId: armId });
if (!ja_is_uturn_qualifying_road(armSeg)) return;
// SUPPRESS LOCAL DOUBLE U-TURNS FOR ARM SEGMENTS CROSSING INTO JB
var armBjCrossing = ja_segment_crosses_bj_boundary(armSeg, allBigJunctions);
if (armBjCrossing.crosses) {
ja_log('Skip arm double turns: ' + armId + ' crosses JB boundary', 3);
return;
}
[armSeg.fromNodeId, armSeg.toNodeId].forEach(function (armNodeId) {
var armNode = sdk.DataModel.Nodes.getById({ nodeId: armNodeId });
armNode.connectedSegmentIds.forEach(function (neighborId) {
if (neighborId === armId) return;
if (selectedIds[neighborId]) return; // already handled as direct median selection
var neighbor = sdk.DataModel.Segments.getById({ segmentId: neighborId });
if (!ja_is_uturn_qualifying_road(neighbor)) return;
var nLen = Math.round(ja_segment_length(neighbor));
if (nLen > 49) return;
if (nLen > 30 && !ja_segment_has_lane_guidance(armId, armNodeId, neighborId)) return;
if (!ja_is_turn_allowed(armSeg, armNode, neighbor)) return;
var a_arm_side = ja_getAngleMidleSeg(armNodeId, neighbor);
var medianFarNodeId = neighbor.fromNodeId === armNodeId ? neighbor.toNodeId : neighbor.fromNodeId;
var a_exit_side = ja_getAngleMidleSeg(medianFarNodeId, neighbor);
var medianFarNode = sdk.DataModel.Nodes.getById({ nodeId: medianFarNodeId });
var arm_a = ja_getAngle(armNodeId, armSeg);
var arm_angle = ja_angle_diff(arm_a, a_arm_side, false);
medianFarNode.connectedSegmentIds.forEach(function (exitId) {
if (exitId === neighborId) return;
var exitSeg = sdk.DataModel.Segments.getById({ segmentId: exitId });
if (!ja_is_uturn_qualifying_road(exitSeg)) return;
if (!ja_is_turn_allowed(neighbor, medianFarNode, exitSeg)) return;
var exit_a = ja_getAngle(medianFarNodeId, exitSeg);
var exit_angle = ja_angle_diff(exit_a, a_exit_side, false);
var combined_angle = Math.abs(exit_angle - arm_angle);
ja_log('Entry-arm trigger: ' + armId + ' -> ' + neighborId + ' -> ' + exitId + ' angle: ' + combined_angle, 3);
var turn_type = ja_classify_uturn_angle(combined_angle, nLen, armSeg, exitSeg, armNodeId, medianFarNodeId);
if (turn_type !== null) {
doubleTurns.farExitMarkers.push({
farNodeId: medianFarNodeId,
exitBearing: exit_a,
angle: combined_angle,
turn_type: turn_type,
});
}
});
});
});
});
}
ja_log('Double-turns collected: ' + doubleTurns.data.length + ' total', 3);
ja_log(doubleTurns.data, 4);
return doubleTurns;
}
/**
* Iterates selected nodes and draws angle markers for all connected segment pairs.
*
* For each node: computes the bearing of every connected segment, determines
* which segments are selected (incoming), then applies either Departure mode
* (one marker per exit, placed along that exit's bearing) or Absolute mode (one
* marker per adjacent pair, placed in the gap between them). Calls
* ja_guess_routing_instruction() to classify each turn and ja_draw_marker() to
* place the feature. Also draws double-turn markers for short connector paths.
*
* @param {number[]} ja_nodes - Array of node IDs to process.
* @param {number} ja_label_distance - Base marker offset distance in meters.
* @param {{data: Object, collect: Function, forEachItem: Function}} doubleTurns - From ja_collect_double_turns().
* @param {boolean} ja_selected_has_median - True if any selected segment is contained inside a
* BigJunction. When true, far-turn markers are suppressed: the regular node-pair logic handles
* internal JB segments, and showing far-turn exit markers would be misleading/incorrect.
* @param {number[]} ja_selected_seg_ids - IDs of the user-selected segments. Passed through to
* ja_draw_far_turn_markers so it only draws far turns from the selected entry segment(s).
* Empty when a node (not a segment) is selected — in that case all entries are shown.
* @param {boolean} ja_is_pure_node_selection - True if a node is directly selected (not via segment).
* When true, far-turn (Path/JB) markers are suppressed — show only the node's absolute angles.
* @returns {boolean} True if a data error occurred and the calculation must be retried.
*/
function ja_draw_node_markers(ja_nodes, ja_label_distance, doubleTurns, ja_selected_has_median, ja_selected_seg_ids, allBigJunctions, ja_is_pure_node_selection) {
var restart = false;
//Start looping through selected nodes
for (var i = 0; i < ja_nodes.length; i++) {
var node = sdk.DataModel.Nodes.getById({ nodeId: ja_nodes[i] });
var angles = [];
var ja_selected_segments_count = 0;
var ja_selected_angles = [];
var a;
if (node == null) {
//Oh oh.. should not happen? We want to use a node that does not exist
ja_log('[draw_node_markers] Null node at index ' + i + ' — should not happen', 1);
continue;
}
//check connected segments
var ja_current_node_segments = node.connectedSegmentIds;
// EPSG:3857 projected units = cos(lat) × true meters; correct so turf distances match OL originals
var ja_ld = ja_corrected_ld(ja_label_distance, node.geometry.coordinates);
ja_log(node, 4);
//ignore of we have less than 2 segments
if (ja_current_node_segments.length <= 1) {
ja_log('Found only ' + ja_current_node_segments.length + ' connected segments at ' + ja_nodes[i] + ', not calculating anything...', 3);
continue;
}
ja_log('Calculating angles for ' + ja_current_node_segments.length + ' segments', 3);
ja_log(ja_current_node_segments, 4);
ja_current_node_segments.forEach(function (nodeSegment, j) {
var s = sdk.DataModel.Segments.getById({ segmentId: nodeSegment });
// During drag polling: if this is the selected segment and we have live SVG coordinates,
// patch the segment object with the live geometry instead of the stale data model
if (ja_drag_geometry_live_coords && nodeSegment === ja_drag_geometry_selected_segment_id && s) {
s = ja_patchSegmentWithLiveCoords(s, ja_drag_geometry_live_coords);
}
if (typeof s === 'undefined') {
//Meh. Something went wrong, and we lost track of the segment. This needs a proper fix, but for now
// it should be sufficient to just restart the calculation
if (ja_drag_geometry_polling_enabled) {
ja_log('RESTART during polling: segment ' + nodeSegment + ' undefined', 2);
}
ja_log('Failed to read segment data from model. Restarting calculations.', 1);
if (ja_last_restart === 0) {
ja_last_restart = new Date().getTime();
setTimeout(function () {
ja_calculate();
}, 500);
}
restart = true;
}
a = ja_getAngle(ja_nodes[i], s);
ja_log('Segment ' + nodeSegment + ' angle: ' + a, 4);
angles[j] = [a, nodeSegment, s == null ? false : ja_is_segment_selected(nodeSegment)];
if (s == null ? false : ja_is_segment_selected(nodeSegment)) {
ja_selected_segments_count++;
}
});
if (restart) {
return true;
}
//make sure we have the selected angles in correct order
ja_log(ja_current_node_segments, 4);
getselfeat().forEach(function (selectedSegment) {
var selectedSegmentId = selectedSegment.id;
if (ja_current_node_segments.indexOf(selectedSegmentId) >= 0) {
//find the angle
for (var j = 0; j < angles.length; j++) {
if (angles[j][1] === selectedSegmentId) {
ja_selected_angles.push(angles[j]);
break;
}
}
ja_log('Selected segment ' + selectedSegmentId + ' found', 4);
}
});
ja_log(angles, 4);
var ha, point;
//if we have two connected segments selected, do some magic to get the turn angle only =)
if (ja_selected_segments_count === 2) {
a = ja_angle_diff(ja_selected_angles[0][0], ja_selected_angles[1][0], false);
ha = (parseFloat(ja_selected_angles[0][0]) + parseFloat(ja_selected_angles[1][0])) / 2;
if (
Math.abs(ja_selected_angles[0][0]) + Math.abs(ja_selected_angles[1][0]) > 180 &&
((ja_selected_angles[0][0] < 0 && ja_selected_angles[1][0] > 0) || (ja_selected_angles[0][0] > 0 && ja_selected_angles[1][0] < 0))
) {
ha += 180;
}
var ja_extra_space_multiplier = ja_compute_extra_space(a, ha);
ja_log('Angle: ' + a + '° at ' + ha + '°', 4);
//Guess some routing instructions based on segment types, angles etc
var ja_junction_type = ja_routing_type.TURN; //Default to old behavior
if (ja_getOption('guess')) {
ja_log(ja_selected_angles, 4);
ja_log(angles, 4);
var s_in_seg = ja_selected_angles[0][1];
var s_out_seg = ja_selected_angles[1][1];
ja_junction_type = ja_guess_routing_instruction(node, s_in_seg, s_out_seg, angles);
ja_log('Guess result: ' + s_in_seg + ' → ' + s_out_seg + ' = ' + ja_junction_type, 2);
}
//get the initial marker point
point = turf.destination(turf.point(node.geometry.coordinates), (ja_extra_space_multiplier * ja_ld) / 1000, ja_math_to_compass(ha)).geometry;
ja_draw_marker(point, node, ja_ld, a, ha, true, ja_junction_type);
// Record this local marker for far-turn conflict detection
// (Far-turn markers drawn later will check this data and adjust their distance if needed)
if (!ja_local_markers_by_node[node.id]) {
ja_local_markers_by_node[node.id] = [];
}
ja_local_markers_by_node[node.id].push({ bearing: ha, distance: ja_extra_space_multiplier * ja_ld });
//draw double turn markers
// If there are double-turn markers at this node+bearing, offset them farther out
var doubleTurnMultiplier = ja_extra_space_multiplier;
doubleTurns.forEachItem(ja_selected_angles[0][1], ja_selected_angles[1][1], function (item) {
if (doubleTurnMultiplier === ja_extra_space_multiplier) {
// First double-turn found: use larger distance to separate from local marker
doubleTurnMultiplier = ja_extra_space_multiplier * 1.4;
ja_log('[DOUBLE-TURN] Offset double-turn markers at node ' + node.id + ' by 1.4x', 2);
}
var doubleTurnPoint = turf.destination(turf.point(node.geometry.coordinates), (doubleTurnMultiplier * ja_ld) / 1000, ja_math_to_compass(ha)).geometry;
ja_draw_marker(doubleTurnPoint, node, ja_ld, item.angle, ha, true, item.turn_type);
});
} else {
//sort angle data (ascending)
angles.sort(function (a, b) {
return a[0] - b[0];
});
ja_log(angles, 4);
ja_log(ja_selected_segments_count, 4);
//get all segment angles
angles.forEach(function (angle, j) {
a = (360 + (angles[(j + 1) % angles.length][0] - angle[0])) % 360;
ha = (360 + (a / 2 + angle[0])) % 360;
var a_in = angles.filter(function (a) {
return !!a[2];
})[0];
//Show only one angle for nodes with only 2 connected segments and a single selected segment
// (not on both sides). Skipping the one > 180
if (ja_selected_segments_count === 1 && angles.length === 2 && a >= 180 && ja_getOption('angleMode') !== 'aDeparture') {
ja_log('Skipping marker, as we need only one of them', 3);
return;
}
if (ja_getOption('angleMode') === 'aDeparture' && ja_selected_segments_count > 0) {
if (a_in[1] === angle[1]) {
ja_log('in == out. skipping.', 3);
return;
}
ja_log('Angle in:', 3);
ja_log(a_in, 4);
var depMarkerType = ja_getOption('guess') ? ja_guess_routing_instruction(node, a_in[1], angle[1], angles) : ja_routing_type.TURN;
ja_log('Guess result: ' + a_in[1] + ' → ' + angle[1] + ' = ' + depMarkerType, 3);
//FIXME: we might want to try to keep the marker on the segment, instead of just
//in the direction of the first part
ha = angle[0];
a = ja_angle_diff(a_in[0], angles[j][0], false);
point = turf.destination(turf.point(node.geometry.coordinates), (ja_ld * 2) / 1000, ja_math_to_compass(ha)).geometry;
// CHECK FOR ENTRY SEGMENT CROSSING INTO JB
// If entry is outside JB and exit crosses out of JB boundary, move marker to boundary
var markerAnchor = node;
var isSquareMarker = false;
var entryIsInJB = sdk.DataModel.Segments.isContainedInBigJunction({ segmentId: a_in[1] });
// Only check for boundary crossing if entry is outside JB
if (!entryIsInJB) {
var exitSegment = sdk.DataModel.Segments.getById({ segmentId: angle[1] });
if (exitSegment) {
// Search for JB that the exit segment crosses OUT of
for (var bji = 0; bji < allBigJunctions.length; bji++) {
var bjPolygon = turf.polygon(allBigJunctions[bji].geometry.coordinates);
// Check if current node is inside this JB
var nodeIsInside = turf.booleanPointInPolygon(turf.point(node.geometry.coordinates), bjPolygon);
if (nodeIsInside) {
// Get the far endpoint of exit segment (node that's NOT the current node)
var exitCoords = exitSegment.geometry.coordinates;
var farEndpoint =
Math.abs(exitCoords[0][0] - node.geometry.coordinates[0]) < 0.0001 && Math.abs(exitCoords[0][1] - node.geometry.coordinates[1]) < 0.0001 ? exitCoords[1] : exitCoords[0];
var farIsInside = turf.booleanPointInPolygon(turf.point(farEndpoint), bjPolygon);
// If node is inside and far endpoint is outside, this exit crosses out of JB
if (!farIsInside) {
var closestPt = ja_find_closest_bj_intersection(exitSegment, bjPolygon, node);
if (closestPt !== null) {
markerAnchor = { geometry: closestPt.geometry };
isSquareMarker = true;
// Recalculate point from boundary anchor
// Use larger distance (3.5x) to avoid overlapping with WME's turn restriction arrows at the boundary
var boundaryLd = ja_corrected_ld(ja_label_distance, markerAnchor.geometry.coordinates);
point = turf.destination(turf.point(markerAnchor.geometry.coordinates), (boundaryLd * 3.5) / 1000, ja_math_to_compass(ha)).geometry;
ja_log('[JAI] Marker moved to JB boundary (3.5x distance)', 3);
break;
}
}
}
}
}
}
ja_draw_marker(
point,
markerAnchor,
ja_ld,
a,
ha,
true,
depMarkerType,
false,
isSquareMarker,
);
// Record this local marker for far-turn conflict detection
// (Far-turn markers drawn later will check this data and adjust their distance if needed)
if (!ja_local_markers_by_node[node.id]) {
ja_local_markers_by_node[node.id] = [];
}
ja_local_markers_by_node[node.id].push({ bearing: ha, distance: 2 * ja_ld });
//draw double turn markers
// If there are double-turn markers at this node+bearing, offset them farther out
// Use larger offset if at JB boundary to avoid WME turn restriction arrows
var doubleTurnDepartureMult = isSquareMarker ? 4.2 : 2.7;
doubleTurns.forEachItem(a_in[1], angle[1], function (item) {
if ((isSquareMarker && doubleTurnDepartureMult === 4.2) || (!isSquareMarker && doubleTurnDepartureMult === 2.7)) {
// First double-turn found at this anchor (boundary or node)
doubleTurnDepartureMult = isSquareMarker ? 4.9 : 3.3;
var boundarySuffix = isSquareMarker ? ' (at JB boundary)' : '';
ja_log('[DOUBLE-TURN] Offset double-turn markers at node ' + node.id + ' by ' + doubleTurnDepartureMult.toFixed(1) + 'x (departure mode)' + boundarySuffix, 2);
}
var doubleTurnDeparturePoint = turf.destination(turf.point(markerAnchor.geometry.coordinates), (doubleTurnDepartureMult * ja_ld) / 1000, ja_math_to_compass(ha)).geometry;
ja_draw_marker(doubleTurnDeparturePoint, markerAnchor, ja_ld, item.angle, ha, true, item.turn_type, false, isSquareMarker);
});
} else {
ja_log('Angle between ' + angle[1] + ' and ' + angles[(j + 1) % angles.length][1] + ' is ' + a + ' and position for label should be at ' + ha, 3);
point = turf.destination(turf.point(node.geometry.coordinates), (ja_ld * 1.25) / 1000, ja_math_to_compass(ha)).geometry;
ja_draw_marker(point, node, ja_ld, a, ha);
// Record this local marker for far-turn conflict detection
// (Far-turn markers drawn later will check this data and adjust their distance if needed)
if (!ja_local_markers_by_node[node.id]) {
ja_local_markers_by_node[node.id] = [];
}