WazeWrapLib dev

WazeWrapLib for development purposes

当前为 2025-04-11 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/532551/1569445/WazeWrapLib%20dev.js

  1. /* global W */
  2. /* global WazeWrap */
  3. /* jshint esversion:6 */
  4. /* eslint-disable */
  5.  
  6. (function () {
  7. 'use strict';
  8. let wwSettings;
  9. let wEvents;
  10. let testValue;
  11.  
  12. function bootstrap(tries = 1) {
  13. testValue = 'test';
  14. if (!location.href.match(/^https:\/\/(www|beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/?.*$/))
  15. return;
  16.  
  17. if (W && W.map &&
  18. W.model && W.loginManager.user &&
  19. $)
  20. init();
  21. else if (tries < 1000)
  22. setTimeout(function () { bootstrap(++tries); }, 200);
  23. else
  24. console.log('WazeWrap failed to load');
  25. }
  26.  
  27. bootstrap();
  28.  
  29. async function init() {
  30. console.log("WazeWrap initializing...");
  31. WazeWrap.Version = "2025.03.12.01";
  32. WazeWrap.isBetaEditor = /beta/.test(location.href);
  33. loadSettings();
  34. if(W.map.events)
  35. wEvents = W.map.events;
  36. else
  37. wEvents = W.map.getMapEventsListener();
  38.  
  39. //SetUpRequire();
  40. wEvents.register("moveend", this, RestoreMissingSegmentFunctions);
  41. wEvents.register("zoomend", this, RestoreMissingSegmentFunctions);
  42. wEvents.register("moveend", this, RestoreMissingNodeFunctions);
  43. wEvents.register("zoomend", this, RestoreMissingNodeFunctions);
  44. RestoreMissingSegmentFunctions();
  45. RestoreMissingNodeFunctions();
  46. RestoreMissingOLKMLSupport();
  47. RestoreMissingWRule();
  48.  
  49. WazeWrap.Geometry = new Geometry();
  50. WazeWrap.Model = new Model();
  51. WazeWrap.Interface = new Interface();
  52. WazeWrap.User = new User();
  53. WazeWrap.Util = new Util();
  54. WazeWrap.Require = new Require();
  55. WazeWrap.String = new String();
  56. WazeWrap.Events = new Events();
  57. WazeWrap.Alerts = new Alerts();
  58. WazeWrap.Remote = new Remote();
  59.  
  60. WazeWrap.getSelectedFeatures = function () {
  61. let arr = W.selectionManager.getSelectedFeatures();
  62. //inject functions for pulling information since WME backend is receiving frequent changes
  63. arr.forEach((item, index, array) => {
  64. array[index].WW = {};
  65. array[index].WW.getObjectModel = function(){ return item._wmeObject;};
  66. array[index].WW.getType = function(){return item?.WW?.getObjectModel().type;};
  67. array[index].WW.getAttributes = function(){return item?.WW?.getObjectModel().attributes;};
  68. });
  69. return arr;
  70. };
  71. WazeWrap.getSelectedDataModelObjects = function(){
  72. if(typeof W.selectionManager.getSelectedDataModelObjects === 'function')
  73. return W.selectionManager.getSelectedDataModelObjects();
  74. else
  75. return WazeWrap.getSelectedFeatures().map(e => e.WW.getObjectModel());
  76. };
  77.  
  78. WazeWrap.hasSelectedFeatures = function () {
  79. return W.selectionManager.hasSelectedFeatures();
  80. };
  81.  
  82. WazeWrap.selectFeature = function (feature) {
  83. if (!W.selectionManager.select)
  84. return W.selectionManager.selectFeature(feature);
  85.  
  86. return W.selectionManager.select(feature);
  87. };
  88.  
  89. WazeWrap.selectFeatures = function (featureArray) {
  90. if (!W.selectionManager.select)
  91. return W.selectionManager.selectFeatures(featureArray);
  92. return W.selectionManager.select(featureArray);
  93. };
  94.  
  95. WazeWrap.hasPlaceSelected = function () {
  96. return (W.selectionManager.hasSelectedFeatures() && WazeWrap.getSelectedFeatures()[0].WW.getType() === "venue");
  97. };
  98.  
  99. WazeWrap.hasSegmentSelected = function () {
  100. return (W.selectionManager.hasSelectedFeatures() && WazeWrap.getSelectedFeatures()[0].WW.getType() === "segment");
  101. };
  102.  
  103. WazeWrap.hasMapCommentSelected = function () {
  104. return (W.selectionManager.hasSelectedFeatures() && WazeWrap.getSelectedFeatures()[0].WW.getType() === "mapComment");
  105. };
  106.  
  107. initializeScriptUpdateInterface();
  108. await initializeToastr();
  109.  
  110. // 5/22/2019 (mapomatic)
  111. // Temporary workaround to get the address field on the place edit
  112. // panel to update when the place is updated. Can be removed if
  113. // staff fixes it on their end.
  114. try {
  115. W.model.venues.on('objectschanged', venues => {
  116. // Update venue address field display, if needed.
  117. try {
  118. const features = WazeWrap.getSelectedDataModelObjects();
  119. if (features.length === 1) {
  120. const venue = features[0];
  121. if (venues.includes(venue)) {
  122. $('#landmark-edit-general span.full-address').text(venue.getAddress().format());
  123. }
  124. }
  125. } catch (ex) {
  126. console.error('WazeWrap error:', ex);
  127. }
  128. });
  129. } catch (ex) {
  130. // ignore if this doesn't work.
  131. }
  132.  
  133. WazeWrap.Ready = true;
  134. initializeWWInterface();
  135.  
  136. console.log('WazeWrap Loaded');
  137. }
  138. function initializeWWInterface(){
  139. var $section = $("<div>", {style:"padding:8px 16px", id:"WMEPIESettings"});
  140. $section.html([
  141. '<h4 style="margin-bottom:0px;"><b>WazeWrap</b></h4>',
  142. `<h6 style="margin-top:0px;">${WazeWrap.Version}</h6>`,
  143. `<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/>`,
  144. `<div id="changePIN" class="controls-container" style="display:${wwSettings.editorPIN !== "" ? "block" : "none"}"><button id="wwChangePIN">Change PIN</button></div>`,
  145. '<div id="divShowAlertHistory" class="controls-container"><input type="checkbox" id="_cbShowAlertHistory" class="wwSettingsCheckbox" /><label for="_cbShowAlertHistory">Show alerts history</label></div>'
  146. ].join(' '));
  147. WazeWrap.Interface.Tab('WW', $section.html(), postInterfaceSetup, 'WazeWrap');
  148. }
  149. function postInterfaceSetup(){
  150. $('#wwEditorPIN')[0].value = wwSettings.editorPIN;
  151. setChecked('_cbShowAlertHistory', wwSettings.showAlertHistoryIcon);
  152. if(!wwSettings.showAlertHistoryIcon)
  153. $('.WWAlertsHistory').css('display', 'none');
  154. $('#showWWEditorPIN').mouseover(function(){
  155. $('#wwEditorPIN').attr('type', 'text');
  156. });
  157. $('#showWWEditorPIN').mouseleave(function(){
  158. $('#wwEditorPIN').attr('type', 'password');
  159. });
  160. $('#wwSetPin').click(function(){
  161. let pin = $('#wwEditorPIN')[0].value;
  162. if(pin != ""){
  163. wwSettings.editorPIN = pin;
  164. saveSettings();
  165. $('#showWWEditorPIN').css('display', 'inline-block');
  166. $('#wwEditorPIN').css('type', 'password');
  167. $('#wwEditorPIN').attr("disabled", true);
  168. $('#wwSetPin').css("display", 'none');
  169. $('#changePIN').css("display", 'block');
  170. }
  171. });
  172. $('#wwChangePIN').click(function(){
  173. 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){
  174. wwSettings.editorPIN = inputVal;
  175. $('#wwEditorPIN')[0].value = inputVal;
  176. saveSettings();
  177. });
  178. });
  179. $('#_cbShowAlertHistory').change(function(){
  180. if(this.checked)
  181. $('.WWAlertsHistory').css('display', 'block');
  182. else
  183. $('.WWAlertsHistory').css('display', 'none');
  184. wwSettings.showAlertHistoryIcon = this.checked;
  185. saveSettings();
  186. });
  187. }
  188. function setChecked(checkboxId, checked) {
  189. $('#' + checkboxId).prop('checked', checked);
  190. }
  191. function loadSettings() {
  192. wwSettings = $.parseJSON(localStorage.getItem("_wazewrap_settings"));
  193. let _defaultsettings = {
  194. showAlertHistoryIcon: true,
  195. editorPIN: ""
  196. };
  197. wwSettings = $.extend({}, _defaultsettings, wwSettings);
  198. }
  199. function saveSettings() {
  200. if (localStorage) {
  201. let settings = {
  202. showAlertHistoryIcon: wwSettings.showAlertHistoryIcon,
  203. editorPIN: wwSettings.editorPIN
  204. };
  205. localStorage.setItem("_wazewrap_settings", JSON.stringify(settings));
  206. }
  207. }
  208.  
  209. async function initializeToastr() {
  210. let toastrSettings = {};
  211. try {
  212. function loadSettings() {
  213. var loadedSettings = $.parseJSON(localStorage.getItem("WWToastr"));
  214. var defaultSettings = {
  215. historyLeftLoc: 35,
  216. historyTopLoc: 40
  217. };
  218. toastrSettings = $.extend({}, defaultSettings, loadedSettings)
  219. }
  220.  
  221. function saveSettings() {
  222. if (localStorage) {
  223. var localsettings = {
  224. historyLeftLoc: toastrSettings.historyLeftLoc,
  225. historyTopLoc: toastrSettings.historyTopLoc
  226. };
  227.  
  228. localStorage.setItem("WWToastr", JSON.stringify(localsettings));
  229. }
  230. }
  231. loadSettings();
  232. $('head').append(
  233. $('<link/>', {
  234. rel: 'stylesheet',
  235. type: 'text/css',
  236. href: 'https://cdn.statically.io/gh/WazeDev/toastr/master/build/toastr.min.css'
  237. }),
  238. $('<style type="text/css">.toast-container-wazedev > div {opacity: 0.95;} .toast-top-center-wide {top: 32px;}</style>')
  239. );
  240.  
  241. await $.getScript('https://cdn.statically.io/gh/WazeDev/toastr/master/build/toastr.min.js');
  242. wazedevtoastr.options = {
  243. target: '#map',
  244. timeOut: 6000,
  245. positionClass: 'toast-top-center-wide',
  246. closeOnHover: false,
  247. closeDuration: 0,
  248. showDuration: 0,
  249. closeButton: true,
  250. progressBar: true
  251. };
  252.  
  253. if ($('.WWAlertsHistory').length > 0)
  254. return;
  255. var $sectionToastr = $("<div>", { style: "padding:8px 16px", id: "wmeWWScriptUpdates" });
  256. $sectionToastr.html([
  257. '<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>'
  258. ].join(' '));
  259. $("#WazeMap").append($sectionToastr.html());
  260.  
  261. $('.WWAlertsHistory').css('left', `${toastrSettings.historyLeftLoc}px`);
  262. $('.WWAlertsHistory').css('top', `${toastrSettings.historyTopLoc}px`);
  263.  
  264. try {
  265. await $.getScript("https://greasyfork.org/scripts/454988-jqueryui-custom-build/code/jQueryUI%20custom%20build.js");
  266. }
  267. catch (err) {
  268. console.log("Could not load jQuery UI " + err);
  269. }
  270.  
  271. if ($.ui) {
  272. $('.WWAlertsHistory').draggable({
  273. stop: function () {
  274. let windowWidth = $('#map').width();
  275. let panelWidth = $('#WWAlertsHistory-list').width();
  276. let historyLoc = $('.WWAlertsHistory').position().left;
  277. if ((panelWidth + historyLoc) > windowWidth) {
  278. $('#WWAlertsHistory-list').css('left', Math.abs(windowWidth - (historyLoc + $('.WWAlertsHistory').width()) - panelWidth) * -1);
  279. }
  280. else
  281. $('#WWAlertsHistory-list').css('left', 'auto');
  282.  
  283. toastrSettings.historyLeftLoc = $('.WWAlertsHistory').position().left;
  284. toastrSettings.historyTopLoc = $('.WWAlertsHistory').position().top;
  285. saveSettings();
  286. }
  287. });
  288. }
  289. }
  290. catch (err) {
  291. console.log(err);
  292. }
  293. }
  294.  
  295. function initializeScriptUpdateInterface() {
  296. console.log("creating script update interface");
  297. injectCSS();
  298. var $section = $("<div>", { style: "padding:8px 16px", id: "wmeWWScriptUpdates" });
  299. $section.html([
  300. '<div id="WWSU-Container" class="fa" style="position:fixed; top:20%; left:40%; z-index:1000; display:none;">',
  301. '<div id="WWSU-Close" class="fa-close fa-lg"></div>',
  302. '<div class="modal-heading">',
  303. '<h2>Script Updates</h2>',
  304. '<h4><span id="WWSU-updateCount">0</span> of your scripts have updates</h4>',
  305. '</div>',
  306. '<div class="WWSU-updates-wrapper">',
  307. '<div id="WWSU-script-list">',
  308. '</div>',
  309. '<div id="WWSU-script-update-info">',
  310. '</div></div></div>'
  311. ].join(' '));
  312. $("#WazeMap").append($section.html());
  313.  
  314. $('#WWSU-Close').click(function () {
  315. $('#WWSU-Container').hide();
  316. });
  317.  
  318. $(document).on('click', '.WWSU-script-item', function () {
  319. $('.WWSU-script-item').removeClass("WWSU-active");
  320. $(this).addClass("WWSU-active");
  321. });
  322. }
  323.  
  324. function injectCSS() {
  325. let css = [
  326. '#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; }',
  327. '#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;}',
  328. '#WWSU-Container .modal-heading,.WWSU-updates-wrapper { font-family: "Helvetica Neue", Helvetica, "Open Sans", sans-serif; } ',
  329. '.WWSU-updates-wrapper { height:350px; }',
  330. '#WWSU-script-list { float:left; width:175px; height:100%; padding-right:6px; margin-right:10px; overflow-y: auto; overflow-x: hidden; height:300px; }',
  331. '.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;}',
  332. '.WWSU-script-item:hover { text-decoration: none; }',
  333. '.WWSU-active { transform: translate3d(5px, 0px, 0px); box-shadow: rgba(0, 0, 0, 0.4) 0px 3px 7px 0px; }',
  334. '#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;}',
  335. '#WWSU-script-update-info div { display: none;}',
  336. '#WWSU-script-update-info div:target { display: block; }',
  337. `.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;}`,
  338. '.WWAlertsHistory:hover #WWAlertsHistory-list{display:block;}',
  339. '.WWAlertsHistory > .fa-exclamation-triangle {position: absolute; left:50%; margin-left:-9px; margin-top:8px;}',
  340. '#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;}',
  341. '#WWAlertsHistory-list #toast-container-history > div {max-width:500px; min-width:500px; border-radius:10px;}',
  342. '#WWAlertsHistory-list > #toast-container-history{ position:static; }'
  343. ].join(' ');
  344. $('<style type="text/css">' + css + '</style>').appendTo('head');
  345. }
  346. function RestoreMissingWRule(){
  347. if(!W.Rule){
  348. W.Rule = OpenLayers.Class(OpenLayers.Rule, {
  349. getContext(feature) {
  350. return feature;
  351. },
  352.  
  353. CLASS_NAME: "Waze.Rule"
  354. });
  355. }
  356. }
  357.  
  358. function RestoreMissingSegmentFunctions() {
  359. if (W.model.segments.getObjectArray().length > 0) {
  360. wEvents.unregister("moveend", this, RestoreMissingSegmentFunctions);
  361. wEvents.unregister("zoomend", this, RestoreMissingSegmentFunctions);
  362. if (typeof W.model.segments.getObjectArray()[0].model.getDirection == "undefined")
  363. W.model.segments.getObjectArray()[0].__proto__.getDirection = function () { return (this.attributes.fwdDirection ? 1 : 0) + (this.attributes.revDirection ? 2 : 0); };
  364. if (typeof W.model.segments.getObjectArray()[0].model.isTollRoad == "undefined")
  365. W.model.segments.getObjectArray()[0].__proto__.isTollRoad = function () { return (this.attributes.fwdToll || this.attributes.revToll); };
  366. if (typeof W.model.segments.getObjectArray()[0].isLockedByHigherRank == "undefined")
  367. W.model.segments.getObjectArray()[0].__proto__.isLockedByHigherRank = function () { return !(!this.attributes.lockRank || !this.model.loginManager.isLoggedIn()) && this.getLockRank() > this.model.loginManager.user.getRank(); };
  368. if (typeof W.model.segments.getObjectArray()[0].isDrivable == "undefined")
  369. W.model.segments.getObjectArray()[0].__proto__.isDrivable = function () { let V = [5, 10, 16, 18, 19]; return !V.includes(this.attributes.roadType); };
  370. if (typeof W.model.segments.getObjectArray()[0].isWalkingRoadType == "undefined")
  371. W.model.segments.getObjectArray()[0].__proto__.isWalkingRoadType = function () { let x = [5, 10, 16]; return x.includes(this.attributes.roadType); };
  372. if (typeof W.model.segments.getObjectArray()[0].isRoutable == "undefined")
  373. W.model.segments.getObjectArray()[0].__proto__.isRoutable = function () { let P = [1, 2, 7, 6, 3]; return P.includes(this.attributes.roadType); };
  374. if (typeof W.model.segments.getObjectArray()[0].isInBigJunction == "undefined")
  375. W.model.segments.getObjectArray()[0].__proto__.isInBigJunction = function () { return this.isBigJunctionShort() || this.hasFromBigJunction() || this.hasToBigJunction(); };
  376. if (typeof W.model.segments.getObjectArray()[0].isBigJunctionShort == "undefined")
  377. W.model.segments.getObjectArray()[0].__proto__.isBigJunctionShort = function () { return null != this.attributes.crossroadID; };
  378. if (typeof W.model.segments.getObjectArray()[0].hasFromBigJunction == "undefined")
  379. W.model.segments.getObjectArray()[0].__proto__.hasFromBigJunction = function (e) { return null != e ? this.attributes.fromCrossroads.includes(e) : this.attributes.fromCrossroads.length > 0; };
  380. if (typeof W.model.segments.getObjectArray()[0].hasToBigJunction == "undefined")
  381. W.model.segments.getObjectArray()[0].__proto__.hasToBigJunction = function (e) { return null != e ? this.attributes.toCrossroads.includes(e) : this.attributes.toCrossroads.length > 0; };
  382. if (typeof W.model.segments.getObjectArray()[0].getRoundabout == "undefined")
  383. W.model.segments.getObjectArray()[0].__proto__.getRoundabout = function () { return this.isInRoundabout() ? this.model.junctions.getObjectById(this.attributes.junctionID) : null; };
  384. }
  385. }
  386.  
  387. function RestoreMissingNodeFunctions() {
  388. if (W.model.nodes.getObjectArray().length > 0) {
  389. wEvents.unregister("moveend", this, RestoreMissingNodeFunctions);
  390. wEvents.unregister("zoomend", this, RestoreMissingNodeFunctions);
  391. if (typeof W.model.nodes.getObjectArray()[0].areConnectionsEditable == "undefined")
  392. 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(); }); };
  393. }
  394. }
  395. /* jshint ignore:start */
  396. function RestoreMissingOLKMLSupport() {
  397. if (!OpenLayers.Format.KML) {
  398. OpenLayers.Format.KML = OpenLayers.Class(OpenLayers.Format.XML, {
  399. 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) {
  400. this.regExes =
  401. { 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])
  402. }, read: function (a) { this.features = []; this.styles = {}; this.fetched = {}; return this.parseData(a, { depth: 0, styleBaseUrl: this.styleBaseUrl }) }, parseData: function (a, b) {
  403. "string" == typeof a &&
  404. (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
  405. }, parseLinks: function (a,
  406. 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) {
  407. var b =
  408. null; a && (a = a.match(this.regExes.kmlColor)) && (b = { color: "#" + a[4] + a[3] + a[2], opacity: parseInt(a[1], 16) / 255 }); return b
  409. }, parseStyle: function (a) {
  410. 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()) {
  411. 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 =
  412. 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) {
  413. var k = this.parseProperty(j, "*", "href"); if (k) {
  414. var l = this.parseProperty(j, "*", "w"), m = this.parseProperty(j,
  415. "*", "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
  416. }
  417. } if (e = this.getElementsByTagNameNS(e, "*", "hotSpot")[0]) k = parseFloat(e.getAttribute("x")), j = parseFloat(e.getAttribute("y")),
  418. 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,
  419. "*", "color"), d = this.parseKmlColor(d)) b.fontColor = d.color, b.fontOpacity = d.opacity
  420. }!b.strokeColor && b.fillColor && (b.strokeColor = b.fillColor); if ((a = a.getAttribute("id")) && b) b.id = a; return b
  421. }, parseStyleMaps: function (a, b) {
  422. 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++) {
  423. 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 ||
  424. "") + i])
  425. }
  426. }, parseFeatures: function (a, b) {
  427. for (var c = [], d = 0, e = a.length; d < e; d++) {
  428. var f = a[d], g = this.parseFeature.apply(this, [f]); if (g) {
  429. 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) {
  430. if ((f = this.getElementsByTagNameNS(f, this.namespaces.gx, "Track")) && 0 < f.length) g = { features: [], feature: g },
  431. this.readNode(f[0], g), 0 < g.features.length && c.push.apply(c, g.features)
  432. } else c.push(g)
  433. } else throw "Bad Placemark: " + d;
  434. } this.features = this.features.concat(c)
  435. }, readers: {
  436. 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: {
  437. Track: function (a, b) {
  438. var c = { whens: [], points: [], angles: [] }; if (this.trackAttributes) {
  439. var d; c.attributes = {}; for (var e = 0, f = this.trackAttributes.length; e <
  440. f; ++e)d = this.trackAttributes[e], c.attributes[d] = [], d in this.readers.kml || (this.readers.kml[d] = this.readers.kml._trackPointAttribute)
  441. } 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,
  442. i, e = 0, f = c.whens.length; e < f; ++e) {
  443. 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 =
  444. parseFloat(i[0]), h.attributes.tilt = parseFloat(i[1]), h.attributes.roll = parseFloat(i[2])); b.features.push(h)
  445. }
  446. }, 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) }
  447. }
  448. }, parseFeature: function (a) {
  449. for (var b = ["MultiGeometry", "Polygon", "LineString", "Point"],
  450. 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") ||
  451. a.getAttribute("name"); null != a && (c.fid = a); return c
  452. }, 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: {
  453. point: function (a) {
  454. var b = this.getElementsByTagNameNS(a, this.internalns, "coordinates"), a = []; if (0 < b.length) var c = b[0].firstChild.nodeValue,
  455. 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
  456. }, linestring: function (a, b) {
  457. var c = this.getElementsByTagNameNS(a, this.internalns, "coordinates"), d = null; if (0 < c.length) {
  458. 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 =
  459. 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;
  460. } return d
  461. }, polygon: function (a) {
  462. 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] =
  463. b; else throw "Bad LinearRing geometry: " + d; return new OpenLayers.Geometry.Polygon(c)
  464. }, 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) }
  465. }, parseAttributes: function (a) {
  466. var b = {}, c = a.getElementsByTagName("ExtendedData"); c.length && (b = this.parseExtendedData(c[0])); for (var d, e, f, a = a.childNodes, c = 0, g =
  467. 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
  468. }, parseExtendedData: function (a) {
  469. var b = {}, c, d, e, f, g = a.getElementsByTagName("Data"); c = 0; for (d = g.length; c < d; c++) {
  470. e = g[c]; f = e.getAttribute("name");
  471. 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)
  472. } 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
  473. }, parseProperty: function (a, b, c) {
  474. var d, a = this.getElementsByTagNameNS(a, b, c); try { d = OpenLayers.Util.getXmlNodeValue(a[0]) } catch (e) {
  475. d =
  476. null
  477. } return d
  478. }, 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 () {
  479. 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 &&
  480. (b = this.createElementNS(this.kmlns, "description"), c = this.createTextNode(this.foldersDesc), b.appendChild(c), a.appendChild(b)); return a
  481. }, createPlacemarkXML: function (a) {
  482. 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 !=
  483. 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
  484. }, 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: {
  485. point: function (a) { var b = this.createElementNS(this.kmlns, "Point"); b.appendChild(this.buildCoordinatesNode(a)); return b }, multipoint: function (a) {
  486. return this.buildGeometry.collection.apply(this,
  487. [a])
  488. }, 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) {
  489. 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",
  490. c = this.createElementNS(this.kmlns, c), d = this.buildGeometry.linearring.apply(this, [a[e]]), c.appendChild(d), b.appendChild(c); return b
  491. }, 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 }
  492. }, buildCoordinatesNode: function (a) {
  493. var b = this.createElementNS(this.kmlns, "coordinates"),
  494. 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
  495. }, buildCoordinates: function (a) { this.internalProjection && this.externalProjection && (a = a.clone(), a.transform(this.internalProjection, this.externalProjection)); return a.x + "," + a.y }, buildExtendedData: function (a) {
  496. var b = this.createElementNS(this.kmlns, "ExtendedData"), c; for (c in a) if (a[c] && "name" != c && "description" !=
  497. 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
  498. },
  499. CLASS_NAME: "OpenLayers.Format.KML"
  500. });
  501. }
  502. }
  503. /* jshint ignore:end */
  504. function Geometry() {
  505. //Converts to "normal" GPS coordinates
  506. this.ConvertTo4326 = function (lon, lat) {
  507. let projI = new OpenLayers.Projection("EPSG:900913");
  508. let projE = new OpenLayers.Projection("EPSG:4326");
  509. return (new OpenLayers.LonLat(lon, lat)).transform(projI, projE);
  510. };
  511.  
  512. this.ConvertTo900913 = function (lon, lat) {
  513. let projI = new OpenLayers.Projection("EPSG:900913");
  514. let projE = new OpenLayers.Projection("EPSG:4326");
  515. return (new OpenLayers.LonLat(lon, lat)).transform(projE, projI);
  516. };
  517.  
  518. //Converts the Longitudinal offset to an offset in 4326 gps coordinates
  519. this.CalculateLongOffsetGPS = function (longMetersOffset, lon, lat) {
  520. let R = 6378137; //Earth's radius
  521. let dLon = longMetersOffset / (R * Math.cos(Math.PI * lat / 180)); //offset in radians
  522. let lon0 = dLon * (180 / Math.PI); //offset degrees
  523.  
  524. return lon0;
  525. };
  526.  
  527. //Converts the Latitudinal offset to an offset in 4326 gps coordinates
  528. this.CalculateLatOffsetGPS = function (latMetersOffset, lat) {
  529. let R = 6378137; //Earth's radius
  530. let dLat = latMetersOffset / R;
  531. let lat0 = dLat * (180 / Math.PI); //offset degrees
  532.  
  533. return lat0;
  534. };
  535.  
  536. /**
  537. * Checks if the given lon & lat
  538. * @function WazeWrap.Geometry.isGeometryInMapExtent
  539. * @param {lon, lat} object
  540. */
  541. this.isLonLatInMapExtent = function (lonLat) {
  542. return lonLat && W.map.getExtent().containsLonLat(lonLat);
  543. };
  544.  
  545. /**
  546. * Checks if the given geometry point is on screen
  547. * @function WazeWrap.Geometry.isGeometryInMapExtent
  548. * @param {OpenLayers.Geometry.Point} Geometry Point we are checking if it is in the extent
  549. */
  550. this.isGeometryInMapExtent = function (geometry) {
  551. return geometry && geometry.getBounds &&
  552. W.map.getExtent().intersectsBounds(geometry.getBounds());
  553. };
  554.  
  555. /**
  556. * Calculates the distance between given points, returned in meters
  557. * @function WazeWrap.Geometry.calculateDistance
  558. * @param {OpenLayers.Geometry.Point} An array of OpenLayers.Geometry.Point with which to measure the total distance. A minimum of 2 points is needed.
  559. */
  560. this.calculateDistance = function (pointArray) {
  561. if (pointArray.length < 2)
  562. return 0;
  563.  
  564. let line = new OpenLayers.Geometry.LineString(pointArray);
  565. let length = line.getGeodesicLength(W.map.getProjectionObject());
  566. return length; //multiply by 3.28084 to convert to feet
  567. };
  568.  
  569. /**
  570. * Finds the closest on-screen drivable segment to the given point, ignoring PLR and PR segments if the options are set
  571. * @function WazeWrap.Geometry.findClosestSegment
  572. * @param {OpenLayers.Geometry.Point} The given point to find the closest segment to
  573. * @param {boolean} If true, Parking Lot Road segments will be ignored when finding the closest segment
  574. * @param {boolean} If true, Private Road segments will be ignored when finding the closest segment
  575. **/
  576. this.findClosestSegment = function (mygeometry, ignorePLR, ignoreUnnamedPR) {
  577. let onscreenSegments = WazeWrap.Model.getOnscreenSegments();
  578. let minDistance = Infinity;
  579. let closestSegment;
  580.  
  581. for (var s in onscreenSegments) {
  582. if (!onscreenSegments.hasOwnProperty(s))
  583. continue;
  584.  
  585. let segmentType = onscreenSegments[s].attributes.roadType;
  586. if (segmentType === 10 || segmentType === 16 || segmentType === 18 || segmentType === 19) //10 ped boardwalk, 16 stairway, 18 railroad, 19 runway, 3 freeway
  587. continue;
  588.  
  589. if (ignorePLR && segmentType === 20) //PLR
  590. continue;
  591.  
  592. if (ignoreUnnamedPR && segmentType === 17) {
  593. var nm = WazeWrap.Model.getStreetName(onscreenSegments[s].attributes.primaryStreetID);
  594. if (nm === null || nm == "") //PR
  595. continue;
  596. }
  597.  
  598. let distanceToSegment = mygeometry.distanceTo(onscreenSegments[s].getOLGeometry(), { details: true });
  599.  
  600. if (distanceToSegment.distance < minDistance) {
  601. minDistance = distanceToSegment.distance;
  602. closestSegment = onscreenSegments[s];
  603. closestSegment.closestPoint = new OpenLayers.Geometry.Point(distanceToSegment.x1, distanceToSegment.y1);
  604. }
  605. }
  606. return closestSegment;
  607. };
  608. }
  609.  
  610. function Model() {
  611.  
  612. this.getPrimaryStreetID = function (segmentID) {
  613. return W.model.segments.getObjectById(segmentID).attributes.primaryStreetID;
  614. };
  615.  
  616. this.getStreetName = function (primaryStreetID) {
  617. return W.model.streets.getObjectById(primaryStreetID).attributes.name;
  618. };
  619.  
  620. this.getCityID = function (primaryStreetID) {
  621. return W.model.streets.getObjectById(primaryStreetID).attributes.cityID;
  622. };
  623.  
  624. this.getCityName = function (primaryStreetID) {
  625. return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.name;
  626. };
  627.  
  628. this.getStateName = function (primaryStreetID) {
  629. return W.model.states.getObjectById(this.getStateID(primaryStreetID)).attributes.name;
  630. };
  631.  
  632. this.getStateID = function (primaryStreetID) {
  633. return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.stateID;
  634. };
  635.  
  636. this.getCountryID = function (primaryStreetID) {
  637. return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.CountryID;
  638. };
  639.  
  640. this.getCountryName = function (primaryStreetID) {
  641. return W.model.countries.getObjectById(this.getCountryID(primaryStreetID)).attributes.name;
  642. };
  643.  
  644. this.getCityNameFromSegmentObj = function (segObj) {
  645. return this.getCityName(segObj.attributes.primaryStreetID);
  646. };
  647.  
  648. this.getStateNameFromSegmentObj = function (segObj) {
  649. return this.getStateName(segObj.attributes.primaryStreetID);
  650. };
  651. this.getObjectModel = function (obj){
  652. return obj?.attributes?.wazeFeature?._wmeObject;
  653. };
  654.  
  655. /**
  656. * Returns an array of segment IDs for all segments that make up the roundabout the given segment is part of
  657. * @function WazeWrap.Model.getAllRoundaboutSegmentsFromObj
  658. * @param {Segment object (Waze/Feature/Vector/Segment)} The roundabout segment
  659. **/
  660. this.getAllRoundaboutSegmentsFromObj = function (segObj) {
  661. let modelObj = {};
  662. if(typeof WazeWrap.getSelectedFeatures()[0].WW !== 'undefined')
  663. modelObj = segObj.WW.getObjectModel();
  664. else
  665. modelObj = segObj.attributes.wazeFeature._wmeObject;
  666. if (modelObj.attributes.junctionID === null)
  667. return null;
  668.  
  669. return W.model.junctions.objects[modelObj.attributes.junctionID].attributes.segIDs;
  670. };
  671.  
  672. /**
  673. * Returns an array of all junction nodes that make up the roundabout
  674. * @function WazeWrap.Model.getAllRoundaboutJunctionNodesFromObj
  675. * @param {Segment object (Waze/Feature/Vector/Segment)} The roundabout segment
  676. **/
  677. this.getAllRoundaboutJunctionNodesFromObj = function (segObj) {
  678. let RASegs = this.getAllRoundaboutSegmentsFromObj(segObj);
  679. let RAJunctionNodes = [];
  680. for (i = 0; i < RASegs.length; i++)
  681. RAJunctionNodes.push(W.model.nodes.objects[W.model.segments.getObjectById(RASegs[i]).attributes.toNodeID]);
  682.  
  683. return RAJunctionNodes;
  684. };
  685.  
  686. /**
  687. * Checks if the given segment ID is a part of a roundabout
  688. * @function WazeWrap.Model.isRoundaboutSegmentID
  689. * @param {integer} The segment ID to check
  690. **/
  691. this.isRoundaboutSegmentID = function (segmentID) {
  692. return W.model.segments.getObjectById(segmentID).attributes.junctionID !== null
  693. };
  694.  
  695. /**
  696. * Checks if the given segment object is a part of a roundabout
  697. * @function WazeWrap.Model.isRoundaboutSegmentID
  698. * @param {Segment object (Waze/Feature/Vector/Segment)} The segment object to check
  699. **/
  700. this.isRoundaboutSegmentObj = function (segObj) {
  701. let modelObj = {};
  702. if(typeof WazeWrap.getSelectedFeatures()[0].WW !== 'undefined')
  703. modelObj = segObj.WW.getObjectModel();
  704. else
  705. modelObj = segObj.attributes.wazeFeature._wmeObject;
  706. return modelObj.attributes.junctionID !== null;
  707. };
  708.  
  709. /**
  710. * Returns an array of all segments in the current extent
  711. * @function WazeWrap.Model.getOnscreenSegments
  712. **/
  713. this.getOnscreenSegments = function () {
  714. let segments = W.model.segments.objects;
  715. let mapExtent = W.map.getExtent();
  716. let onScreenSegments = [];
  717. let seg;
  718.  
  719. for (var s in segments) {
  720. if (!segments.hasOwnProperty(s))
  721. continue;
  722.  
  723. seg = W.model.segments.getObjectById(s);
  724. if (mapExtent.intersectsBounds(seg.getOLGeometry().getBounds()))
  725. onScreenSegments.push(seg);
  726. }
  727. return onScreenSegments;
  728. };
  729.  
  730. /**
  731. * Defers execution of a callback function until the WME map and data
  732. * model are ready. Call this function before calling a function that
  733. * causes a map and model reload, such as W.map.moveTo(). After the
  734. * move is completed the callback function will be executed.
  735. * @function WazeWrap.Model.onModelReady
  736. * @param {Function} callback The callback function to be executed.
  737. * @param {Boolean} now Whether or not to call the callback now if the
  738. * model is currently ready.
  739. * @param {Object} context The context in which to call the callback.
  740. */
  741. this.onModelReady = function (callback, now, context) {
  742. var deferModelReady = function () {
  743. return $.Deferred(function (dfd) {
  744. var resolve = function () {
  745. dfd.resolve();
  746. W.model.events.unregister('mergeend', null, resolve);
  747. };
  748. W.model.events.register('mergeend', null, resolve);
  749. }).promise();
  750. };
  751. var deferMapReady = function () {
  752. return $.Deferred(function (dfd) {
  753. var resolve = function () {
  754. dfd.resolve();
  755. W.app.layout.model.off('operationDone', resolve);
  756. };
  757. W.app.layout.model.on('operationDone', resolve);
  758. }).promise();
  759. };
  760.  
  761. if (typeof callback === 'function') {
  762. context = context || callback;
  763. if (now && WazeWrap.Util.mapReady() && WazeWrap.Util.modelReady()) {
  764. callback.call(context);
  765. } else {
  766. $.when(deferMapReady() && deferModelReady()).
  767. then(function () {
  768. callback.call(context);
  769. });
  770. }
  771. }
  772. };
  773.  
  774. /**
  775. * Retrives a route from the Waze Live Map.
  776. * @class
  777. * @name WazeWrap.Model.RouteSelection
  778. * @param firstSegment The segment to use as the start of the route.
  779. * @param lastSegment The segment to use as the destination for the route.
  780. * @param {Array|Function} callback A function or array of funcitons to be
  781. * executed after the route
  782. * is retrieved. 'This' in the callback functions will refer to the
  783. * RouteSelection object.
  784. * @param {Object} options A hash of options for determining route. Valid
  785. * options are:
  786. * fastest: {Boolean} Whether or not the fastest route should be used.
  787. * Default is false, which selects the shortest route.
  788. * freeways: {Boolean} Whether or not to avoid freeways. Default is false.
  789. * dirt: {Boolean} Whether or not to avoid dirt roads. Default is false.
  790. * longtrails: {Boolean} Whether or not to avoid long dirt roads. Default
  791. * is false.
  792. * uturns: {Boolean} Whether or not to allow U-turns. Default is true.
  793. * @return {WazeWrap.Model.RouteSelection} The new RouteSelection object.
  794. * @example: // The following example will retrieve a route from the Live Map and select the segments in the route.
  795. * selection = W.selectionManager.selectedItems;
  796. * myRoute = new WazeWrap.Model.RouteSelection(selection[0], selection[1], function(){this.selectRouteSegments();}, {fastest: true});
  797. */
  798. this.RouteSelection = function (firstSegment, lastSegment, callback, options) {
  799. var i,
  800. n,
  801. start = this.getSegmentCenterLonLat(firstSegment),
  802. end = this.getSegmentCenterLonLat(lastSegment);
  803. this.options = {
  804. fastest: options && options.fastest || false,
  805. freeways: options && options.freeways || false,
  806. dirt: options && options.dirt || false,
  807. longtrails: options && options.longtrails || false,
  808. uturns: options && options.uturns || true
  809. };
  810. this.requestData = {
  811. from: 'x:' + start.x + ' y:' + start.y + ' bd:true',
  812. to: 'x:' + end.x + ' y:' + end.y + ' bd:true',
  813. returnJSON: true,
  814. returnGeometries: true,
  815. returnInstructions: false,
  816. type: this.options.fastest ? 'HISTORIC_TIME' : 'DISTANCE',
  817. clientVersion: '4.0.0',
  818. timeout: 60000,
  819. nPaths: 3,
  820. options: this.setRequestOptions(this.options)
  821. };
  822. this.callbacks = [];
  823. if (callback) {
  824. if (!(callback instanceof Array)) {
  825. callback = [callback];
  826. }
  827. for (i = 0, n = callback.length; i < n; i++) {
  828. if ('function' === typeof callback[i]) {
  829. this.callbacks.push(callback[i]);
  830. }
  831. }
  832. }
  833. this.routeData = null;
  834. this.getRouteData();
  835. };
  836.  
  837. this.RouteSelection.prototype =
  838. /** @lends WazeWrap.Model.RouteSelection.prototype */ {
  839.  
  840. /**
  841. * Formats the routing options string for the ajax request.
  842. * @private
  843. * @param {Object} options Object containing the routing options.
  844. * @return {String} String containing routing options.
  845. */
  846. setRequestOptions: function (options) {
  847. return 'AVOID_TOLL_ROADS:' + (options.tolls ? 't' : 'f') + ',' +
  848. 'AVOID_PRIMARIES:' + (options.freeways ? 't' : 'f') + ',' +
  849. 'AVOID_TRAILS:' + (options.dirt ? 't' : 'f') + ',' +
  850. 'AVOID_LONG_TRAILS:' + (options.longtrails ? 't' : 'f') + ',' +
  851. 'ALLOW_UTURNS:' + (options.uturns ? 't' : 'f');
  852. },
  853.  
  854. /**
  855. * Gets the center of a segment in LonLat form.
  856. * @private
  857. * @param segment A Waze model segment object.
  858. * @return {OpenLayers.LonLat} The LonLat object corresponding to the
  859. * center of the segment.
  860. */
  861. getSegmentCenterLonLat: function (segment) {
  862. var x, y, componentsLength, midPoint;
  863. if (segment) {
  864. componentsLength = segment.getOLGeometry().components.length;
  865. midPoint = Math.floor(componentsLength / 2);
  866. if (componentsLength % 2 === 1) {
  867. x = segment.getOLGeometry().components[midPoint].x;
  868. y = segment.getOLGeometry().components[midPoint].y;
  869. } else {
  870. x = (segment.getOLGeometry().components[midPoint - 1].x +
  871. segment.getOLGeometry().components[midPoint].x) / 2;
  872. y = (segment.getOLGeometry().components[midPoint - 1].y +
  873. segment.getOLGeometry().components[midPoint].y) / 2;
  874. }
  875. return new OpenLayers.Geometry.Point(x, y).
  876. transform(W.map.getProjectionObject(), 'EPSG:4326');
  877. }
  878.  
  879. },
  880.  
  881. /**
  882. * Gets the route from Live Map and executes any callbacks upon success.
  883. * @private
  884. * @returns The ajax request object. The responseJSON property of the
  885. * returned object
  886. * contains the route information.
  887. *
  888. */
  889. getRouteData: function () {
  890. var i,
  891. n,
  892. that = this;
  893. return $.ajax({
  894. dataType: 'json',
  895. url: this.getURL(),
  896. data: this.requestData,
  897. dataFilter: function (data, dataType) {
  898. return data.replace(/NaN/g, '0');
  899. },
  900. success: function (data) {
  901. that.routeData = data;
  902. for (i = 0, n = that.callbacks.length; i < n; i++) {
  903. that.callbacks[i].call(that);
  904. }
  905. }
  906. });
  907. },
  908.  
  909. /**
  910. * Extracts the IDs from all segments on the route.
  911. * @private
  912. * @return {Array} Array containing an array of segment IDs for
  913. * each route alternative.
  914. */
  915. getRouteSegmentIDs: function () {
  916. var i, j, route, len1, len2, segIDs = [],
  917. routeArray = [],
  918. data = this.routeData;
  919. if ('undefined' !== typeof data.alternatives) {
  920. for (i = 0, len1 = data.alternatives.length; i < len1; i++) {
  921. route = data.alternatives[i].response.results;
  922. for (j = 0, len2 = route.length; j < len2; j++) {
  923. routeArray.push(route[j].path.segmentId);
  924. }
  925. segIDs.push(routeArray);
  926. routeArray = [];
  927. }
  928. } else {
  929. route = data.response.results;
  930. for (i = 0, len1 = route.length; i < len1; i++) {
  931. routeArray.push(route[i].path.segmentId);
  932. }
  933. segIDs.push(routeArray);
  934. }
  935. return segIDs;
  936. },
  937.  
  938. /**
  939. * Gets the URL to use for the ajax request based on country.
  940. * @private
  941. * @return {String} Relative URl to use for route ajax request.
  942. */
  943. getURL: function () {
  944. if (W.model.countries.getObjectById(235) || W.model.countries.getObjectById(40)) {
  945. return '/RoutingManager/routingRequest';
  946. } else if (W.model.countries.getObjectById(106)) {
  947. return '/il-RoutingManager/routingRequest';
  948. } else {
  949. return '/row-RoutingManager/routingRequest';
  950. }
  951. },
  952.  
  953. /**
  954. * Selects all segments on the route in the editor.
  955. * @param {Integer} routeIndex The index of the alternate route.
  956. * Default route to use is the first one, which is 0.
  957. */
  958. selectRouteSegments: function (routeIndex) {
  959. var i, n, seg,
  960. segIDs = this.getRouteSegmentIDs()[Math.floor(routeIndex) || 0],
  961. segments = [];
  962. if ('undefined' === typeof segIDs) {
  963. return;
  964. }
  965. for (i = 0, n = segIDs.length; i < n; i++) {
  966. seg = W.model.segments.getObjectById(segIDs[i]);
  967. if ('undefined' !== seg) {
  968. segments.push(seg);
  969. }
  970. }
  971. return WazeWrap.selectFeatures(segments);
  972. }
  973. };
  974. }
  975.  
  976. function User() {
  977. /**
  978. * Returns the "normalized" (1 based) user rank/level
  979. */
  980. this.Rank = function () {
  981. return W.loginManager.user.getRank() + 1;
  982. };
  983.  
  984. /**
  985. * Returns the current user's username
  986. */
  987. this.Username = function () {
  988. return W.loginManager.user.getUsername();
  989. };
  990.  
  991. /**
  992. * Returns if the user is a CM (in any country)
  993. */
  994. this.isCM = function () {
  995. // Temporary fix for WME change. Going forward, the property will be under attributes.
  996. if (W.loginManager.user.editableCountryIDs) {
  997. return W.loginManager.user.editableCountryIDs.length > 0;
  998. }
  999. return W.loginManager.user.attributes.editableCountryIDs.length > 0
  1000. };
  1001.  
  1002. /**
  1003. * Returns if the user is an Area Manager (in any country)
  1004. */
  1005. this.isAM = function () {
  1006. // Temporary fix for WME change. Going forward, the property will be under attributes.
  1007. return W.loginManager.user.isAreaManager || W.loginManager.user.attributes.isAreaManager;
  1008. };
  1009. }
  1010.  
  1011. function Require() {
  1012. this.DragElement = function () {
  1013. var myDragElement = OpenLayers.Class({
  1014. started: !1,
  1015. stopDown: !0,
  1016. dragging: !1,
  1017. touch: !1,
  1018. last: null,
  1019. start: null,
  1020. lastMoveEvt: null,
  1021. oldOnselectstart: null,
  1022. interval: 0,
  1023. timeoutId: null,
  1024. forced: !1,
  1025. active: !1,
  1026. viewPortDiv: null,
  1027. initialize: function (e) {
  1028. this.map = e,
  1029. this.uniqueID = myDragElement.baseID--;
  1030. this.viewPortDiv = W.map.getViewport();
  1031. },
  1032. callback: function (e, t) {
  1033. if (this[e])
  1034. return this[e].apply(this, t)
  1035. },
  1036. dragstart: function (e) {
  1037. e.xy = new OpenLayers.Pixel(e.clientX - this.viewPortDiv.offsets[0], e.clientY - this.viewPortDiv.offsets[1]);
  1038. var t = !0;
  1039. return this.dragging = !1,
  1040. (OpenLayers.Event.isLeftClick(e) || OpenLayers.Event.isSingleTouch(e)) && (this.started = !0,
  1041. this.start = e.xy,
  1042. this.last = e.xy,
  1043. OpenLayers.Element.addClass(this.viewPortDiv, "olDragDown"),
  1044. this.down(e),
  1045. this.callback("down", [e.xy]),
  1046. OpenLayers.Event.stop(e),
  1047. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart ? document.onselectstart : OpenLayers.Function.True),
  1048. document.onselectstart = OpenLayers.Function.False,
  1049. t = !this.stopDown),
  1050. t
  1051. },
  1052. forceStart: function () {
  1053. var e = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
  1054. return this.started = !0,
  1055. this.endOnMouseUp = e,
  1056. this.forced = !0,
  1057. this.last = {
  1058. x: 0,
  1059. y: 0
  1060. },
  1061. this.callback("force")
  1062. },
  1063. forceEnd: function () {
  1064. if (this.forced)
  1065. return this.endDrag()
  1066. },
  1067. dragmove: function (e) {
  1068. return this.viewPortDiv.offsets && (e.xy = new OpenLayers.Pixel(e.clientX - this.viewPortDiv.offsets[0], e.clientY - this.viewPortDiv.offsets[1])),
  1069. this.lastMoveEvt = e,
  1070. !this.started || this.timeoutId || e.xy.x === this.last.x && e.xy.y === this.last.y || (this.interval > 0 && (this.timeoutId = window.setTimeout(OpenLayers.Function.bind(this.removeTimeout, this), this.interval)),
  1071. this.dragging = !0,
  1072. this.move(e),
  1073. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart,
  1074. document.onselectstart = OpenLayers.Function.False),
  1075. this.last = e.xy),
  1076. !0
  1077. },
  1078. dragend: function (e) {
  1079. if (e.xy = new OpenLayers.Pixel(e.clientX - this.viewPortDiv.offsets[0], e.clientY - this.viewPortDiv.offsets[1]),
  1080. this.started) {
  1081. var t = this.start !== this.last;
  1082. this.endDrag(),
  1083. this.up(e),
  1084. this.callback("up", [e.xy]),
  1085. t && this.callback("done", [e.xy])
  1086. }
  1087. return !0
  1088. },
  1089. endDrag: function () {
  1090. this.started = !1,
  1091. this.dragging = !1,
  1092. this.forced = !1,
  1093. OpenLayers.Element.removeClass(this.viewPortDiv, "olDragDown"),
  1094. document.onselectstart = this.oldOnselectstart
  1095. },
  1096. down: function (e) { },
  1097. move: function (e) { },
  1098. up: function (e) { },
  1099. out: function (e) { },
  1100. mousedown: function (e) {
  1101. return this.dragstart(e)
  1102. },
  1103. touchstart: function (e) {
  1104. return this.touch || (this.touch = !0,
  1105. this.map.events.un({
  1106. mousedown: this.mousedown,
  1107. mouseup: this.mouseup,
  1108. mousemove: this.mousemove,
  1109. click: this.click,
  1110. scope: this
  1111. })),
  1112. this.dragstart(e)
  1113. },
  1114. mousemove: function (e) {
  1115. return this.dragmove(e)
  1116. },
  1117. touchmove: function (e) {
  1118. return this.dragmove(e)
  1119. },
  1120. removeTimeout: function () {
  1121. if (this.timeoutId = null,
  1122. this.dragging)
  1123. return this.mousemove(this.lastMoveEvt)
  1124. },
  1125. mouseup: function (e) {
  1126. if (!this.forced || this.endOnMouseUp)
  1127. return this.started ? this.dragend(e) : void 0
  1128. },
  1129. touchend: function (e) {
  1130. if (e.xy = this.last,
  1131. !this.forced)
  1132. return this.dragend(e)
  1133. },
  1134. click: function (e) {
  1135. return this.start === this.last
  1136. },
  1137. activate: function (e) {
  1138. this.$el = e,
  1139. this.active = !0;
  1140. var t = $(this.viewPortDiv);
  1141. return this.$el.on("mousedown.drag-" + this.uniqueID, $.proxy(this.mousedown, this)),
  1142. this.$el.on("touchstart.drag-" + this.uniqueID, $.proxy(this.touchstart, this)),
  1143. t.on("mouseup.drag-" + this.uniqueID, $.proxy(this.mouseup, this)),
  1144. t.on("mousemove.drag-" + this.uniqueID, $.proxy(this.mousemove, this)),
  1145. t.on("touchmove.drag-" + this.uniqueID, $.proxy(this.touchmove, this)),
  1146. t.on("touchend.drag-" + this.uniqueID, $.proxy(this.touchend, this))
  1147. },
  1148. deactivate: function () {
  1149. return this.active = !1,
  1150. this.$el.off(".drag-" + this.uniqueID),
  1151. $(this.viewPortDiv).off(".drag-" + this.uniqueID),
  1152. this.touch = !1,
  1153. this.started = !1,
  1154. this.forced = !1,
  1155. this.dragging = !1,
  1156. this.start = null,
  1157. this.last = null,
  1158. OpenLayers.Element.removeClass(this.viewPortDiv, "olDragDown")
  1159. },
  1160. adjustXY: function (e) {
  1161. var t = OpenLayers.Util.pagePosition(this.viewPortDiv);
  1162. return e.xy.x -= t[0],
  1163. e.xy.y -= t[1]
  1164. },
  1165. CLASS_NAME: "W.Handler.DragElement"
  1166. });
  1167. myDragElement.baseID = 0;
  1168. return myDragElement;
  1169. };
  1170.  
  1171. this.DivIcon = OpenLayers.Class({
  1172. className: null,
  1173. $div: null,
  1174. events: null,
  1175. initialize: function (e, t) {
  1176. this.className = e,
  1177. this.moveWithTransform = !!t,
  1178. this.$div = $("<div />").addClass(e),
  1179. this.div = this.$div.get(0),
  1180. this.imageDiv = this.$div.get(0);
  1181. },
  1182. destroy: function () {
  1183. this.erase(),
  1184. this.$div = null;
  1185. },
  1186. clone: function () {
  1187. return new i(this.className);
  1188. },
  1189. draw: function (e) {
  1190. return this.moveWithTransform ? (this.$div.css({
  1191. transform: "translate(" + e.x + "px, " + e.y + "px)"
  1192. }),
  1193. this.$div.css({
  1194. position: "absolute"
  1195. })) : this.$div.css({
  1196. position: "absolute",
  1197. left: e.x,
  1198. top: e.y
  1199. }),
  1200. this.$div.get(0);
  1201. },
  1202. moveTo: function (e) {
  1203. null !== e && (this.px = e),
  1204. null === this.px ? this.display(!1) : this.moveWithTransform ? this.$div.css({
  1205. transform: "translate(" + this.px.x + "px, " + this.px.y + "px)"
  1206. }) : this.$div.css({
  1207. left: this.px.x,
  1208. top: this.px.y
  1209. });
  1210. },
  1211. erase: function () {
  1212. this.$div.remove();
  1213. },
  1214. display: function (e) {
  1215. this.$div.toggle(e);
  1216. },
  1217. isDrawn: function () {
  1218. return !!this.$div.parent().length;
  1219. },
  1220. bringToFront: function () {
  1221. if (this.isDrawn()) {
  1222. var e = this.$div.parent();
  1223. this.$div.detach().appendTo(e);
  1224. }
  1225. },
  1226. forceReflow: function () {
  1227. return this.$div.get(0).offsetWidth;
  1228. },
  1229. CLASS_NAME: "W.DivIcon"
  1230. });
  1231. this.Icon = OpenLayers.Class({
  1232. url: null,
  1233. size: null,
  1234. offset: null,
  1235. calculateOffset: null,
  1236. imageDiv: null,
  1237. px: null,
  1238. initialize: function(a,b,c,d){
  1239. this.url=a;
  1240. this.size=b||{w: 20,h: 20};
  1241. this.offset=c||{x: -(this.size.w/2),y: -(this.size.h/2)};
  1242. this.calculateOffset=d;
  1243. a = OpenLayers.Util.createUniqueID("OL_Icon_");
  1244. var div = this.imageDiv = OpenLayers.Util.createAlphaImageDiv(a);
  1245. $(div.firstChild).removeClass('olAlphaImg'); // LEAVE THIS LINE TO PREVENT WME-HARDHATS SCRIPT FROM TURNING ALL ICONS INTO HARDHAT WAZERS --MAPOMATIC
  1246. },
  1247. destroy: function(){ this.erase();OpenLayers.Event.stopObservingElement(this.imageDiv.firstChild);this.imageDiv.innerHTML="";this.imageDiv=null; },
  1248. clone: function(){ return new OpenLayers.Icon(this.url,this.size,this.offset,this.calculateOffset); },
  1249. setSize: function(a){ null!==a&&(this.size=a); this.draw(); },
  1250. setUrl: function(a){ null!==a&&(this.url=a); this.draw(); },
  1251. draw: function(a){
  1252. OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,this.size,this.url,"absolute");
  1253. this.moveTo(a);
  1254. return this.imageDiv;
  1255. },
  1256. erase: function(){ null!==this.imageDiv&&null!==this.imageDiv.parentNode && OpenLayers.Element.remove(this.imageDiv); },
  1257. setOpacity: function(a){ OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,null,null,null,null,null,a); },
  1258. moveTo: function(a){
  1259. null!==a&&(this.px=a);
  1260. null!==this.imageDiv&&(null===this.px?this.display(!1): (
  1261. this.calculateOffset&&(this.offset=this.calculateOffset(this.size)),
  1262. OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,{x: this.px.x+this.offset.x,y: this.px.y+this.offset.y})
  1263. ));
  1264. },
  1265. display: function(a){ this.imageDiv.style.display=a?"": "none"; },
  1266. isDrawn: function(){ return this.imageDiv&&this.imageDiv.parentNode&&11!=this.imageDiv.parentNode.nodeType; },
  1267. CLASS_NAME: "OpenLayers.Icon"
  1268. });
  1269.  
  1270. }
  1271.  
  1272. function Util() {
  1273. /**
  1274. * Function to defer function execution until an element is present on
  1275. * the page.
  1276. * @function WazeWrap.Util.waitForElement
  1277. * @param {String} selector The CSS selector string or a jQuery object
  1278. * to find before executing the callback.
  1279. * @param {Function} callback The function to call when the page
  1280. * element is detected.
  1281. * @param {Object} [context] The context in which to call the callback.
  1282. */
  1283. this.waitForElement = function (selector, callback, context) {
  1284. let jqObj;
  1285. if (!selector || typeof callback !== 'function')
  1286. return;
  1287.  
  1288. jqObj = typeof selector === 'string' ?
  1289. $(selector) : selector instanceof $ ? selector : null;
  1290.  
  1291. if (!jqObj.length) {
  1292. window.requestAnimationFrame(function () {
  1293. WazeWrap.Util.waitForElement(selector, callback, context);
  1294. });
  1295. } else
  1296. callback.call(context || callback);
  1297. };
  1298.  
  1299. /**
  1300. * Function to track the ready state of the map.
  1301. * @function WazeWrap.Util.mapReady
  1302. * @return {Boolean} Whether or not a map operation is pending or
  1303. * undefined if the function has not yet seen a map ready event fired.
  1304. */
  1305. this.mapReady = function () {
  1306. var mapReady = true;
  1307. W.app.layout.model.on('operationPending', function () {
  1308. mapReady = false;
  1309. });
  1310. W.app.layout.model.on('operationDone', function () {
  1311. mapReady = true;
  1312. });
  1313.  
  1314. return function () {
  1315. return mapReady;
  1316. };
  1317. }();
  1318.  
  1319. /**
  1320. * Function to track the ready state of the model.
  1321. * @function WazeWrap.Util.modelReady
  1322. * @return {Boolean} Whether or not the model has loaded objects or
  1323. * undefined if the function has not yet seen a model ready event fired.
  1324. */
  1325. this.modelReady = function () {
  1326. var modelReady = true;
  1327. W.model.events.register('mergestart', null, function () {
  1328. modelReady = false;
  1329. });
  1330. W.model.events.register('mergeend', null, function () {
  1331. modelReady = true;
  1332. });
  1333. return function () {
  1334. return modelReady;
  1335. };
  1336. }();
  1337.  
  1338. /**
  1339. * Returns orthogonalized geometry for the given geometry and threshold
  1340. * @function WazeWrap.Util.OrthogonalizeGeometry
  1341. * @param {OpenLayers.Geometry} The OpenLayers.Geometry to orthogonalize
  1342. * @param {integer} threshold to use for orthogonalization - the higher the threshold, the more nodes that will be removed
  1343. * @return {OpenLayers.Geometry } Orthogonalized geometry
  1344. **/
  1345. this.OrthogonalizeGeometry = function (geometry, threshold = 12) {
  1346. let nomthreshold = threshold, // degrees within right or straight to alter
  1347. lowerThreshold = Math.cos((90 - nomthreshold) * Math.PI / 180),
  1348. upperThreshold = Math.cos(nomthreshold * Math.PI / 180);
  1349.  
  1350. function Orthogonalize() {
  1351. var nodes = geometry,
  1352. points = nodes.slice(0, -1).map(function (n) {
  1353. let p = n.clone().transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
  1354. p.y = lat2latp(p.y);
  1355. return p;
  1356. }),
  1357. corner = { i: 0, dotp: 1 },
  1358. epsilon = 1e-4,
  1359. i, j, score, motions;
  1360.  
  1361. // Triangle
  1362. if (nodes.length === 4) {
  1363. for (i = 0; i < 1000; i++) {
  1364. motions = points.map(calcMotion);
  1365.  
  1366. var tmp = addPoints(points[corner.i], motions[corner.i]);
  1367. points[corner.i].x = tmp.x;
  1368. points[corner.i].y = tmp.y;
  1369.  
  1370. score = corner.dotp;
  1371. if (score < epsilon)
  1372. break;
  1373. }
  1374.  
  1375. var n = points[corner.i];
  1376. n.y = latp2lat(n.y);
  1377. let pp = n.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
  1378.  
  1379. let id = nodes[corner.i].id;
  1380. for (i = 0; i < nodes.length; i++) {
  1381. if (nodes[i].id != id)
  1382. continue;
  1383.  
  1384. nodes[i].x = pp.x;
  1385. nodes[i].y = pp.y;
  1386. }
  1387.  
  1388. return nodes;
  1389. } else {
  1390. var best,
  1391. originalPoints = nodes.slice(0, -1).map(function (n) {
  1392. let p = n.clone().transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
  1393. p.y = lat2latp(p.y);
  1394. return p;
  1395. });
  1396. score = Infinity;
  1397.  
  1398. for (i = 0; i < 1000; i++) {
  1399. motions = points.map(calcMotion);
  1400. for (j = 0; j < motions.length; j++) {
  1401. let tmp = addPoints(points[j], motions[j]);
  1402. points[j].x = tmp.x;
  1403. points[j].y = tmp.y;
  1404. }
  1405. var newScore = squareness(points);
  1406. if (newScore < score) {
  1407. best = [].concat(points);
  1408. score = newScore;
  1409. }
  1410. if (score < epsilon)
  1411. break;
  1412. }
  1413.  
  1414. points = best;
  1415.  
  1416. for (i = 0; i < points.length; i++) {
  1417. // only move the points that actually moved
  1418. if (originalPoints[i].x !== points[i].x || originalPoints[i].y !== points[i].y) {
  1419. let n = points[i];
  1420. n.y = latp2lat(n.y);
  1421. let pp = n.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
  1422.  
  1423. let id = nodes[i].id;
  1424. for (j = 0; j < nodes.length; j++) {
  1425. if (nodes[j].id != id)
  1426. continue;
  1427.  
  1428. nodes[j].x = pp.x;
  1429. nodes[j].y = pp.y;
  1430. }
  1431. }
  1432. }
  1433.  
  1434. // remove empty nodes on straight sections
  1435. for (i = 0; i < points.length; i++) {
  1436. let dotp = normalizedDotProduct(i, points);
  1437. if (dotp < -1 + epsilon) {
  1438. id = nodes[i].id;
  1439. for (j = 0; j < nodes.length; j++) {
  1440. if (nodes[j].id != id)
  1441. continue;
  1442.  
  1443. nodes[j] = false;
  1444. }
  1445. }
  1446. }
  1447.  
  1448. return nodes.filter(item => item !== false);
  1449. }
  1450.  
  1451. function calcMotion(b, i, array) {
  1452. let a = array[(i - 1 + array.length) % array.length],
  1453. c = array[(i + 1) % array.length],
  1454. p = subtractPoints(a, b),
  1455. q = subtractPoints(c, b),
  1456. scale, dotp;
  1457.  
  1458. scale = 2 * Math.min(euclideanDistance(p, { x: 0, y: 0 }), euclideanDistance(q, { x: 0, y: 0 }));
  1459. p = normalizePoint(p, 1.0);
  1460. q = normalizePoint(q, 1.0);
  1461.  
  1462. dotp = filterDotProduct(p.x * q.x + p.y * q.y);
  1463.  
  1464. // nasty hack to deal with almost-straight segments (angle is closer to 180 than to 90/270).
  1465. if (array.length > 3) {
  1466. if (dotp < -0.707106781186547)
  1467. dotp += 1.0;
  1468. } else if (dotp && Math.abs(dotp) < corner.dotp) {
  1469. corner.i = i;
  1470. corner.dotp = Math.abs(dotp);
  1471. }
  1472.  
  1473. return normalizePoint(addPoints(p, q), 0.1 * dotp * scale);
  1474. }
  1475. };
  1476.  
  1477. function lat2latp(lat) {
  1478. return 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * (Math.PI / 180) / 2));
  1479. }
  1480.  
  1481. function latp2lat(a) {
  1482. return 180 / Math.PI * (2 * Math.atan(Math.exp(a * Math.PI / 180)) - Math.PI / 2);
  1483. }
  1484.  
  1485. function squareness(points) {
  1486. return points.reduce(function (sum, val, i, array) {
  1487. let dotp = normalizedDotProduct(i, array);
  1488.  
  1489. dotp = filterDotProduct(dotp);
  1490. return sum + 2.0 * Math.min(Math.abs(dotp - 1.0), Math.min(Math.abs(dotp), Math.abs(dotp + 1)));
  1491. }, 0);
  1492. }
  1493.  
  1494. function normalizedDotProduct(i, points) {
  1495. let a = points[(i - 1 + points.length) % points.length],
  1496. b = points[i],
  1497. c = points[(i + 1) % points.length],
  1498. p = subtractPoints(a, b),
  1499. q = subtractPoints(c, b);
  1500.  
  1501. p = normalizePoint(p, 1.0);
  1502. q = normalizePoint(q, 1.0);
  1503.  
  1504. return p.x * q.x + p.y * q.y;
  1505. }
  1506.  
  1507. function subtractPoints(a, b) {
  1508. return { x: a.x - b.x, y: a.y - b.y };
  1509. }
  1510.  
  1511. function addPoints(a, b) {
  1512. return { x: a.x + b.x, y: a.y + b.y };
  1513. }
  1514.  
  1515. function euclideanDistance(a, b) {
  1516. let x = a.x - b.x, y = a.y - b.y;
  1517. return Math.sqrt((x * x) + (y * y));
  1518. }
  1519.  
  1520. function normalizePoint(point, scale) {
  1521. let vector = { x: 0, y: 0 };
  1522. let length = Math.sqrt(point.x * point.x + point.y * point.y);
  1523. if (length !== 0) {
  1524. vector.x = point.x / length;
  1525. vector.y = point.y / length;
  1526. }
  1527.  
  1528. vector.x *= scale;
  1529. vector.y *= scale;
  1530.  
  1531. return vector;
  1532. }
  1533.  
  1534. function filterDotProduct(dotp) {
  1535. if (lowerThreshold > Math.abs(dotp) || Math.abs(dotp) > upperThreshold)
  1536. return dotp;
  1537.  
  1538. return 0;
  1539. }
  1540.  
  1541. this.isDisabled = function (nodes) {
  1542. let points = nodes.slice(0, -1).map(function (n) {
  1543. let p = n.toLonLat().transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
  1544. return { x: p.lat, y: p.lon };
  1545. });
  1546.  
  1547. return squareness(points);
  1548. };
  1549.  
  1550. return Orthogonalize();
  1551. };
  1552.  
  1553. /**
  1554. * Returns the general location of the segment queried
  1555. * @function WazeWrap.Util.findSegment
  1556. * @param {OpenLayers.Geometry} The server to search on. The current server can be obtained from W.app.getAppRegionCode()
  1557. * @param {integer} The segment ID to search for
  1558. * @return {OpenLayers.Geometry.Point} A point at the general location of the segment, null if the segment is not found
  1559. **/
  1560. this.findSegment = async function (server, segmentID) {
  1561. let apiURL = location.origin;
  1562. switch (server) {
  1563. case 'row':
  1564. apiURL += '/row-Descartes/app/HouseNumbers?ids=';
  1565. break;
  1566. case 'il':
  1567. apiURL += '/il-Descartes/app/HouseNumbers?ids=';
  1568. break;
  1569. case 'usa':
  1570. default:
  1571. apiURL += '/Descartes/app/HouseNumbers?ids=';
  1572. }
  1573. let response, result = null;
  1574. try {
  1575. response = await $.get(`${apiURL + segmentID}`);
  1576. if (response && response.editAreas.objects.length > 0) {
  1577. let segGeoArea = response.editAreas.objects[0].geometry.coordinates[0];
  1578. let ringGeo = [];
  1579. for (let i = 0; i < segGeoArea.length - 1; i++)
  1580. ringGeo.push(new OpenLayers.Geometry.Point(segGeoArea[i][0], segGeoArea[i][1]));
  1581. if (ringGeo.length > 0) {
  1582. let ring = new OpenLayers.Geometry.LinearRing(ringGeo);
  1583. result = ring.getCentroid();
  1584. }
  1585. }
  1586. }
  1587. catch (err) {
  1588. console.log(err);
  1589. }
  1590.  
  1591. return result;
  1592. };
  1593.  
  1594. /**
  1595. * Returns the location of the venue queried
  1596. * @function WazeWrap.Util.findVenue
  1597. * @param {OpenLayers.Geometry} The server to search on. The current server can be obtained from W.app.getAppRegionCode()
  1598. * @param {integer} The venue ID to search for
  1599. * @return {OpenLayers.Geometry.Point} A point at the location of the venue, null if the venue is not found
  1600. **/
  1601. this.findVenue = async function (server, venueID) {
  1602. let apiURL = location.origin;
  1603. switch (server) {
  1604. case 'row':
  1605. apiURL += '/row-SearchServer/mozi?max_distance_kms=&lon=-84.22637&lat=39.61097&format=PROTO_JSON_FULL&venue_id=';
  1606. break;
  1607. case 'il':
  1608. apiURL += '/il-SearchServer/mozi?max_distance_kms=&lon=-84.22637&lat=39.61097&format=PROTO_JSON_FULL&venue_id=';
  1609. break;
  1610. case 'usa':
  1611. default:
  1612. apiURL += '/SearchServer/mozi?max_distance_kms=&lon=-84.22637&lat=39.61097&format=PROTO_JSON_FULL&venue_id=';
  1613. }
  1614. let response, result = null;
  1615. try {
  1616. response = await $.get(`${apiURL + venueID}`);
  1617. if (response && response.venue) {
  1618. result = new OpenLayers.Geometry.Point(response.venue.location.x, response.venue.location.y);
  1619. }
  1620. }
  1621. catch (err) {
  1622. console.log(err);
  1623. }
  1624.  
  1625. return result;
  1626. };
  1627. }
  1628.  
  1629. function Events() {
  1630. const eventMap = {
  1631. 'moveend': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1632. 'zoomend': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1633. 'mousemove': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1634. 'mouseup': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1635. 'mousedown': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1636. 'changelayer': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1637. 'selectionchanged': { register: function (p1, p2, p3) { W.selectionManager.events.register(p1, p2, p3) }, unregister: function (p1, p2, p3) { W.selectionManager.events.unregister(p1, p2, p3) } },
  1638. 'afterundoaction': { register: function (p1, p2, p3) { W.model.actionManager.events.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { W.model.actionManager.events.unregister(p1, p2, p3); } },
  1639. 'afterclearactions': { register: function (p1, p2, p3) { W.model.actionManager.events.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { W.model.actionManager.events.unregister(p1, p2, p3); } },
  1640. 'afteraction': { register: function (p1, p2, p3) { W.model.actionManager.events.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { W.model.actionManager.events.unregister(p1, p2, p3); } },
  1641. 'change:editingHouseNumbers': { register: function (p1, p2) { W.editingMediator.on(p1, p2); }, unregister: function (p1, p2) { W.editingMediator.off(p1, p2); } },
  1642. 'change:mode': { register: function (p1, p2) { W.app.bind(p1, p2); }, unregister: function (p1, p2) { W.app.unbind(p1, p2); } },
  1643. 'change:isImperial': { register: function (p1, p2) { W.prefs.on(p1, p2); }, unregister: function (p1, p2) { W.prefs.off(p1, p2); } }
  1644. };
  1645.  
  1646. var eventHandlerList = {};
  1647.  
  1648. this.register = function (event, context, handler, errorHandler) {
  1649. if (typeof eventHandlerList[event] == "undefined")
  1650. eventHandlerList[event] = [];
  1651.  
  1652. let newHandler = function () {
  1653. try {
  1654. handler(...arguments);
  1655. }
  1656. catch (err) {
  1657. console.error(`Error thrown in: ${handler.name}\n ${err}`);
  1658. if (errorHandler)
  1659. errorHandler(err);
  1660. }
  1661. };
  1662.  
  1663. eventHandlerList[event].push({ origFunc: handler, newFunc: newHandler });
  1664. if (event === 'change:editingHouseNumbers' || event === 'change:mode' || event === 'change:isImperial')
  1665. eventMap[event].register(event, newHandler);
  1666. else
  1667. eventMap[event].register(event, context, newHandler);
  1668. };
  1669.  
  1670. this.unregister = function (event, context, handler) {
  1671. let unregHandler;
  1672. if (eventHandlerList && eventHandlerList[event]) { //Must check in case a script is trying to unregister before registering an eventhandler and one has not yet been created
  1673. for (let i = 0; i < eventHandlerList[event].length; i++) {
  1674. if (eventHandlerList[event][i].origFunc.toString() == handler.toString())
  1675. unregHandler = eventHandlerList[event][i].newFunc;
  1676. }
  1677. if (typeof unregHandler != "undefined") {
  1678. if (event === 'change:editingHouseNumbers' || event === 'change:mode' || event === 'change:isImperial')
  1679. eventMap[event].unregister(event, unregHandler);
  1680. else
  1681. eventMap[event].unregister(event, context, unregHandler);
  1682. }
  1683. }
  1684. };
  1685.  
  1686. }
  1687.  
  1688. function Interface() {
  1689. /**
  1690. * Generates id for message bars.
  1691. * @private
  1692. */
  1693. var getNextID = function () {
  1694. let id = 1;
  1695. return function () {
  1696. return id++;
  1697. };
  1698. }();
  1699.  
  1700. /**
  1701. * Creates a keyboard shortcut for the supplied callback event
  1702. * @function WazeWrap.Interface.Shortcut
  1703. * @param {string}
  1704. * @param {string}
  1705. * @param {string}
  1706. * @param {string}
  1707. * @param {string}
  1708. * @param {function}
  1709. * @param {object}
  1710. * @param {integer} The segment ID to search for
  1711. * @return {OpenLayers.Geometry.Point} A point at the general location of the segment, null if the segment is not found
  1712. **/
  1713. this.Shortcut = class Shortcut {
  1714. constructor(name, desc, group, title, shortcut, callback, scope) {
  1715. if ('string' === typeof name && name.length > 0 && 'string' === typeof shortcut && 'function' === typeof callback) {
  1716. this.name = name;
  1717. this.desc = desc;
  1718. this.group = group || this.defaults.group;
  1719. this.title = title;
  1720. this.callback = callback;
  1721. this.shortcut = {};
  1722. if (shortcut.length > 0)
  1723. this.shortcut[shortcut] = name;
  1724. if ('object' !== typeof scope)
  1725. this.scope = null;
  1726. else
  1727. this.scope = scope;
  1728. this.groupExists = false;
  1729. this.actionExists = false;
  1730. this.eventExists = false;
  1731. this.defaults = { group: 'default' };
  1732.  
  1733. return this;
  1734. }
  1735. }
  1736.  
  1737. /**
  1738. * Determines if the shortcut's action already exists.
  1739. * @private
  1740. */
  1741. doesGroupExist() {
  1742. this.groupExists = 'undefined' !== typeof W.accelerators.Groups[this.group] &&
  1743. undefined !== typeof W.accelerators.Groups[this.group].members;
  1744. return this.groupExists;
  1745. }
  1746.  
  1747. /**
  1748. * Determines if the shortcut's action already exists.
  1749. * @private
  1750. */
  1751. doesActionExist() {
  1752. this.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];
  1753. return this.actionExists;
  1754. }
  1755.  
  1756. /**
  1757. * Determines if the shortcut's event already exists.
  1758. * @private
  1759. */
  1760. doesEventExist() {
  1761. this.eventExists = 'undefined' !== typeof W.accelerators.events.dispatcher._events[this.name] &&
  1762. W.accelerators.events.dispatcher._events[this.name].length > 0 &&
  1763. this.callback === W.accelerators.events.dispatcher._events[this.name][0].func &&
  1764. this.scope === W.accelerators.events.dispatcher._events[this.name][0].obj;
  1765. return this.eventExists;
  1766. }
  1767.  
  1768. /**
  1769. * Creates the shortcut's group.
  1770. * @private
  1771. */
  1772. createGroup() {
  1773. W.accelerators.Groups[this.group] = [];
  1774. W.accelerators.Groups[this.group].members = [];
  1775.  
  1776. if (this.title && !I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group]) {
  1777. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group] = [];
  1778. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].description = this.title;
  1779. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].members = [];
  1780. }
  1781. }
  1782.  
  1783. /**
  1784. * Registers the shortcut's action.
  1785. * @private
  1786. */
  1787. addAction() {
  1788. if (this.title)
  1789. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].members[this.name] = this.desc;
  1790. W.accelerators.addAction(this.name, { group: this.group });
  1791. }
  1792.  
  1793. /**
  1794. * Registers the shortcut's event.
  1795. * @private
  1796. */
  1797. addEvent() {
  1798. W.accelerators.events.register(this.name, this.scope, this.callback);
  1799. }
  1800.  
  1801. /**
  1802. * Registers the shortcut's keyboard shortcut.
  1803. * @private
  1804. */
  1805. registerShortcut() {
  1806. W.accelerators._registerShortcuts(this.shortcut);
  1807. }
  1808.  
  1809. /**
  1810. * Adds the keyboard shortcut to the map.
  1811. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  1812. */
  1813. add() {
  1814. /* If the group is not already defined, initialize the group. */
  1815. if (!this.doesGroupExist()) {
  1816. this.createGroup();
  1817. }
  1818.  
  1819. /* Clear existing actions with same name */
  1820. if (this.doesActionExist()) {
  1821. W.accelerators.Actions[this.name] = null;
  1822. }
  1823. this.addAction();
  1824.  
  1825. /* Register event only if it's not already registered */
  1826. if (!this.doesEventExist()) {
  1827. this.addEvent();
  1828. }
  1829.  
  1830. /* Finally, register the shortcut. */
  1831. this.registerShortcut();
  1832. return this;
  1833. }
  1834.  
  1835. /**
  1836. * Removes the keyboard shortcut from the map.
  1837. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  1838. */
  1839. remove() {
  1840. if (this.doesEventExist()) {
  1841. W.accelerators.events.unregister(this.name, this.scope, this.callback);
  1842. }
  1843. if (this.doesActionExist()) {
  1844. delete W.accelerators.Actions[this.name];
  1845. }
  1846. //remove shortcut?
  1847. return this;
  1848. }
  1849.  
  1850. /**
  1851. * Changes the keyboard shortcut and applies changes to the map.
  1852. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  1853. */
  1854. change(shortcut) {
  1855. if (shortcut) {
  1856. this.shortcut = {};
  1857. this.shortcut[shortcut] = this.name;
  1858. this.registerShortcut();
  1859. }
  1860. return this;
  1861. }
  1862. }
  1863.  
  1864. /**
  1865. * Creates a tab in the side panel
  1866. * @function WazeWrap.Interface.Tab
  1867. * @param {string}
  1868. * @param {string}
  1869. * @param {function}
  1870. * @param {string}
  1871. **/
  1872. this.Tab = async function Tab(name, content, callback, labelText) {
  1873. if(!labelText)
  1874. labelText = name;
  1875. const {tabLabel, tabPane} = W.userscripts.registerSidebarTab(name);
  1876. tabLabel.innerHTML = labelText;
  1877. tabPane.innerHTML = content;
  1878. await W.userscripts.waitForElementConnected(tabPane);
  1879. if('function' === typeof callback)
  1880. callback();
  1881.  
  1882. }
  1883.  
  1884. /**
  1885. * Creates a checkbox in the layer menu
  1886. * @function WazeWrap.Interface.AddLayerCheckbox
  1887. * @param {string}
  1888. * @param {string}
  1889. * @param {boolean}
  1890. * @param {function}
  1891. * @param {object}
  1892. * @param {Layer object}
  1893. **/
  1894. this.AddLayerCheckbox = function (group, checkboxText, checked, callback, layer) {
  1895. group = group.toLowerCase();
  1896. let normalizedText = checkboxText.toLowerCase().replace(/\s/g, '_');
  1897. let checkboxID = "layer-switcher-item_" + normalizedText;
  1898. let groupPrefix = 'layer-switcher-group_';
  1899. let groupClass = groupPrefix + group.toLowerCase();
  1900. sessionStorage[normalizedText] = checked;
  1901.  
  1902. let CreateParentGroup = function (groupChecked) {
  1903. let groupList = $('.layer-switcher').find('.list-unstyled.togglers');
  1904. let checkboxText = group.charAt(0).toUpperCase() + group.substr(1);
  1905. let newLI = $('<li class="group">');
  1906. newLI.html([
  1907. '<div class="layer-switcher-toggler-tree-category">',
  1908. '<i class="toggle-category w-icon-caret-down" data-group-id="GROUP_' + group.toUpperCase() + '"></i>',
  1909. '<wz-toggle-switch class="' + groupClass + ' hydrated" id="' + groupClass + '" ' + (groupChecked ? 'checked' : '') + '>',
  1910. '<label class="label-text" for="' + groupClass + '">' + checkboxText + '</label>',
  1911. '</div>',
  1912. '</li></ul>'
  1913. ].join(' '));
  1914.  
  1915. groupList.append(newLI);
  1916. $('#' + groupClass).change(function () { sessionStorage[groupClass] = this.checked; });
  1917. };
  1918.  
  1919. if (group !== "issues" && group !== "places" && group !== "road" && group !== "display") //"non-standard" group, check its existence
  1920. if ($('.' + groupClass).length === 0) { //Group doesn't exist yet, create it
  1921. let isParentChecked = (typeof sessionStorage[groupClass] == "undefined" ? true : sessionStorage[groupClass] == 'true');
  1922. CreateParentGroup(isParentChecked); //create the group
  1923. sessionStorage[groupClass] = isParentChecked;
  1924. }
  1925.  
  1926. var buildLayerItem = function (isChecked) {
  1927. let groupChildren = $(".collapsible-GROUP_" + group.toUpperCase());
  1928. let $li = $('<li>');
  1929. $li.html([
  1930. '<wz-checkbox id="' + checkboxID + '" class="hydrated">',
  1931. checkboxText,
  1932. '</wz-checkbox>',
  1933. ].join(' '));
  1934.  
  1935. groupChildren.append($li);
  1936. $('#' + checkboxID).prop('checked', isChecked);
  1937. $('#' + checkboxID).change(function () { callback(this.checked); sessionStorage[normalizedText] = this.checked; });
  1938. if (!$('#' + groupClass).prop('checked')) {
  1939. $('#' + checkboxID).prop('disabled', true);
  1940. if (typeof layer === 'undefined')
  1941. callback(false);
  1942. else {
  1943. if ($.isArray(layer))
  1944. $.each(layer, (k, v) => { v.setVisibility(false); });
  1945. else
  1946. layer.setVisibility(false);
  1947. }
  1948. }
  1949.  
  1950. $('#' + groupClass).change(function () {
  1951. $('#' + checkboxID).prop('disabled', !this.checked);
  1952. if (typeof layer === 'undefined')
  1953. callback(!this.checked ? false : sessionStorage[normalizedText] == 'true');
  1954. else {
  1955. if ($.isArray(layer))
  1956. $.each(layer, (k, v) => { v.setVisibility(this.checked); });
  1957. else
  1958. layer.setVisibility(this.checked);
  1959. }
  1960. });
  1961. };
  1962.  
  1963. buildLayerItem(checked);
  1964. };
  1965.  
  1966. /**
  1967. * Shows the script update window with the given update text
  1968. * @function WazeWrap.Interface.ShowScriptUpdate
  1969. * @param {string}
  1970. * @param {string}
  1971. * @param {string}
  1972. * @param {string}
  1973. * @param {string}
  1974. **/
  1975. this.ShowScriptUpdate = function (scriptName, version, updateHTML, greasyforkLink = "", forumLink = "") {
  1976. let settings;
  1977. function loadSettings() {
  1978. var loadedSettings = $.parseJSON(localStorage.getItem("WWScriptUpdate"));
  1979. var defaultSettings = {
  1980. ScriptUpdateHistory: {},
  1981. };
  1982. settings = loadedSettings ? loadedSettings : defaultSettings;
  1983. for (var prop in defaultSettings) {
  1984. if (!settings.hasOwnProperty(prop))
  1985. settings[prop] = defaultSettings[prop];
  1986. }
  1987. }
  1988.  
  1989. function saveSettings() {
  1990. if (localStorage) {
  1991. var localsettings = {
  1992. ScriptUpdateHistory: settings.ScriptUpdateHistory,
  1993. };
  1994.  
  1995. localStorage.setItem("WWScriptUpdate", JSON.stringify(localsettings));
  1996. }
  1997. }
  1998.  
  1999. loadSettings();
  2000.  
  2001. if ((updateHTML && updateHTML.length > 0) && (typeof settings.ScriptUpdateHistory[scriptName] === "undefined" || settings.ScriptUpdateHistory[scriptName] != version)) {
  2002. let currCount = $('.WWSU-script-item').length;
  2003. let divID = (scriptName + ("" + version)).toLowerCase().replace(/[^a-z-_0-9]/g, '');
  2004. $('#WWSU-script-list').append(`<a href="#${divID}" class="WWSU-script-item ${currCount === 0 ? 'WWSU-active' : ''}">${scriptName}</a>`); //add the script's tab
  2005. $("#WWSU-updateCount").html(parseInt($("#WWSU-updateCount").html()) + 1); //increment the total script updates value
  2006. let install = "", forum = "";
  2007. if (greasyforkLink != "")
  2008. install = `<a href="${greasyforkLink}" target="_blank">Greasyfork</a>`;
  2009. if (forumLink != "")
  2010. forum = `<a href="${forumLink}" target="_blank">Forum</a>`;
  2011. let footer = "";
  2012. if (forumLink != "" || greasyforkLink != "") {
  2013. footer = `<span class="WWSUFooter" style="margin-bottom:2px; display:block;">${install}${(greasyforkLink != "" && forumLink != "") ? " | " : ""}${forum}</span>`;
  2014. }
  2015. $('#WWSU-script-update-info').append(`<div id="${divID}"><span><h3>${version}</h3><br>${updateHTML}</span>${footer}</div>`);
  2016. $('#WWSU-Container').show();
  2017. if (currCount === 0)
  2018. $('#WWSU-script-list').find("a")[0].click();
  2019. settings.ScriptUpdateHistory[scriptName] = version;
  2020. saveSettings();
  2021. }
  2022. };
  2023. }
  2024.  
  2025. function Alerts() {
  2026. this.success = function (scriptName, message) {
  2027. $(wazedevtoastr.success(message, scriptName)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2028. }
  2029.  
  2030. this.info = function (scriptName, message, disableTimeout, disableClickToClose, timeOut) {
  2031. let options = {};
  2032. if (disableTimeout)
  2033. options.timeOut = 0;
  2034. else if (timeOut)
  2035. options.timeOut = timeOut;
  2036.  
  2037. if (disableClickToClose)
  2038. options.tapToDismiss = false;
  2039. $(wazedevtoastr.info(message, scriptName, options)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2040. }
  2041.  
  2042. this.warning = function (scriptName, message) {
  2043. $(wazedevtoastr.warning(message, scriptName)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2044. }
  2045.  
  2046. this.error = function (scriptName, message) {
  2047. $(wazedevtoastr.error(message, scriptName)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2048. }
  2049.  
  2050. this.debug = function (scriptName, message) {
  2051. wazedevtoastr.debug(message, scriptName);
  2052. }
  2053.  
  2054. this.prompt = function (scriptName, message, defaultText = '', okFunction, cancelFunction) {
  2055. wazedevtoastr.prompt(message, scriptName, { promptOK: okFunction, promptCancel: cancelFunction, PromptDefaultInput: defaultText });
  2056. }
  2057.  
  2058. this.confirm = function (scriptName, message, okFunction, cancelFunction, okBtnText = "Ok", cancelBtnText = "Cancel") {
  2059. wazedevtoastr.confirm(message, scriptName, { confirmOK: okFunction, confirmCancel: cancelFunction, ConfirmOkButtonText: okBtnText, ConfirmCancelButtonText: cancelBtnText });
  2060. }
  2061.  
  2062. this.ScriptUpdateMonitor = class {
  2063. #lastVersionChecked = '0';
  2064. #scriptName;
  2065. #currentVersion;
  2066. #downloadUrl;
  2067. #metaUrl;
  2068. #metaRegExp;
  2069. #GM_xmlhttpRequest;
  2070. #intervalChecker = null;
  2071. /**
  2072. * Creates an instance of ScriptUpdateMonitor.
  2073. * @param {string} scriptName The name of your script. Used as the alert title and in console error messages.
  2074. * @param {string|number} currentVersion The current installed version of the script.
  2075. * @param {string} downloadUrl The download URL of the script. If using Greasy Fork, the URL should end with ".user.js".
  2076. * @param {object} GM_xmlhttpRequest A reference to the GM_xmlhttpRequest function used by your script.
  2077. * This is used to obtain the latest script version number from the server.
  2078. * @param {string} [metaUrl] The URL to a page containing the latest script version number.
  2079. * Optional for Greasy Fork scripts (uses download URL path, replacing ".user.js" with ".meta.js").
  2080. * @param {RegExp} [metaRegExp] A regular expression with a single capture group to extract the
  2081. * version number from the metaUrl page. e.g. /@version\s+(.+)/i. Required if metaUrl is specified.
  2082. * Ignored if metaUrl is a falsy value.
  2083. * @memberof ScriptUpdateMonitor
  2084. */
  2085. constructor(scriptName, currentVersion, downloadUrl, GM_xmlhttpRequest, metaUrl = null, metaRegExp = null) {
  2086. this.#scriptName = scriptName;
  2087. this.#currentVersion = currentVersion;
  2088. this.#downloadUrl = downloadUrl;
  2089. this.#GM_xmlhttpRequest = GM_xmlhttpRequest;
  2090. this.#metaUrl = metaUrl;
  2091. this.#metaRegExp = metaRegExp || /@version\s+(.+)/i;
  2092. this.#validateParameters();
  2093. }
  2094. /**
  2095. * Starts checking for script updates at a specified interval.
  2096. *
  2097. * @memberof ScriptUpdateMonitor
  2098. * @param {number} [intervalHours = 2] The interval, in hours, to check for script updates. Default is 2. Minimum is 1.
  2099. * @param {boolean} [checkImmediately = true] If true, checks for a script update immediately when called. Default is true.
  2100. */
  2101. start(intervalHours = 2, checkImmediately = true) {
  2102. if (intervalHours < 1) {
  2103. throw new Error('Parameter intervalHours must be at least 1');
  2104. }
  2105. if (!this.#intervalChecker) {
  2106. if (checkImmediately) this.#postAlertIfNewReleaseAvailable();
  2107. // Use the arrow function here to bind the "this" context to the ScriptUpdateMonitor object.
  2108. this.#intervalChecker = setInterval(() => this.#postAlertIfNewReleaseAvailable(), intervalHours * 60 * 60 * 1000);
  2109. }
  2110. }
  2111. /**
  2112. * Stops checking for script updates.
  2113. *
  2114. * @memberof ScriptUpdateMonitor
  2115. */
  2116. stop() {
  2117. if (this.#intervalChecker) {
  2118. clearInterval(this.#intervalChecker);
  2119. this.#intervalChecker = null;
  2120. }
  2121. }
  2122. #validateParameters() {
  2123. if (this.#metaUrl) {
  2124. if (!this.#metaRegExp) {
  2125. throw new Error('metaRegExp must be defined if metaUrl is defined.');
  2126. }
  2127. if (!(this.#metaRegExp instanceof RegExp)) {
  2128. throw new Error('metaUrl must be a regular expression.');
  2129. }
  2130. } else {
  2131. if (!/\.user\.js$/.test(this.#downloadUrl)) {
  2132. throw new Error('Invalid downloadUrl paramenter. Must end with ".user.js" [', this.#downloadUrl, ']');
  2133. }
  2134. this.#metaUrl = this.#downloadUrl.replace(/\.user\.js$/, '.meta.js');
  2135. }
  2136. }
  2137. async #postAlertIfNewReleaseAvailable() {
  2138. const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
  2139. let latestVersion;
  2140. try {
  2141. let tries = 1;
  2142. const maxTries = 3;
  2143. while (tries <= maxTries) {
  2144. latestVersion = await this.#fetchLatestReleaseVersion();
  2145. if (latestVersion === 503) {
  2146. // Greasy Fork returns a 503 error when too many requests are sent quickly.
  2147. // Pause and try again.
  2148. if (tries < maxTries) {
  2149. console.log(`${this.#scriptName}: Checking for latest version again (retry #${tries})`);
  2150. await sleep(1000);
  2151. } else {
  2152. console.error(`${this.#scriptName}: Failed to check latest version #. Too many 503 status codes returned.`);
  2153. }
  2154. tries += 1;
  2155. } else if (latestVersion.status) {
  2156. console.error(`${this.#scriptName}: Error while checking for latest version.`, latestVersion);
  2157. return;
  2158. } else {
  2159. break;
  2160. }
  2161. }
  2162. } catch (ex) {
  2163. console.error(`${this.#scriptName}: Error while checking for latest version.`, ex);
  2164. return;
  2165. }
  2166. if (latestVersion > this.#currentVersion && latestVersion > (this.#lastVersionChecked || '0')) {
  2167. this.#lastVersionChecked = latestVersion;
  2168. this.#clearPreviousAlerts();
  2169. this.#postNewVersionAlert(latestVersion);
  2170. }
  2171. }
  2172. #postNewVersionAlert(newVersion) {
  2173. const message = `<a href="${this.#downloadUrl}" target = "_blank">Version ${
  2174. newVersion}</a> is available.<br>Update now to get the latest features and fixes.`;
  2175. WazeWrap.Alerts.info(this.#scriptName, message, true, false);
  2176. }
  2177. #fetchLatestReleaseVersion() {
  2178. const metaUrl = this.#metaUrl;
  2179. const metaRegExp = this.#metaRegExp;
  2180. return new Promise((resolve, reject) => {
  2181. this.#GM_xmlhttpRequest({
  2182. nocache: true,
  2183. revalidate: true,
  2184. url: metaUrl,
  2185. onload(res) {
  2186. if (res.status === 503) {
  2187. resolve(503);
  2188. } else if (res.status === 200) {
  2189. const versionMatch = res.responseText.match(metaRegExp);
  2190. if (versionMatch?.length !== 2) {
  2191. throw new Error(`Invalid RegExp expression (${metaRegExp}) or version # could not be found at this URL: ${metaUrl}`);
  2192. }
  2193. resolve(res.responseText.match(metaRegExp)[1]);
  2194. } else {
  2195. resolve(res);
  2196. }
  2197. },
  2198. onerror(res) {
  2199. reject(res);
  2200. }
  2201. });
  2202. });
  2203. }
  2204. #clearPreviousAlerts() {
  2205. $('.toast-container-wazedev .toast-info:visible').toArray().forEach(elem => {
  2206. const $alert = $(elem);
  2207. const title = $alert.find('.toast-title').text();
  2208. if (title === this.#scriptName) {
  2209. const message = $alert.find('.toast-message').text();
  2210. if (/version .* is available/i.test(message)) {
  2211. // Force a click to make the alert go away.
  2212. $alert.click();
  2213. }
  2214. }
  2215. });
  2216. }
  2217. }
  2218. }
  2219. function Remote(){
  2220. function sendPOST(scriptName, scriptSettings){
  2221. return new Promise(function (resolve, reject) {
  2222. var xhr = new XMLHttpRequest();
  2223. xhr.open("POST", "https://wazedev.com:8443", true);
  2224. xhr.setRequestHeader('Content-Type', 'application/json');
  2225. xhr.onreadystatechange = function(e) {
  2226. if (xhr.readyState === 4) {
  2227. if (xhr.status === 200)
  2228. resolve(true)
  2229. else
  2230. reject(false)
  2231. }
  2232. }
  2233. xhr.send(JSON.stringify({
  2234. userID: W.loginManager.user.getID().toString(),
  2235. pin: wwSettings.editorPIN,
  2236. script: scriptName,
  2237. settings: scriptSettings
  2238. }));
  2239. });
  2240. }
  2241.  
  2242. this.SaveSettings = async function(scriptName, scriptSettings){
  2243. if(wwSettings.editorPIN === ""){
  2244. console.error("Editor PIN not set");
  2245. return null;
  2246. }
  2247. if(scriptName === ""){
  2248. console.error("No script name provided");
  2249. return null;
  2250. }
  2251. try{
  2252. return await sendPOST(scriptName, scriptSettings);
  2253. /*let result = await $.ajax({
  2254. url: 'https://wazedev.com:8443',
  2255. type: 'POST',
  2256. contentType: 'application/json',
  2257. data: JSON.stringify({
  2258. userID: W.loginManager.user.id,
  2259. pin: wwSettings.editorPIN,
  2260. script: scriptName,
  2261. settings: scriptSettings
  2262. })}
  2263. );
  2264. return result;*/
  2265. }
  2266. catch(err){
  2267. console.log(err);
  2268. return null;
  2269. }
  2270. }
  2271. this.RetrieveSettings = async function(script){
  2272. if(wwSettings.editorPIN === ""){
  2273. console.error("Editor PIN not set");
  2274. return null;
  2275. }
  2276. if(script === ""){
  2277. console.error("No script name provided");
  2278. return null;
  2279. }
  2280. try{
  2281. let response = await fetch(`https://wazedev.com/userID/${W.loginManager.user.getID()}/PIN/${wwSettings.editorPIN}/script/${script}`);
  2282. response = await response.json();
  2283. return response;
  2284. }
  2285. catch(err){
  2286. console.log(err);
  2287. return null;
  2288. }
  2289. }
  2290. }
  2291.  
  2292. function String() {
  2293. this.toTitleCase = function (str) {
  2294. return str.replace(/(?:^|\s)\w/g, function (match) {
  2295. return match.toUpperCase();
  2296. });
  2297. };
  2298. }
  2299. }.call(this));