WazeWrapBeta

A base library for WME script writers

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

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

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

QingJ © 2025

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