Sleazy Fork is available in English.

WazeWrap site_suite

A base library for WME script writers

このスクリプトは単体で利用できません。右のようなメタデータを含むスクリプトから、ライブラリとして読み込まれます: // @require https://update.sleazyfork.org/scripts/390912/739166/WazeWrap%20site_suite.js

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