WazeWrapLib dev

WazeWrapLib for development purposes

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址