WazeWrap

A base library for WME script writers

当前为 2019-03-06 提交的版本,查看 最新版本

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

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

QingJ © 2025

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