WazeWrapBeta

A base library for WME script writers

当前为 2019-04-26 提交的版本,查看 最新版本

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

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