WazeWrapBeta

A base library for WME script writers

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

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

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

QingJ © 2025

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