WazeWrapBeta

A base library for WME script writers

目前为 2019-04-22 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/24870/691694/WazeWrapBeta.js

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

QingJ © 2025

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