WazeWrapBeta

A base library for WME script writers

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

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

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

QingJ © 2025

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