WazeWrap

A base library for WME script writers

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

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

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

QingJ © 2025

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