WazeWrapBeta

A base library for WME script writers

As of 2019-05-01. See the latest version.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/24870/694140/WazeWrapBeta.js

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