forked from WazeDev/WazeWrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WazeWrapLib.js
2150 lines (1941 loc) · 107 KB
/
WazeWrapLib.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
/* global W */
/* global WazeWrap */
/* global & */
/* jshint esversion:6 */
/* eslint-disable */
(function () {
'use strict';
let wwSettings;
let wEvents;
function bootstrap(tries = 1) {
if (!location.href.match(/^https:\/\/(www|beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/?.*$/))
return;
if (W && W.map &&
W.model && W.loginManager.user &&
$)
init();
else if (tries < 1000)
setTimeout(function () { bootstrap(++tries); }, 200);
else
console.log('WazeWrap failed to load');
}
bootstrap();
async function init() {
console.log("WazeWrap initializing...");
WazeWrap.Version = "2020.05.22.01";
WazeWrap.isBetaEditor = /beta/.test(location.href);
loadSettings();
if(W.map.events)
wEvents = W.map.events;
else
wEvents = W.map.getMapEventsListener();
//SetUpRequire();
wEvents.register("moveend", this, RestoreMissingSegmentFunctions);
wEvents.register("zoomend", this, RestoreMissingSegmentFunctions);
wEvents.register("moveend", this, RestoreMissingNodeFunctions);
wEvents.register("zoomend", this, RestoreMissingNodeFunctions);
RestoreMissingSegmentFunctions();
RestoreMissingNodeFunctions();
RestoreMissingOLKMLSupport();
RestoreMissingWRule();
WazeWrap.Geometry = new Geometry();
WazeWrap.Model = new Model();
WazeWrap.Interface = new Interface();
WazeWrap.User = new User();
WazeWrap.Util = new Util();
WazeWrap.Require = new Require();
WazeWrap.String = new String();
WazeWrap.Events = new Events();
WazeWrap.Alerts = new Alerts();
WazeWrap.Remote = new Remote();
WazeWrap.getSelectedFeatures = function () {
return W.selectionManager.getSelectedFeatures();
};
WazeWrap.hasSelectedFeatures = function () {
return W.selectionManager.hasSelectedFeatures();
};
WazeWrap.selectFeature = function (feature) {
if (!W.selectionManager.select)
return W.selectionManager.selectFeature(feature);
return W.selectionManager.select(feature);
};
WazeWrap.selectFeatures = function (featureArray) {
if (!W.selectionManager.select)
return W.selectionManager.selectFeatures(featureArray);
return W.selectionManager.select(featureArray);
};
WazeWrap.hasPlaceSelected = function () {
return (W.selectionManager.hasSelectedFeatures() && W.selectionManager.getSelectedFeatures()[0].model.type === "venue");
};
WazeWrap.hasSegmentSelected = function () {
return (W.selectionManager.hasSelectedFeatures() && W.selectionManager.getSelectedFeatures()[0].model.type === "segment");
};
WazeWrap.hasMapCommentSelected = function () {
return (W.selectionManager.hasSelectedFeatures() && W.selectionManager.getSelectedFeatures()[0].model.type === "mapComment");
};
initializeScriptUpdateInterface();
await initializeToastr();
// 5/22/2019 (mapomatic)
// Temporary workaround to get the address field on the place edit
// panel to update when the place is updated. Can be removed if
// staff fixes it on their end.
try {
W.model.venues.on('objectschanged', venues => {
// Update venue address field display, if needed.
try {
const features = WazeWrap.getSelectedFeatures();
if (features.length === 1) {
const venue = features[0].model;
if (venues.includes(venue)) {
$('#landmark-edit-general span.full-address').text(venue.getAddress().format());
}
}
} catch (ex) {
console.error('WazeWrap error:', ex)
}
});
} catch (ex) {
// ignore if this doesn't work.
}
WazeWrap.Ready = true;
initializeWWInterface();
console.log('WazeWrap Loaded');
}
function initializeWWInterface(){
var $section = $("<div>", {style:"padding:8px 16px", id:"WMEPIESettings"});
$section.html([
'<h4 style="margin-bottom:0px;"><b>WazeWrap</b></h4>',
`<h6 style="margin-top:0px;">${WazeWrap.Version}</h6>`,
`<div id="divEditorPIN" class="controls-container">Editor PIN: <input type="${wwSettings.editorPIN != "" ? "password" : "text"}" size="10" id="wwEditorPIN" ${wwSettings.editorPIN != "" ? 'disabled' : ''}/>${wwSettings.editorPIN === "" ? '<button id="wwSetPin">Set PIN</button>' : ''}<i class="fa fa-eye fa-lg" style="display:${wwSettings.editorPIN === "" ? 'none' : 'inline-block'}" id="showWWEditorPIN" aria-hidden="true"></i></div><br/>`,
`<div id="changePIN" class="controls-container" style="display:${wwSettings.editorPIN !== "" ? "block" : "none"}"><button id="wwChangePIN">Change PIN</button></div>`,
'<div id="divShowAlertHistory" class="controls-container"><input type="checkbox" id="_cbShowAlertHistory" class="wwSettingsCheckbox" /><label for="_cbShowAlertHistory">Show alerts history</label></div>'
].join(' '));
new WazeWrap.Interface.Tab('WW', $section.html(), postInterfaceSetup);
}
function postInterfaceSetup(){
$('#wwEditorPIN')[0].value = wwSettings.editorPIN;
setChecked('_cbShowAlertHistory', wwSettings.showAlertHistoryIcon);
if(!wwSettings.showAlertHistoryIcon)
$('.WWAlertsHistory').css('display', 'none');
$('#showWWEditorPIN').mouseover(function(){
$('#wwEditorPIN').attr('type', 'text');
});
$('#showWWEditorPIN').mouseleave(function(){
$('#wwEditorPIN').attr('type', 'password');
});
$('#wwSetPin').click(function(){
let pin = $('#wwEditorPIN')[0].value;
if(pin != ""){
wwSettings.editorPIN = pin;
saveSettings();
$('#showWWEditorPIN').css('display', 'inline-block');
$('#wwEditorPIN').css('type', 'password');
$('#wwEditorPIN').attr("disabled", true);
$('#wwSetPin').css("display", 'none');
$('#changePIN').css("display", 'block');
}
});
$('#wwChangePIN').click(function(){
WazeWrap.Alerts.prompt("WazeWrap", "This will <b>not</b> change the PIN stored with your settings, only the PIN that is stored on your machine to lookup/save your settings. \n\nChanging your PIN can result in a loss of your settings on the server and/or your local machine. Proceed only if you are sure you need to change this value. \n\n Enter your new PIN", '', function(e, inputVal){
wwSettings.editorPIN = inputVal;
$('#wwEditorPIN')[0].value = inputVal;
saveSettings();
});
});
$('#_cbShowAlertHistory').change(function(){
if(this.checked)
$('.WWAlertsHistory').css('display', 'block');
else
$('.WWAlertsHistory').css('display', 'none');
wwSettings.showAlertHistoryIcon = this.checked;
saveSettings();
});
}
function setChecked(checkboxId, checked) {
$('#' + checkboxId).prop('checked', checked);
}
function loadSettings() {
wwSettings = $.parseJSON(localStorage.getItem("_wazewrap_settings"));
let _defaultsettings = {
showAlertHistoryIcon: true,
editorPIN: ""
};
wwSettings = $.extend({}, _defaultsettings, wwSettings);
}
function saveSettings() {
if (localStorage) {
let settings = {
showAlertHistoryIcon: wwSettings.showAlertHistoryIcon,
editorPIN: wwSettings.editorPIN
};
localStorage.setItem("_wazewrap_settings", JSON.stringify(settings));
}
}
async function initializeToastr() {
let toastrSettings = {};
try {
function loadSettings() {
var loadedSettings = $.parseJSON(localStorage.getItem("WWToastr"));
var defaultSettings = {
historyLeftLoc: 35,
historyTopLoc: 40
};
toastrSettings = $.extend({}, defaultSettings, loadedSettings)
}
function saveSettings() {
if (localStorage) {
var localsettings = {
historyLeftLoc: toastrSettings.historyLeftLoc,
historyTopLoc: toastrSettings.historyTopLoc
};
localStorage.setItem("WWToastr", JSON.stringify(localsettings));
}
}
loadSettings();
$('head').append(
$('<link/>', {
rel: 'stylesheet',
type: 'text/css',
href: 'https://cdn.staticaly.com/gh/WazeDev/toastr/master/build/toastr.min.css'
}),
$('<style type="text/css">.toast-container-wazedev > div {opacity: 0.95;} .toast-top-center-wide {top: 32px;}</style>')
);
await $.getScript('https://cdn.staticaly.com/gh/WazeDev/toastr/master/build/toastr.min.js');
wazedevtoastr.options = {
target: '#map',
timeOut: 6000,
positionClass: 'toast-top-center-wide',
closeOnHover: false,
closeDuration: 0,
showDuration: 0,
closeButton: true,
progressBar: true
};
if ($('.WWAlertsHistory').length > 0)
return;
var $sectionToastr = $("<div>", { style: "padding:8px 16px", id: "wmeWWScriptUpdates" });
$sectionToastr.html([
'<div class="WWAlertsHistory" title="Script Alert History"><i class="fa fa-exclamation-triangle fa-lg"></i><div id="WWAlertsHistory-list"><div id="toast-container-history" class="toast-container-wazedev"></div></div></div>'
].join(' '));
$("#WazeMap").append($sectionToastr.html());
$('.WWAlertsHistory').css('left', `${toastrSettings.historyLeftLoc}px`);
$('.WWAlertsHistory').css('top', `${toastrSettings.historyTopLoc}px`);
try {
await $.getScript("https://greasyfork.org/scripts/28687-jquery-ui-1-11-4-custom-min-js/code/jquery-ui-1114customminjs.js");
}
catch (err) {
console.log("Could not load jQuery UI " + err);
}
if ($.ui) {
$('.WWAlertsHistory').draggable({
stop: function () {
let windowWidth = $('#map').width();
let panelWidth = $('#WWAlertsHistory-list').width();
let historyLoc = $('.WWAlertsHistory').position().left;
if ((panelWidth + historyLoc) > windowWidth) {
$('#WWAlertsHistory-list').css('left', Math.abs(windowWidth - (historyLoc + $('.WWAlertsHistory').width()) - panelWidth) * -1);
}
else
$('#WWAlertsHistory-list').css('left', 'auto');
toastrSettings.historyLeftLoc = $('.WWAlertsHistory').position().left;
toastrSettings.historyTopLoc = $('.WWAlertsHistory').position().top;
saveSettings();
}
});
}
}
catch (err) {
console.log(err);
}
}
function initializeScriptUpdateInterface() {
console.log("creating script update interface");
injectCSS();
var $section = $("<div>", { style: "padding:8px 16px", id: "wmeWWScriptUpdates" });
$section.html([
'<div id="WWSU-Container" class="fa" style="position:fixed; top:20%; left:40%; z-index:1000; display:none;">',
'<div id="WWSU-Close" class="fa-close fa-lg"></div>',
'<div class="modal-heading">',
'<h2>Script Updates</h2>',
'<h4><span id="WWSU-updateCount">0</span> of your scripts have updates</h4>',
'</div>',
'<div class="WWSU-updates-wrapper">',
'<div id="WWSU-script-list">',
'</div>',
'<div id="WWSU-script-update-info">',
'</div></div></div>'
].join(' '));
$("#WazeMap").append($section.html());
$('#WWSU-Close').click(function () {
$('#WWSU-Container').hide();
});
$(document).on('click', '.WWSU-script-item', function () {
$('.WWSU-script-item').removeClass("WWSU-active");
$(this).addClass("WWSU-active");
});
}
function injectCSS() {
let css = [
'#WWSU-Container { position:relative; background-color:#fbfbfb; width:650px; height:375px; border-radius:8px; padding:20px; box-shadow: 0 22px 84px 0 rgba(87, 99, 125, 0.5); border:1px solid #ededed; }',
'#WWSU-Close { color:#000000; background-color:#ffffff; border:1px solid #ececec; border-radius:10px; height:25px; width:25px; position: absolute; right:14px; top:10px; cursor:pointer; padding: 5px 0px 0px 5px;}',
'#WWSU-Container .modal-heading,.WWSU-updates-wrapper { font-family: "Helvetica Neue", Helvetica, "Open Sans", sans-serif; } ',
'.WWSU-updates-wrapper { height:350px; }',
'#WWSU-script-list { float:left; width:175px; height:100%; padding-right:6px; margin-right:10px; overflow-y: auto; overflow-x: hidden; height:300px; }',
'.WWSU-script-item { text-decoration: none; min-height:40px; display:flex; text-align: center; justify-content: center; align-items: center; margin:3px 3px 10px 3px; background-color:white; border-radius:8px; box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 1px 0.25px; transition:all 200ms ease-in-out; cursor:pointer;}',
'.WWSU-script-item:hover { text-decoration: none; }',
'.WWSU-active { transform: translate3d(5px, 0px, 0px); box-shadow: rgba(0, 0, 0, 0.4) 0px 3px 7px 0px; }',
'#WWSU-script-update-info { width:auto; background-color:white; height:275px; overflow-y:auto; border-radius:8px; box-shadow: rgba(0, 0, 0, 0.09) 0px 6px 7px 0.09px; padding:15px; position:relative;}',
'#WWSU-script-update-info div { display: none;}',
'#WWSU-script-update-info div:target { display: block; }',
`.WWAlertsHistory {display:${wwSettings.showAlertHistoryIcon ? 'block' : 'none'}; width:32px; height:32px; background-color: #F89406; position: absolute; top:35px; left:40px; border-radius: 10px; border: 2px solid; box-size: border-box; z-index: 1050;}`,
'.WWAlertsHistory:hover #WWAlertsHistory-list{display:block;}',
'.WWAlertsHistory > .fa-exclamation-triangle {position: absolute; left:50%; margin-left:-9px; margin-top:8px;}',
'#WWAlertsHistory-list{display:none; position:absolute; top:28px; border:2px solid black; border-radius:10px; background-color:white; padding:4px; overflow-y:auto; max-height: 300px;}',
'#WWAlertsHistory-list #toast-container-history > div {max-width:500px; min-width:500px; border-radius:10px;}',
'#WWAlertsHistory-list > #toast-container-history{ position:static; }'
].join(' ');
$('<style type="text/css">' + css + '</style>').appendTo('head');
}
function RestoreMissingWRule(){
if(!W.Rule){
W.Rule = OpenLayers.Class(OpenLayers.Rule, {
getContext(feature) {
return feature;
},
CLASS_NAME: "Waze.Rule"
});
}
}
function RestoreMissingSegmentFunctions() {
if (W.model.segments.getObjectArray().length > 0) {
wEvents.unregister("moveend", this, RestoreMissingSegmentFunctions);
wEvents.unregister("zoomend", this, RestoreMissingSegmentFunctions);
if (typeof W.model.segments.getObjectArray()[0].model.getDirection == "undefined")
W.model.segments.getObjectArray()[0].__proto__.getDirection = function () { return (this.attributes.fwdDirection ? 1 : 0) + (this.attributes.revDirection ? 2 : 0); };
if (typeof W.model.segments.getObjectArray()[0].model.isTollRoad == "undefined")
W.model.segments.getObjectArray()[0].__proto__.isTollRoad = function () { return (this.attributes.fwdToll || this.attributes.revToll); };
if (typeof W.model.segments.getObjectArray()[0].isLockedByHigherRank == "undefined")
W.model.segments.getObjectArray()[0].__proto__.isLockedByHigherRank = function () { return !(!this.attributes.lockRank || !this.model.loginManager.isLoggedIn()) && this.getLockRank() > this.model.loginManager.user.rank; };
if (typeof W.model.segments.getObjectArray()[0].isDrivable == "undefined")
W.model.segments.getObjectArray()[0].__proto__.isDrivable = function () { let V = [5, 10, 16, 18, 19]; return !V.includes(this.attributes.roadType); };
if (typeof W.model.segments.getObjectArray()[0].isWalkingRoadType == "undefined")
W.model.segments.getObjectArray()[0].__proto__.isWalkingRoadType = function () { let x = [5, 10, 16]; return x.includes(this.attributes.roadType); };
if (typeof W.model.segments.getObjectArray()[0].isRoutable == "undefined")
W.model.segments.getObjectArray()[0].__proto__.isRoutable = function () { let P = [1, 2, 7, 6, 3]; return P.includes(this.attributes.roadType); };
if (typeof W.model.segments.getObjectArray()[0].isInBigJunction == "undefined")
W.model.segments.getObjectArray()[0].__proto__.isInBigJunction = function () { return this.isBigJunctionShort() || this.hasFromBigJunction() || this.hasToBigJunction(); };
if (typeof W.model.segments.getObjectArray()[0].isBigJunctionShort == "undefined")
W.model.segments.getObjectArray()[0].__proto__.isBigJunctionShort = function () { return null != this.attributes.crossroadID; };
if (typeof W.model.segments.getObjectArray()[0].hasFromBigJunction == "undefined")
W.model.segments.getObjectArray()[0].__proto__.hasFromBigJunction = function (e) { return null != e ? this.attributes.fromCrossroads.includes(e) : this.attributes.fromCrossroads.length > 0; };
if (typeof W.model.segments.getObjectArray()[0].hasToBigJunction == "undefined")
W.model.segments.getObjectArray()[0].__proto__.hasToBigJunction = function (e) { return null != e ? this.attributes.toCrossroads.includes(e) : this.attributes.toCrossroads.length > 0; };
if (typeof W.model.segments.getObjectArray()[0].getRoundabout == "undefined")
W.model.segments.getObjectArray()[0].__proto__.getRoundabout = function () { return this.isInRoundabout() ? this.model.junctions.getObjectById(this.attributes.junctionID) : null; };
}
}
function RestoreMissingNodeFunctions() {
if (W.model.nodes.getObjectArray().length > 0) {
wEvents.unregister("moveend", this, RestoreMissingNodeFunctions);
wEvents.unregister("zoomend", this, RestoreMissingNodeFunctions);
if (typeof W.model.nodes.getObjectArray()[0].areConnectionsEditable == "undefined")
W.model.nodes.getObjectArray()[0].__proto__.areConnectionsEditable = function () { var e = this.model.segments.getByIds(this.attributes.segIDs); return e.length === this.attributes.segIDs.length && e.every(function (e) { return e.canEditConnections(); }); };
}
}
/* jshint ignore:start */
function RestoreMissingOLKMLSupport() {
if (!OpenLayers.Format.KML) {
OpenLayers.Format.KML = OpenLayers.Class(OpenLayers.Format.XML, {
namespaces: { kml: "http://www.opengis.net/kml/2.2", gx: "http://www.google.com/kml/ext/2.2" }, kmlns: "http://earth.google.com/kml/2.0", placemarksDesc: "No description available", foldersName: "OL export", foldersDesc: "Exported on " + new Date, extractAttributes: !0, kvpAttributes: !1, extractStyles: !1, extractTracks: !1, trackAttributes: null, internalns: null, features: null, styles: null, styleBaseUrl: "", fetched: null, maxDepth: 0, initialize: function (a) {
this.regExes =
{ trimSpace: /^\s*|\s*$/g, removeSpace: /\s*/g, splitSpace: /\s+/, trimComma: /\s*,\s*/g, kmlColor: /(\w{2})(\w{2})(\w{2})(\w{2})/, kmlIconPalette: /root:\/\/icons\/palette-(\d+)(\.\w+)/, straightBracket: /\$\[(.*?)\]/g }; this.externalProjection = new OpenLayers.Projection("EPSG:4326"); OpenLayers.Format.XML.prototype.initialize.apply(this, [a])
}, read: function (a) { this.features = []; this.styles = {}; this.fetched = {}; return this.parseData(a, { depth: 0, styleBaseUrl: this.styleBaseUrl }) }, parseData: function (a, b) {
"string" == typeof a &&
(a = OpenLayers.Format.XML.prototype.read.apply(this, [a])); for (var c = ["Link", "NetworkLink", "Style", "StyleMap", "Placemark"], d = 0, e = c.length; d < e; ++d) { var f = c[d], g = this.getElementsByTagNameNS(a, "*", f); if (0 != g.length) switch (f.toLowerCase()) { case "link": case "networklink": this.parseLinks(g, b); break; case "style": this.extractStyles && this.parseStyles(g, b); break; case "stylemap": this.extractStyles && this.parseStyleMaps(g, b); break; case "placemark": this.parseFeatures(g, b) } } return this.features
}, parseLinks: function (a,
b) { if (b.depth >= this.maxDepth) return !1; var c = OpenLayers.Util.extend({}, b); c.depth++; for (var d = 0, e = a.length; d < e; d++) { var f = this.parseProperty(a[d], "*", "href"); f && !this.fetched[f] && (this.fetched[f] = !0, (f = this.fetchLink(f)) && this.parseData(f, c)) } }, fetchLink: function (a) { if (a = OpenLayers.Request.GET({ url: a, async: !1 })) return a.responseText }, parseStyles: function (a, b) { for (var c = 0, d = a.length; c < d; c++) { var e = this.parseStyle(a[c]); e && (this.styles[(b.styleBaseUrl || "") + "#" + e.id] = e) } }, parseKmlColor: function (a) {
var b =
null; a && (a = a.match(this.regExes.kmlColor)) && (b = { color: "#" + a[4] + a[3] + a[2], opacity: parseInt(a[1], 16) / 255 }); return b
}, parseStyle: function (a) {
for (var b = {}, c = ["LineStyle", "PolyStyle", "IconStyle", "BalloonStyle", "LabelStyle"], d, e, f = 0, g = c.length; f < g; ++f)if (d = c[f], e = this.getElementsByTagNameNS(a, "*", d)[0]) switch (d.toLowerCase()) {
case "linestyle": d = this.parseProperty(e, "*", "color"); if (d = this.parseKmlColor(d)) b.strokeColor = d.color, b.strokeOpacity = d.opacity; (d = this.parseProperty(e, "*", "width")) && (b.strokeWidth =
d); break; case "polystyle": d = this.parseProperty(e, "*", "color"); if (d = this.parseKmlColor(d)) b.fillOpacity = d.opacity, b.fillColor = d.color; "0" == this.parseProperty(e, "*", "fill") && (b.fillColor = "none"); "0" == this.parseProperty(e, "*", "outline") && (b.strokeWidth = "0"); break; case "iconstyle": var h = parseFloat(this.parseProperty(e, "*", "scale") || 1); d = 32 * h; var i = 32 * h, j = this.getElementsByTagNameNS(e, "*", "Icon")[0]; if (j) {
var k = this.parseProperty(j, "*", "href"); if (k) {
var l = this.parseProperty(j, "*", "w"), m = this.parseProperty(j,
"*", "h"); OpenLayers.String.startsWith(k, "http://maps.google.com/mapfiles/kml") && (!l && !m) && (m = l = 64, h /= 2); l = l || m; m = m || l; l && (d = parseInt(l) * h); m && (i = parseInt(m) * h); if (m = k.match(this.regExes.kmlIconPalette)) l = m[1], m = m[2], k = this.parseProperty(j, "*", "x"), j = this.parseProperty(j, "*", "y"), k = "http://maps.google.com/mapfiles/kml/pal" + l + "/icon" + (8 * (j ? 7 - j / 32 : 7) + (k ? k / 32 : 0)) + m; b.graphicOpacity = 1; b.externalGraphic = k
}
} if (e = this.getElementsByTagNameNS(e, "*", "hotSpot")[0]) k = parseFloat(e.getAttribute("x")), j = parseFloat(e.getAttribute("y")),
l = e.getAttribute("xunits"), "pixels" == l ? b.graphicXOffset = -k * h : "insetPixels" == l ? b.graphicXOffset = -d + k * h : "fraction" == l && (b.graphicXOffset = -d * k), e = e.getAttribute("yunits"), "pixels" == e ? b.graphicYOffset = -i + j * h + 1 : "insetPixels" == e ? b.graphicYOffset = -(j * h) + 1 : "fraction" == e && (b.graphicYOffset = -i * (1 - j) + 1); b.graphicWidth = d; b.graphicHeight = i; break; case "balloonstyle": (e = OpenLayers.Util.getXmlNodeValue(e)) && (b.balloonStyle = e.replace(this.regExes.straightBracket, "${$1}")); break; case "labelstyle": if (d = this.parseProperty(e,
"*", "color"), d = this.parseKmlColor(d)) b.fontColor = d.color, b.fontOpacity = d.opacity
}!b.strokeColor && b.fillColor && (b.strokeColor = b.fillColor); if ((a = a.getAttribute("id")) && b) b.id = a; return b
}, parseStyleMaps: function (a, b) {
for (var c = 0, d = a.length; c < d; c++)for (var e = a[c], f = this.getElementsByTagNameNS(e, "*", "Pair"), e = e.getAttribute("id"), g = 0, h = f.length; g < h; g++) {
var i = f[g], j = this.parseProperty(i, "*", "key"); (i = this.parseProperty(i, "*", "styleUrl")) && "normal" == j && (this.styles[(b.styleBaseUrl || "") + "#" + e] = this.styles[(b.styleBaseUrl ||
"") + i])
}
}, parseFeatures: function (a, b) {
for (var c = [], d = 0, e = a.length; d < e; d++) {
var f = a[d], g = this.parseFeature.apply(this, [f]); if (g) {
this.extractStyles && (g.attributes && g.attributes.styleUrl) && (g.style = this.getStyle(g.attributes.styleUrl, b)); if (this.extractStyles) { var h = this.getElementsByTagNameNS(f, "*", "Style")[0]; if (h && (h = this.parseStyle(h))) g.style = OpenLayers.Util.extend(g.style, h) } if (this.extractTracks) {
if ((f = this.getElementsByTagNameNS(f, this.namespaces.gx, "Track")) && 0 < f.length) g = { features: [], feature: g },
this.readNode(f[0], g), 0 < g.features.length && c.push.apply(c, g.features)
} else c.push(g)
} else throw "Bad Placemark: " + d;
} this.features = this.features.concat(c)
}, readers: {
kml: { when: function (a, b) { b.whens.push(OpenLayers.Date.parse(this.getChildValue(a))) }, _trackPointAttribute: function (a, b) { var c = a.nodeName.split(":").pop(); b.attributes[c].push(this.getChildValue(a)) } }, gx: {
Track: function (a, b) {
var c = { whens: [], points: [], angles: [] }; if (this.trackAttributes) {
var d; c.attributes = {}; for (var e = 0, f = this.trackAttributes.length; e <
f; ++e)d = this.trackAttributes[e], c.attributes[d] = [], d in this.readers.kml || (this.readers.kml[d] = this.readers.kml._trackPointAttribute)
} this.readChildNodes(a, c); if (c.whens.length !== c.points.length) throw Error("gx:Track with unequal number of when (" + c.whens.length + ") and gx:coord (" + c.points.length + ") elements."); var g = 0 < c.angles.length; if (g && c.whens.length !== c.angles.length) throw Error("gx:Track with unequal number of when (" + c.whens.length + ") and gx:angles (" + c.angles.length + ") elements."); for (var h,
i, e = 0, f = c.whens.length; e < f; ++e) {
h = b.feature.clone(); h.fid = b.feature.fid || b.feature.id; i = c.points[e]; h.geometry = i; "z" in i && (h.attributes.altitude = i.z); this.internalProjection && this.externalProjection && h.geometry.transform(this.externalProjection, this.internalProjection); if (this.trackAttributes) { i = 0; for (var j = this.trackAttributes.length; i < j; ++i)h.attributes[d] = c.attributes[this.trackAttributes[i]][e] } h.attributes.when = c.whens[e]; h.attributes.trackId = b.feature.id; g && (i = c.angles[e], h.attributes.heading =
parseFloat(i[0]), h.attributes.tilt = parseFloat(i[1]), h.attributes.roll = parseFloat(i[2])); b.features.push(h)
}
}, coord: function (a, b) { var c = this.getChildValue(a).replace(this.regExes.trimSpace, "").split(/\s+/), d = new OpenLayers.Geometry.Point(c[0], c[1]); 2 < c.length && (d.z = parseFloat(c[2])); b.points.push(d) }, angles: function (a, b) { var c = this.getChildValue(a).replace(this.regExes.trimSpace, "").split(/\s+/); b.angles.push(c) }
}
}, parseFeature: function (a) {
for (var b = ["MultiGeometry", "Polygon", "LineString", "Point"],
c, d, e, f = 0, g = b.length; f < g; ++f)if (c = b[f], this.internalns = a.namespaceURI ? a.namespaceURI : this.kmlns, d = this.getElementsByTagNameNS(a, this.internalns, c), 0 < d.length) { if (b = this.parseGeometry[c.toLowerCase()]) e = b.apply(this, [d[0]]), this.internalProjection && this.externalProjection && e.transform(this.externalProjection, this.internalProjection); else throw new TypeError("Unsupported geometry type: " + c); break } var h; this.extractAttributes && (h = this.parseAttributes(a)); c = new OpenLayers.Feature.Vector(e, h); a = a.getAttribute("id") ||
a.getAttribute("name"); null != a && (c.fid = a); return c
}, getStyle: function (a, b) { var c = OpenLayers.Util.removeTail(a), d = OpenLayers.Util.extend({}, b); d.depth++; d.styleBaseUrl = c; !this.styles[a] && !OpenLayers.String.startsWith(a, "#") && d.depth <= this.maxDepth && !this.fetched[c] && (c = this.fetchLink(c)) && this.parseData(c, d); return OpenLayers.Util.extend({}, this.styles[a]) }, parseGeometry: {
point: function (a) {
var b = this.getElementsByTagNameNS(a, this.internalns, "coordinates"), a = []; if (0 < b.length) var c = b[0].firstChild.nodeValue,
c = c.replace(this.regExes.removeSpace, ""), a = c.split(","); b = null; if (1 < a.length) 2 == a.length && (a[2] = null), b = new OpenLayers.Geometry.Point(a[0], a[1], a[2]); else throw "Bad coordinate string: " + c; return b
}, linestring: function (a, b) {
var c = this.getElementsByTagNameNS(a, this.internalns, "coordinates"), d = null; if (0 < c.length) {
for (var c = this.getChildValue(c[0]), c = c.replace(this.regExes.trimSpace, ""), c = c.replace(this.regExes.trimComma, ","), d = c.split(this.regExes.splitSpace), e = d.length, f = Array(e), g, h, i = 0; i < e; ++i)if (g =
d[i].split(","), h = g.length, 1 < h) 2 == g.length && (g[2] = null), f[i] = new OpenLayers.Geometry.Point(g[0], g[1], g[2]); else throw "Bad LineString point coordinates: " + d[i]; if (e) d = b ? new OpenLayers.Geometry.LinearRing(f) : new OpenLayers.Geometry.LineString(f); else throw "Bad LineString coordinates: " + c;
} return d
}, polygon: function (a) {
var a = this.getElementsByTagNameNS(a, this.internalns, "LinearRing"), b = a.length, c = Array(b); if (0 < b) for (var d = 0, e = a.length; d < e; ++d)if (b = this.parseGeometry.linestring.apply(this, [a[d], !0])) c[d] =
b; else throw "Bad LinearRing geometry: " + d; return new OpenLayers.Geometry.Polygon(c)
}, multigeometry: function (a) { for (var b, c = [], d = a.childNodes, e = 0, f = d.length; e < f; ++e)a = d[e], 1 == a.nodeType && (b = this.parseGeometry[(a.prefix ? a.nodeName.split(":")[1] : a.nodeName).toLowerCase()]) && c.push(b.apply(this, [a])); return new OpenLayers.Geometry.Collection(c) }
}, parseAttributes: function (a) {
var b = {}, c = a.getElementsByTagName("ExtendedData"); c.length && (b = this.parseExtendedData(c[0])); for (var d, e, f, a = a.childNodes, c = 0, g =
a.length; c < g; ++c)if (d = a[c], 1 == d.nodeType && (e = d.childNodes, 1 <= e.length && 3 >= e.length)) { switch (e.length) { case 1: f = e[0]; break; case 2: f = e[0]; e = e[1]; f = 3 == f.nodeType || 4 == f.nodeType ? f : e; break; default: f = e[1] }if (3 == f.nodeType || 4 == f.nodeType) if (d = d.prefix ? d.nodeName.split(":")[1] : d.nodeName, f = OpenLayers.Util.getXmlNodeValue(f)) f = f.replace(this.regExes.trimSpace, ""), b[d] = f } return b
}, parseExtendedData: function (a) {
var b = {}, c, d, e, f, g = a.getElementsByTagName("Data"); c = 0; for (d = g.length; c < d; c++) {
e = g[c]; f = e.getAttribute("name");
var h = {}, i = e.getElementsByTagName("value"); i.length && (h.value = this.getChildValue(i[0])); this.kvpAttributes ? b[f] = h.value : (e = e.getElementsByTagName("displayName"), e.length && (h.displayName = this.getChildValue(e[0])), b[f] = h)
} a = a.getElementsByTagName("SimpleData"); c = 0; for (d = a.length; c < d; c++)h = {}, e = a[c], f = e.getAttribute("name"), h.value = this.getChildValue(e), this.kvpAttributes ? b[f] = h.value : (h.displayName = f, b[f] = h); return b
}, parseProperty: function (a, b, c) {
var d, a = this.getElementsByTagNameNS(a, b, c); try { d = OpenLayers.Util.getXmlNodeValue(a[0]) } catch (e) {
d =
null
} return d
}, write: function (a) { OpenLayers.Util.isArray(a) || (a = [a]); for (var b = this.createElementNS(this.kmlns, "kml"), c = this.createFolderXML(), d = 0, e = a.length; d < e; ++d)c.appendChild(this.createPlacemarkXML(a[d])); b.appendChild(c); return OpenLayers.Format.XML.prototype.write.apply(this, [b]) }, createFolderXML: function () {
var a = this.createElementNS(this.kmlns, "Folder"); if (this.foldersName) { var b = this.createElementNS(this.kmlns, "name"), c = this.createTextNode(this.foldersName); b.appendChild(c); a.appendChild(b) } this.foldersDesc &&
(b = this.createElementNS(this.kmlns, "description"), c = this.createTextNode(this.foldersDesc), b.appendChild(c), a.appendChild(b)); return a
}, createPlacemarkXML: function (a) {
var b = this.createElementNS(this.kmlns, "name"); b.appendChild(this.createTextNode(a.style && a.style.label ? a.style.label : a.attributes.name || a.id)); var c = this.createElementNS(this.kmlns, "description"); c.appendChild(this.createTextNode(a.attributes.description || this.placemarksDesc)); var d = this.createElementNS(this.kmlns, "Placemark"); null !=
a.fid && d.setAttribute("id", a.fid); d.appendChild(b); d.appendChild(c); b = this.buildGeometryNode(a.geometry); d.appendChild(b); a.attributes && (a = this.buildExtendedData(a.attributes)) && d.appendChild(a); return d
}, buildGeometryNode: function (a) { var b = a.CLASS_NAME, b = this.buildGeometry[b.substring(b.lastIndexOf(".") + 1).toLowerCase()], c = null; b && (c = b.apply(this, [a])); return c }, buildGeometry: {
point: function (a) { var b = this.createElementNS(this.kmlns, "Point"); b.appendChild(this.buildCoordinatesNode(a)); return b }, multipoint: function (a) {
return this.buildGeometry.collection.apply(this,
[a])
}, linestring: function (a) { var b = this.createElementNS(this.kmlns, "LineString"); b.appendChild(this.buildCoordinatesNode(a)); return b }, multilinestring: function (a) { return this.buildGeometry.collection.apply(this, [a]) }, linearring: function (a) { var b = this.createElementNS(this.kmlns, "LinearRing"); b.appendChild(this.buildCoordinatesNode(a)); return b }, polygon: function (a) {
for (var b = this.createElementNS(this.kmlns, "Polygon"), a = a.components, c, d, e = 0, f = a.length; e < f; ++e)c = 0 == e ? "outerBoundaryIs" : "innerBoundaryIs",
c = this.createElementNS(this.kmlns, c), d = this.buildGeometry.linearring.apply(this, [a[e]]), c.appendChild(d), b.appendChild(c); return b
}, multipolygon: function (a) { return this.buildGeometry.collection.apply(this, [a]) }, collection: function (a) { for (var b = this.createElementNS(this.kmlns, "MultiGeometry"), c, d = 0, e = a.components.length; d < e; ++d)(c = this.buildGeometryNode.apply(this, [a.components[d]])) && b.appendChild(c); return b }
}, buildCoordinatesNode: function (a) {
var b = this.createElementNS(this.kmlns, "coordinates"),
c; if (c = a.components) { for (var d = c.length, e = Array(d), f = 0; f < d; ++f)a = c[f], e[f] = this.buildCoordinates(a); c = e.join(" ") } else c = this.buildCoordinates(a); c = this.createTextNode(c); b.appendChild(c); return b
}, buildCoordinates: function (a) { this.internalProjection && this.externalProjection && (a = a.clone(), a.transform(this.internalProjection, this.externalProjection)); return a.x + "," + a.y }, buildExtendedData: function (a) {
var b = this.createElementNS(this.kmlns, "ExtendedData"), c; for (c in a) if (a[c] && "name" != c && "description" !=
c && "styleUrl" != c) { var d = this.createElementNS(this.kmlns, "Data"); d.setAttribute("name", c); var e = this.createElementNS(this.kmlns, "value"); if ("object" == typeof a[c]) { if (a[c].value && e.appendChild(this.createTextNode(a[c].value)), a[c].displayName) { var f = this.createElementNS(this.kmlns, "displayName"); f.appendChild(this.getXMLDoc().createCDATASection(a[c].displayName)); d.appendChild(f) } } else e.appendChild(this.createTextNode(a[c])); d.appendChild(e); b.appendChild(d) } return this.isSimpleContent(b) ? null : b
},
CLASS_NAME: "OpenLayers.Format.KML"
});
}
}
/* jshint ignore:end */
function Geometry() {
//Converts to "normal" GPS coordinates
this.ConvertTo4326 = function (lon, lat) {
let projI = new OpenLayers.Projection("EPSG:900913");
let projE = new OpenLayers.Projection("EPSG:4326");
return (new OpenLayers.LonLat(lon, lat)).transform(projI, projE);
};
this.ConvertTo900913 = function (lon, lat) {
let projI = new OpenLayers.Projection("EPSG:900913");
let projE = new OpenLayers.Projection("EPSG:4326");
return (new OpenLayers.LonLat(lon, lat)).transform(projE, projI);
};
//Converts the Longitudinal offset to an offset in 4326 gps coordinates
this.CalculateLongOffsetGPS = function (longMetersOffset, lon, lat) {
let R = 6378137; //Earth's radius
let dLon = longMetersOffset / (R * Math.cos(Math.PI * lat / 180)); //offset in radians
let lon0 = dLon * (180 / Math.PI); //offset degrees
return lon0;
};
//Converts the Latitudinal offset to an offset in 4326 gps coordinates
this.CalculateLatOffsetGPS = function (latMetersOffset, lat) {
let R = 6378137; //Earth's radius
let dLat = latMetersOffset / R;
let lat0 = dLat * (180 / Math.PI); //offset degrees
return lat0;
};
/**
* Checks if the given lon & lat
* @function WazeWrap.Geometry.isGeometryInMapExtent
* @param {lon, lat} object
*/
this.isLonLatInMapExtent = function (lonLat) {
return lonLat && W.map.getExtent().containsLonLat(lonLat);
};
/**
* Checks if the given geometry point is on screen
* @function WazeWrap.Geometry.isGeometryInMapExtent
* @param {OpenLayers.Geometry.Point} Geometry Point we are checking if it is in the extent
*/
this.isGeometryInMapExtent = function (geometry) {
return geometry && geometry.getBounds &&
W.map.getExtent().intersectsBounds(geometry.getBounds());
};
/**
* Calculates the distance between given points, returned in meters
* @function WazeWrap.Geometry.calculateDistance
* @param {OpenLayers.Geometry.Point} An array of OpenLayers.Geometry.Point with which to measure the total distance. A minimum of 2 points is needed.
*/
this.calculateDistance = function (pointArray) {
if (pointArray.length < 2)
return 0;
let line = new OpenLayers.Geometry.LineString(pointArray);
let length = line.getGeodesicLength(W.map.getProjectionObject());
return length; //multiply by 3.28084 to convert to feet
};
/**
* Finds the closest on-screen drivable segment to the given point, ignoring PLR and PR segments if the options are set
* @function WazeWrap.Geometry.findClosestSegment
* @param {OpenLayers.Geometry.Point} The given point to find the closest segment to
* @param {boolean} If true, Parking Lot Road segments will be ignored when finding the closest segment
* @param {boolean} If true, Private Road segments will be ignored when finding the closest segment
**/
this.findClosestSegment = function (mygeometry, ignorePLR, ignoreUnnamedPR) {
let onscreenSegments = WazeWrap.Model.getOnscreenSegments();
let minDistance = Infinity;
let closestSegment;
for (var s in onscreenSegments) {
if (!onscreenSegments.hasOwnProperty(s))
continue;
let segmentType = onscreenSegments[s].attributes.roadType;
if (segmentType === 10 || segmentType === 16 || segmentType === 18 || segmentType === 19) //10 ped boardwalk, 16 stairway, 18 railroad, 19 runway, 3 freeway
continue;
if (ignorePLR && segmentType === 20) //PLR
continue;
if (ignoreUnnamedPR)
if (segmentType === 17 && WazeWrap.Model.getStreetName(onscreenSegments[s].attributes.primaryStreetID) === null) //PR
continue;
let distanceToSegment = mygeometry.distanceTo(onscreenSegments[s].geometry, { details: true });
if (distanceToSegment.distance < minDistance) {
minDistance = distanceToSegment.distance;
closestSegment = onscreenSegments[s];
closestSegment.closestPoint = new OpenLayers.Geometry.Point(distanceToSegment.x1, distanceToSegment.y1);
}
}
return closestSegment;
};
}
function Model() {
this.getPrimaryStreetID = function (segmentID) {
return W.model.segments.getObjectById(segmentID).attributes.primaryStreetID;
};
this.getStreetName = function (primaryStreetID) {
return W.model.streets.getObjectById(primaryStreetID).name;
};
this.getCityID = function (primaryStreetID) {
return W.model.streets.getObjectById(primaryStreetID).cityID;
};
this.getCityName = function (primaryStreetID) {
return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.name;
};
this.getStateName = function (primaryStreetID) {
return W.model.states.getObjectById(this.getStateID(primaryStreetID)).name;
};
this.getStateID = function (primaryStreetID) {
return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.stateID;
};
this.getCountryID = function (primaryStreetID) {
return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.CountryID;
};
this.getCountryName = function (primaryStreetID) {
return W.model.countries.getObjectById(this.getCountryID(primaryStreetID)).name;
};
this.getCityNameFromSegmentObj = function (segObj) {
return this.getCityName(segObj.attributes.primaryStreetID);
};
this.getStateNameFromSegmentObj = function (segObj) {
return this.getStateName(segObj.attributes.primaryStreetID);
};
/**
* Returns an array of segment IDs for all segments that make up the roundabout the given segment is part of
* @function WazeWrap.Model.getAllRoundaboutSegmentsFromObj
* @param {Segment object (Waze/Feature/Vector/Segment)} The roundabout segment
**/
this.getAllRoundaboutSegmentsFromObj = function (segObj) {
if (segObj.model.attributes.junctionID === null)
return null;
return W.model.junctions.objects[segObj.model.attributes.junctionID].attributes.segIDs;
};
/**
* Returns an array of all junction nodes that make up the roundabout
* @function WazeWrap.Model.getAllRoundaboutJunctionNodesFromObj
* @param {Segment object (Waze/Feature/Vector/Segment)} The roundabout segment
**/
this.getAllRoundaboutJunctionNodesFromObj = function (segObj) {
let RASegs = this.getAllRoundaboutSegmentsFromObj(segObj);
let RAJunctionNodes = [];
for (i = 0; i < RASegs.length; i++)
RAJunctionNodes.push(W.model.nodes.objects[W.model.segments.getObjectById(RASegs[i]).attributes.toNodeID]);
return RAJunctionNodes;
};
/**
* Checks if the given segment ID is a part of a roundabout
* @function WazeWrap.Model.isRoundaboutSegmentID
* @param {integer} The segment ID to check
**/
this.isRoundaboutSegmentID = function (segmentID) {
return W.model.segments.getObjectById(segmentID).attributes.junctionID !== null
};
/**
* Checks if the given segment object is a part of a roundabout
* @function WazeWrap.Model.isRoundaboutSegmentID
* @param {Segment object (Waze/Feature/Vector/Segment)} The segment object to check
**/
this.isRoundaboutSegmentObj = function (segObj) {
return segObj.model.attributes.junctionID !== null;
};
/**
* Returns an array of all segments in the current extent
* @function WazeWrap.Model.getOnscreenSegments
**/
this.getOnscreenSegments = function () {
let segments = W.model.segments.objects;
let mapExtent = W.map.getExtent();
let onScreenSegments = [];
let seg;
for (var s in segments) {
if (!segments.hasOwnProperty(s))
continue;
seg = W.model.segments.getObjectById(s);
if (mapExtent.intersectsBounds(seg.geometry.getBounds()))
onScreenSegments.push(seg);
}
return onScreenSegments;
};
/**
* Defers execution of a callback function until the WME map and data
* model are ready. Call this function before calling a function that
* causes a map and model reload, such as W.map.moveTo(). After the
* move is completed the callback function will be executed.
* @function WazeWrap.Model.onModelReady
* @param {Function} callback The callback function to be executed.
* @param {Boolean} now Whether or not to call the callback now if the
* model is currently ready.
* @param {Object} context The context in which to call the callback.
*/
this.onModelReady = function (callback, now, context) {
var deferModelReady = function () {
return $.Deferred(function (dfd) {
var resolve = function () {
dfd.resolve();
W.model.events.unregister('mergeend', null, resolve);
};
W.model.events.register('mergeend', null, resolve);
}).promise();
};
var deferMapReady = function () {
return $.Deferred(function (dfd) {
var resolve = function () {
dfd.resolve();
W.vent.off('operationDone', resolve);
};
W.vent.on('operationDone', resolve);
}).promise();
};
if (typeof callback === 'function') {
context = context || callback;
if (now && WazeWrap.Util.mapReady() && WazeWrap.Util.modelReady()) {
callback.call(context);
} else {
$.when(deferMapReady() && deferModelReady()).
then(function () {
callback.call(context);
});
}
}
};
/**
* Retrives a route from the Waze Live Map.
* @class
* @name WazeWrap.Model.RouteSelection
* @param firstSegment The segment to use as the start of the route.
* @param lastSegment The segment to use as the destination for the route.
* @param {Array|Function} callback A function or array of funcitons to be
* executed after the route
* is retrieved. 'This' in the callback functions will refer to the
* RouteSelection object.
* @param {Object} options A hash of options for determining route. Valid
* options are:
* fastest: {Boolean} Whether or not the fastest route should be used.
* Default is false, which selects the shortest route.
* freeways: {Boolean} Whether or not to avoid freeways. Default is false.
* dirt: {Boolean} Whether or not to avoid dirt roads. Default is false.
* longtrails: {Boolean} Whether or not to avoid long dirt roads. Default
* is false.
* uturns: {Boolean} Whether or not to allow U-turns. Default is true.
* @return {WazeWrap.Model.RouteSelection} The new RouteSelection object.
* @example: // The following example will retrieve a route from the Live Map and select the segments in the route.
* selection = W.selectionManager.selectedItems;
* myRoute = new WazeWrap.Model.RouteSelection(selection[0], selection[1], function(){this.selectRouteSegments();}, {fastest: true});
*/
this.RouteSelection = function (firstSegment, lastSegment, callback, options) {
var i,
n,
start = this.getSegmentCenterLonLat(firstSegment),
end = this.getSegmentCenterLonLat(lastSegment);
this.options = {
fastest: options && options.fastest || false,
freeways: options && options.freeways || false,
dirt: options && options.dirt || false,
longtrails: options && options.longtrails || false,
uturns: options && options.uturns || true
};
this.requestData = {
from: 'x:' + start.x + ' y:' + start.y + ' bd:true',
to: 'x:' + end.x + ' y:' + end.y + ' bd:true',
returnJSON: true,
returnGeometries: true,
returnInstructions: false,
type: this.options.fastest ? 'HISTORIC_TIME' : 'DISTANCE',
clientVersion: '4.0.0',
timeout: 60000,
nPaths: 3,
options: this.setRequestOptions(this.options)
};
this.callbacks = [];
if (callback) {
if (!(callback instanceof Array)) {
callback = [callback];
}
for (i = 0, n = callback.length; i < n; i++) {
if ('function' === typeof callback[i]) {
this.callbacks.push(callback[i]);
}
}
}
this.routeData = null;
this.getRouteData();
};
this.RouteSelection.prototype =
/** @lends WazeWrap.Model.RouteSelection.prototype */ {
/**
* Formats the routing options string for the ajax request.
* @private
* @param {Object} options Object containing the routing options.
* @return {String} String containing routing options.
*/
setRequestOptions: function (options) {
return 'AVOID_TOLL_ROADS:' + (options.tolls ? 't' : 'f') + ',' +
'AVOID_PRIMARIES:' + (options.freeways ? 't' : 'f') + ',' +
'AVOID_TRAILS:' + (options.dirt ? 't' : 'f') + ',' +
'AVOID_LONG_TRAILS:' + (options.longtrails ? 't' : 'f') + ',' +
'ALLOW_UTURNS:' + (options.uturns ? 't' : 'f');
},
/**
* Gets the center of a segment in LonLat form.
* @private
* @param segment A Waze model segment object.
* @return {OpenLayers.LonLat} The LonLat object corresponding to the
* center of the segment.
*/
getSegmentCenterLonLat: function (segment) {
var x, y, componentsLength, midPoint;
if (segment) {
componentsLength = segment.geometry.components.length;
midPoint = Math.floor(componentsLength / 2);
if (componentsLength % 2 === 1) {
x = segment.geometry.components[midPoint].x;
y = segment.geometry.components[midPoint].y;
} else {
x = (segment.geometry.components[midPoint - 1].x +
segment.geometry.components[midPoint].x) / 2;
y = (segment.geometry.components[midPoint - 1].y +
segment.geometry.components[midPoint].y) / 2;
}
return new OpenLayers.Geometry.Point(x, y).
transform(W.map.getProjectionObject(), 'EPSG:4326');
}
},
/**
* Gets the route from Live Map and executes any callbacks upon success.
* @private
* @returns The ajax request object. The responseJSON property of the
* returned object
* contains the route information.
*
*/
getRouteData: function () {
var i,
n,
that = this;
return $.ajax({
dataType: 'json',
url: this.getURL(),
data: this.requestData,
dataFilter: function (data, dataType) {
return data.replace(/NaN/g, '0');
},
success: function (data) {
that.routeData = data;
for (i = 0, n = that.callbacks.length; i < n; i++) {
that.callbacks[i].call(that);
}
}
});
},
/**
* Extracts the IDs from all segments on the route.
* @private
* @return {Array} Array containing an array of segment IDs for
* each route alternative.
*/
getRouteSegmentIDs: function () {
var i, j, route, len1, len2, segIDs = [],
routeArray = [],
data = this.routeData;
if ('undefined' !== typeof data.alternatives) {
for (i = 0, len1 = data.alternatives.length; i < len1; i++) {
route = data.alternatives[i].response.results;
for (j = 0, len2 = route.length; j < len2; j++) {
routeArray.push(route[j].path.segmentId);
}
segIDs.push(routeArray);
routeArray = [];
}
} else {
route = data.response.results;
for (i = 0, len1 = route.length; i < len1; i++) {
routeArray.push(route[i].path.segmentId);
}
segIDs.push(routeArray);
}
return segIDs;
},
/**
* Gets the URL to use for the ajax request based on country.
* @private
* @return {String} Relative URl to use for route ajax request.
*/
getURL: function () {
if (W.model.countries.getObjectById(235) || W.model.countries.getObjectById(40)) {
return '/RoutingManager/routingRequest';
} else if (W.model.countries.getObjectById(106)) {
return '/il-RoutingManager/routingRequest';
} else {
return '/row-RoutingManager/routingRequest';
}
},
/**
* Selects all segments on the route in the editor.
* @param {Integer} routeIndex The index of the alternate route.
* Default route to use is the first one, which is 0.
*/
selectRouteSegments: function (routeIndex) {
var i, n, seg,
segIDs = this.getRouteSegmentIDs()[Math.floor(routeIndex) || 0],
segments = [];
if ('undefined' === typeof segIDs) {
return;
}
for (i = 0, n = segIDs.length; i < n; i++) {
seg = W.model.segments.getObjectById(segIDs[i]);
if ('undefined' !== seg) {
segments.push(seg);
}
}
return WazeWrap.selectFeatures(segments);
}
};
}
function User() {
/**
* Returns the "normalized" (1 based) user rank/level
*/
this.Rank = function () {
return W.loginManager.user.rank + 1;
};
/**
* Returns the current user's username
*/
this.Username = function () {
return W.loginManager.user.userName;
};
/**
* Returns if the user is a CM (in any country)
*/
this.isCM = function () {
return W.loginManager.user.editableCountryIDs.length > 0
};
/**
* Returns if the user is an Area Manager (in any country)
*/
this.isAM = function () {
return W.loginManager.user.isAreaManager;
};
}
function Require() {
this.DragElement = function () {
var myDragElement = OpenLayers.Class({
started: !1,
stopDown: !0,
dragging: !1,
touch: !1,
last: null,
start: null,
lastMoveEvt: null,