WazeWrap Beta

A base library for WME script writers

目前為 2017-03-15 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/24870/181189/WazeWrap%20Beta.js

  1. // ==UserScript==
  2. // @name WazeWrap Beta
  3. // @namespace https://gf.qytechs.cn/users/30701-justins83-waze
  4. // @version 0.2.6b
  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 WazeWrapBeta */
  15. var WazeWrapBeta = {};
  16.  
  17. (function() {
  18.  
  19. function bootstrap(tries) {
  20. tries = tries || 1;
  21. if (window.W &&
  22. window.W.map &&
  23. window.W.model &&
  24. window.W.loginManager.user &&
  25. $) {
  26. init();
  27. } else if (tries < 1000) {
  28. setTimeout(function () { bootstrap(tries++); }, 200);
  29. } else {
  30. console.log('WazeWrap failed to load');
  31. }
  32. }
  33.  
  34. bootstrap();
  35.  
  36. function init(){
  37. console.log("WazeWrap initializing...");
  38. var oldLib = window.WazeWrapBeta;
  39. var root = this;
  40.  
  41. WazeWrapBeta.Version = GM_info.script.version;
  42. WazeWrapBeta.isBetaEditor = /beta/.test(location.href);
  43.  
  44. //SetUpRequire();
  45.  
  46. WazeWrapBeta.test = "test";
  47. WazeWrapBeta.Geometry = new Geometry;
  48. WazeWrapBeta.Model = new Model;
  49. WazeWrapBeta.Interface = new Interface;
  50. WazeWrapBeta.User = new User;
  51. WazeWrapBeta.Util = new Util;
  52. WazeWrapBeta.Require = new Require;
  53. root.WazeWrapBeta = WazeWrapBeta;
  54.  
  55. console.log('WazeWrapBeta Loaded');
  56. };
  57.  
  58.  
  59. function SetUpRequire(){
  60. if(this.isBetaEditor || typeof window.require !== "undefined")
  61. return;
  62.  
  63. console.log("Setting d2's require fix...");
  64.  
  65. // setup one global var and put all in
  66. var WMEAPI = {};
  67.  
  68. // detect URL of WME source code
  69. WMEAPI.scripts = document.getElementsByTagName('script');
  70. WMEAPI.url=null;
  71. for (i=0;i<WMEAPI.scripts.length;i++){
  72. if (WMEAPI.scripts[i].src.indexOf('/assets-editor/js/app')!=-1)
  73. {
  74. WMEAPI.url=WMEAPI.scripts[i].src;
  75. break;
  76. }
  77. }
  78. if (WMEAPI.url==null)
  79. throw new Error("WME Hack: can't detect WME main JS");
  80.  
  81.  
  82. // setup a fake require and require.define
  83. WMEAPI.require=function (e) {
  84. if (WMEAPI.require.define.modules.hasOwnProperty(e))
  85. return WMEAPI.require.define.modules[e];
  86. else
  87. console.error('Require failed on ' + e, WMEAPI.require.define.modules);
  88. return null;
  89. };
  90.  
  91. WMEAPI.require.define=function (m) {
  92. if (WMEAPI.require.define.hasOwnProperty('modules')==false)
  93. WMEAPI.require.define.modules={};
  94. for (var p in m){
  95. WMEAPI.require.define.modules[p]=m[p];
  96. }
  97. };
  98.  
  99. // save the original webpackJsonp function
  100. WMEAPI.tmp = window.webpackJsonp;
  101.  
  102. // taken from WME code: this function is a wrapper that setup the API and may call recursively other functions
  103. WMEAPI.t = function (n) {
  104. if (WMEAPI.s[n]) return WMEAPI.s[n].exports;
  105. var r = WMEAPI.s[n] = {
  106. exports: {},
  107. id: n,
  108. loaded: !1
  109. };
  110. return WMEAPI.e[n].call(r.exports, r, r.exports, WMEAPI.t), r.loaded = !0, r.exports;
  111. };
  112.  
  113. // e is a copy of all WME funcs because function t need to access to this list
  114. WMEAPI.e=[];
  115.  
  116. // the patch
  117. window.webpackJsonp = function(a, i) {
  118. // our API but we will use it only to build the require stuffs
  119. var api={};
  120. // taken from WME code. a is [1], so...
  121. for (var o, d, u = 0, l = []; u < a.length; u++) d = a[u], WMEAPI.r[d] && l.push.apply(l, WMEAPI.r[d]), WMEAPI.r[d] = 0;
  122. var unknownCount=0;
  123. var classname, funcStr;
  124. // copy i in e and keep a link from classname to index in e
  125. for (o in i){
  126. WMEAPI.e[o] = i[o];
  127. funcStr = i[o].toString();
  128. classname = funcStr.match(/CLASS_NAME:\"([^\"]*)\"/);
  129. if (classname){
  130. // keep the link.
  131. api[classname[1].replace(/\./g,'/').replace(/^W\//, 'Waze/')]={index: o, func: WMEAPI.e[o]};
  132. }
  133. else{
  134. api['Waze/Unknown/' + unknownCount]={index: o, func: WMEAPI.e[o]};
  135. unknownCount++;
  136. }
  137. }
  138. // taken from WME code: it calls the original webpackJsonp and do something else, but I don't really know what.
  139. // removed the call to the original webpackJsonp: still works...
  140. //for (tmp && tmp(a, i); l.length;) l.shift().call(null, t);
  141. for (; l.length;) l.shift().call(null, WMEAPI.t);
  142. WMEAPI.s[0] = 0;
  143. // run the first func of WME. This first func will call recusrsively all funcs needed to setup the API.
  144. // After this call, s will contain all instanciables classes.
  145. //var ret = WMEAPI.t(0);
  146. // now, build the requires thanks to the link we've built in var api.
  147. var module={};
  148. var apiFuncName;
  149. unknownCount=0;
  150. for (o in i){
  151. funcStr = i[o].toString();
  152. classname = funcStr.match(/CLASS_NAME:\"([^\"]*)\"/);
  153. if (classname){
  154. module={};
  155. apiFuncName = classname[1].replace(/\./g,'/').replace(/^W\//, 'Waze/');
  156. module[apiFuncName]=WMEAPI.t(api[apiFuncName].index);
  157. WMEAPI.require.define(module);
  158. }
  159. else{
  160. var matches = funcStr.match(/SEGMENT:"segment",/);
  161. if (matches){
  162. module={};
  163. apiFuncName='Waze/Model/ObjectType';
  164. module[apiFuncName]=WMEAPI.t(api['Waze/Unknown/' + unknownCount].index);
  165. WMEAPI.require.define(module);
  166. }
  167. unknownCount++;
  168. }
  169. }
  170.  
  171. // restore the original func
  172. window.webpackJsonp=WMEAPI.tmp;
  173.  
  174. // set the require public if needed
  175. // if so: others scripts must wait for the window.require to be available before using it.
  176. window.require = WMEAPI.require;
  177. // all available functions are in WMEAPI.require.define.modules
  178. // console.debug this variable to read it:
  179. // console.debug('Modules: ', WMEAPI.require.define.modules);
  180. // run your script here:
  181. // setTimeout(yourscript);
  182. // again taken from WME code. Not sure about what it does.
  183. //if (i[0]) return ret;
  184. };
  185.  
  186. // some kind of global vars and init
  187. WMEAPI.s = {};
  188. WMEAPI.r = {
  189. 0: 0
  190. };
  191.  
  192. // hacking finished
  193.  
  194. // load again WME through our patched func
  195. WMEAPI.WMEHACK_Injected_script = document.createElement("script");
  196. WMEAPI.WMEHACK_Injected_script.setAttribute("type", "application/javascript");
  197. WMEAPI.WMEHACK_Injected_script.src = WMEAPI.url;
  198. document.body.appendChild(WMEAPI.WMEHACK_Injected_script);
  199. console.log("d2 fix complete");
  200. }
  201.  
  202. function Geometry(){
  203. //var geometry = WazeWrapBeta.Geometry;
  204.  
  205. //Converts to "normal" GPS coordinates
  206. this.ConvertTo4326 = function (long, lat){
  207. var projI=new OpenLayers.Projection("EPSG:900913");
  208. var projE=new OpenLayers.Projection("EPSG:4326");
  209. return (new OpenLayers.LonLat(long, lat)).transform(projI,projE);
  210. };
  211. this.ConvertTo900913 = function (long, lat){
  212. var projI=new OpenLayers.Projection("EPSG:900913");
  213. var projE=new OpenLayers.Projection("EPSG:4326");
  214. return (new OpenLayers.LonLat(long, lat)).transform(projE,projI);
  215. };
  216.  
  217. //Converts the Longitudinal offset to an offset in 4326 gps coordinates
  218. this.CalculateLongOffsetGPS = function(longMetersOffset, long, lat)
  219. {
  220. var R= 6378137; //Earth's radius
  221. var dLon = longMetersOffset / (R * Math.cos(Math.PI * lat / 180)); //offset in radians
  222. var lon0 = dLon * (180 / Math.PI); //offset degrees
  223.  
  224. return lon0;
  225. };
  226.  
  227. //Converts the Latitudinal offset to an offset in 4326 gps coordinates
  228. this.CalculateLatOffsetGPS = function(latMetersOffset, lat)
  229. {
  230. var R= 6378137; //Earth's radius
  231. var dLat = latMetersOffset/R;
  232. var lat0 = dLat * (180 /Math.PI); //offset degrees
  233.  
  234. return lat0;
  235. };
  236. /**
  237. * Checks if the given geometry is on screen
  238. * @function WazeWrapBeta.Geometry.isGeometryInMapExtent
  239. * @param {OpenLayers.Geometry} Geometry to check if any part of is in the current viewport
  240. */
  241. this.isLonLatInMapExtent = function (lonLat) {
  242. 'use strict';
  243. return lonLat && W.map.getExtent().containsLonLat(lonLat);
  244. };
  245. /**
  246. * Checks if the given geometry is on screen
  247. * @function WazeWrapBeta.Geometry.isGeometryInMapExtent
  248. * @param {OpenLayers.Geometry} Geometry to check if any part of is in the current viewport
  249. */
  250. this.isGeometryInMapExtent = function (geometry) {
  251. 'use strict';
  252. return geometry && geometry.getBounds &&
  253. W.map.getExtent().intersectsBounds(geometry.getBounds());
  254. };
  255. /**
  256. * Calculates the distance between two given points, returned in meters
  257. * @function WazeWrapBeta.Geometry.calculateDistance
  258. * @param {OpenLayers.Geometry.Point} An array of OL.Geometry.Point with which to measure the total distance. A minimum of 2 points is needed.
  259. */
  260. this.calculateDistance = function(pointArray) {
  261. if(pointArray.length < 2)
  262. return 0;
  263.  
  264. var line = new OpenLayers.Geometry.LineString(pointArray);
  265. length = line.getGeodesicLength(W.map.getProjectionObject());
  266. return length; //multiply by 3.28084 to convert to feet
  267. };
  268. this.findClosestSegment = function(mygeometry, ignorePLR, ignoreUnnamedPR){
  269. var onscreenSegments = WazeWrapBeta.Model.getOnscreenSegments();
  270. var minDistance = Infinity;
  271. var closestSegment;
  272. for (s in onscreenSegments) {
  273. if (!onscreenSegments.hasOwnProperty(s))
  274. continue;
  275.  
  276. segmentType = onscreenSegments[s].attributes.roadType;
  277. if (segmentType === 10 || segmentType === 3 || segmentType === 16 || segmentType === 18 || segmentType === 19 || segmentType === 5) //10 ped boardwalk, 16 stairway, 18 railroad, 19 runway, 3 freeway, 5 walking trail
  278. continue;
  279. if(ignorePLR)
  280. if(segmentType === 20) //PLR
  281. continue;
  282.  
  283. if(ignoreUnnamedPR)
  284. if(segmentType === 17 && WazeWrapBeta.Model.getStreetName(onscreenSegments[s].attributes.primaryStreetID) === null) //PR
  285. continue;
  286.  
  287.  
  288. distanceToSegment = mygeometry.distanceTo(onscreenSegments[s].geometry, {details: true});
  289.  
  290. if (distanceToSegment.distance < minDistance) {
  291. minDistance = distanceToSegment.distance;
  292. closestSegment = onscreenSegments[s];
  293. }
  294. }
  295. return closestSegment;
  296. };
  297. };
  298.  
  299. function Model(){
  300.  
  301. this.getPrimaryStreetID = function(segmentID){
  302. return W.model.segments.get(segmentID).attributes.primaryStreetID;
  303. };
  304.  
  305. this.getStreetName = function(primaryStreetID){
  306. return W.model.streets.get(primaryStreetID).name;
  307. };
  308.  
  309. this.getCityID = function(primaryStreetID){
  310. return W.model.streets.get(primaryStreetID).cityID;
  311. };
  312.  
  313. this.getCityName = function(primaryStreetID){
  314. return W.model.cities.get(this.getCityID(primaryStreetID)).attributes.Name;
  315. };
  316.  
  317. this.getStateName = function(primaryStreetID){
  318. return W.model.states.get(getStateID(primaryStreetID)).Name;
  319. };
  320.  
  321. this.getStateID = function(primaryStreetID){
  322. return W.model.cities.get(primaryStreetID).attributes.stateID;
  323. };
  324.  
  325. this.getCountryID = function(primaryStreetID){
  326. return W.model.cities.get(this.getCityID(primaryStreetID)).attributes.CountryID;
  327. };
  328.  
  329. this.getCountryName = function(primaryStreetID){
  330. return W.model.countries.get(getCountryID(primaryStreetID)).name;
  331. };
  332.  
  333. this.getCityNameFromSegmentObj = function(segObj){
  334. return this.getCityName(segObj.attributes.primaryStreetID);
  335. };
  336.  
  337. this.getStateNameFromSegmentObj = function(segObj){
  338. return this.getStateName(segObj.attributes.primaryStreetID);
  339. };
  340.  
  341. //returns an array of segmentIDs for all segments that are part of the same roundabout as the passed segment
  342. this.getAllRoundaboutSegmentsFromObj = function(segObj){
  343. if(segObj.model.attributes.junctionID === null)
  344. return null;
  345.  
  346. return W.model.junctions.objects[segObj.model.attributes.junctionID].segIDs;
  347. };
  348.  
  349. this.getAllRoundaboutJunctionNodesFromObj = function(segObj){
  350. var RASegs = this.getAllRoundaboutSegmentsFromObj(segObj);
  351. var RAJunctionNodes = [];
  352. for(i=0; i< RASegs.length; i++){
  353. RAJunctionNodes.push(W.model.nodes.objects[W.model.segments.get(RASegs[i]).attributes.toNodeID]);
  354.  
  355. }
  356. return RAJunctionNodes;
  357. };
  358.  
  359. this.isRoundaboutSegmentID = function(segmentID){
  360. if(W.model.segments.get(segmentID).attributes.junctionID === null)
  361. return false;
  362. else
  363. return true;
  364. };
  365.  
  366. this.isRoundaboutSegmentObj = function(segObj){
  367. if(segObj.model.attributes.junctionID === null)
  368. return false;
  369. else
  370. return true;
  371. };
  372. this.getOnscreenSegments = function(){
  373. var segments = W.model.segments.objects;
  374. var mapExtent = W.map.getExtent();
  375. var onScreenSegments = [];
  376. var seg;
  377.  
  378. for (s in segments) {
  379. if (!segments.hasOwnProperty(s))
  380. continue;
  381.  
  382. seg = W.model.segments.get(s);
  383. if (mapExtent.intersectsBounds(seg.geometry.getBounds()))
  384. onScreenSegments.push(seg);
  385. }
  386. return onScreenSegments;
  387. };
  388.  
  389. /**
  390. * Defers execution of a callback function until the WME map and data
  391. * model are ready. Call this function before calling a function that
  392. * causes a map and model reload, such as W.map.moveTo(). After the
  393. * move is completed the callback function will be executed.
  394. * @function WazeWrapBeta.Model.onModelReady
  395. * @param {Function} callback The callback function to be executed.
  396. * @param {Boolean} now Whether or not to call the callback now if the
  397. * model is currently ready.
  398. * @param {Object} context The context in which to call the callback.
  399. */
  400. this.onModelReady = function (callback, now, context) {
  401. var deferModelReady = function () {
  402. return $.Deferred(function (dfd) {
  403. var resolve = function () {
  404. dfd.resolve();
  405. W.model.events.unregister('mergeend', null, resolve);
  406. };
  407. W.model.events.register('mergeend', null, resolve);
  408. }).promise();
  409. };
  410. var deferMapReady = function () {
  411. return $.Deferred(function (dfd) {
  412. var resolve = function () {
  413. dfd.resolve();
  414. W.vent.off('operationDone', resolve);
  415. };
  416. W.vent.on('operationDone', resolve);
  417. }).promise();
  418. };
  419.  
  420. if (typeof callback === 'function') {
  421. context = context || callback;
  422. if (now && WazeWrapBeta.Util.mapReady() && WazeWrapBeta.Util.modelReady()) {
  423. callback.call(context);
  424. } else {
  425. $.when(deferMapReady() && deferModelReady()).
  426. then(function () {
  427. callback.call(context);
  428. });
  429. }
  430. }
  431. };
  432. /**
  433. * Retrives a route from the Waze Live Map.
  434. * @class
  435. * @name wLib.Model.RouteSelection
  436. * @param firstSegment The segment to use as the start of the route.
  437. * @param lastSegment The segment to use as the destination for the route.
  438. * @param {Array|Function} callback A function or array of funcitons to be
  439. * executed after the route
  440. * is retrieved. 'This' in the callback functions will refer to the
  441. * RouteSelection object.
  442. * @param {Object} options A hash of options for determining route. Valid
  443. * options are:
  444. * fastest: {Boolean} Whether or not the fastest route should be used.
  445. * Default is false, which selects the shortest route.
  446. * freeways: {Boolean} Whether or not to avoid freeways. Default is false.
  447. * dirt: {Boolean} Whether or not to avoid dirt roads. Default is false.
  448. * longtrails: {Boolean} Whether or not to avoid long dirt roads. Default
  449. * is false.
  450. * uturns: {Boolean} Whether or not to allow U-turns. Default is true.
  451. * @return {wLib.Model.RouteSelection} The new RouteSelection object.
  452. * @example: // The following example will retrieve a route from the Live Map and select the segments in the route.
  453. * selection = W.selectionManager.selectedItems;
  454. * myRoute = new wLib.Model.RouteSelection(selection[0], selection[1], function(){this.selectRouteSegments();}, {fastest: true});
  455. */
  456. this.RouteSelection = function (firstSegment, lastSegment, callback, options) {
  457. var i,
  458. n,
  459. start = this.getSegmentCenterLonLat(firstSegment),
  460. end = this.getSegmentCenterLonLat(lastSegment);
  461. this.options = {
  462. fastest: options && options.fastest || false,
  463. freeways: options && options.freeways || false,
  464. dirt: options && options.dirt || false,
  465. longtrails: options && options.longtrails || false,
  466. uturns: options && options.uturns || true
  467. };
  468. this.requestData = {
  469. from: 'x:' + start.x + ' y:' + start.y + ' bd:true',
  470. to: 'x:' + end.x + ' y:' + end.y + ' bd:true',
  471. returnJSON: true,
  472. returnGeometries: true,
  473. returnInstructions: false,
  474. type: this.options.fastest ? 'HISTORIC_TIME' : 'DISTANCE',
  475. clientVersion: '4.0.0',
  476. timeout: 60000,
  477. nPaths: 3,
  478. options: this.setRequestOptions(this.options)
  479. };
  480. this.callbacks = [];
  481. if (callback) {
  482. if (!(callback instanceof Array)) {
  483. callback = [callback];
  484. }
  485. for (i = 0, n = callback.length; i < n; i++) {
  486. if ('function' === typeof callback[i]) {
  487. this.callbacks.push(callback[i]);
  488. }
  489. }
  490. }
  491. this.routeData = null;
  492. this.getRouteData();
  493. };
  494.  
  495. this.RouteSelection.prototype =
  496. /** @lends wLib.Model.RouteSelection.prototype */ {
  497. /**
  498. * Formats the routing options string for the ajax request.
  499. * @private
  500. * @param {Object} options Object containing the routing options.
  501. * @return {String} String containing routing options.
  502. */
  503. setRequestOptions: function (options) {
  504. return 'AVOID_TOLL_ROADS:' + (options.tolls ? 't' : 'f') + ',' +
  505. 'AVOID_PRIMARIES:' + (options.freeways ? 't' : 'f') + ',' +
  506. 'AVOID_TRAILS:' + (options.dirt ? 't' : 'f') + ',' +
  507. 'AVOID_LONG_TRAILS:' + (options.longtrails ? 't' : 'f') + ',' +
  508. 'ALLOW_UTURNS:' + (options.uturns ? 't' : 'f');
  509. },
  510. /**
  511. * Gets the center of a segment in LonLat form.
  512. * @private
  513. * @param segment A Waze model segment object.
  514. * @return {OpenLayers.LonLat} The LonLat object corresponding to the
  515. * center of the segment.
  516. */
  517. getSegmentCenterLonLat: function (segment) {
  518. var x, y, componentsLength, midPoint;
  519. if (segment) {
  520. componentsLength = segment.geometry.components.length;
  521. midPoint = Math.floor(componentsLength / 2);
  522. if (componentsLength % 2 === 1) {
  523. x = segment.geometry.components[midPoint].x;
  524. y = segment.geometry.components[midPoint].y;
  525. } else {
  526. x = (segment.geometry.components[midPoint - 1].x +
  527. segment.geometry.components[midPoint].x) / 2;
  528. y = (segment.geometry.components[midPoint - 1].y +
  529. segment.geometry.components[midPoint].y) / 2;
  530. }
  531. return new OL.Geometry.Point(x, y).
  532. transform(W.map.getProjectionObject(), 'EPSG:4326');
  533. }
  534.  
  535. },
  536. /**
  537. * Gets the route from Live Map and executes any callbacks upon success.
  538. * @private
  539. * @returns The ajax request object. The responseJSON property of the
  540. * returned object
  541. * contains the route information.
  542. *
  543. */
  544. getRouteData: function () {
  545. var i,
  546. n,
  547. that = this;
  548. return $.ajax({
  549. dataType: 'json',
  550. url: this.getURL(),
  551. data: this.requestData,
  552. dataFilter: function (data, dataType) {
  553. return data.replace(/NaN/g, '0');
  554. },
  555. success: function (data) {
  556. that.routeData = data;
  557. for (i = 0, n = that.callbacks.length; i < n; i++) {
  558. that.callbacks[i].call(that);
  559. }
  560. }
  561. });
  562. },
  563. /**
  564. * Extracts the IDs from all segments on the route.
  565. * @private
  566. * @return {Array} Array containing an array of segment IDs for
  567. * each route alternative.
  568. */
  569. getRouteSegmentIDs: function () {
  570. var i, j, route, len1, len2, segIDs = [],
  571. routeArray = [],
  572. data = this.routeData;
  573. if ('undefined' !== typeof data.alternatives) {
  574. for (i = 0, len1 = data.alternatives.length; i < len1; i++) {
  575. route = data.alternatives[i].response.results;
  576. for (j = 0, len2 = route.length; j < len2; j++) {
  577. routeArray.push(route[j].path.segmentId);
  578. }
  579. segIDs.push(routeArray);
  580. routeArray = [];
  581. }
  582. } else {
  583. route = data.response.results;
  584. for (i = 0, len1 = route.length; i < len1; i++) {
  585. routeArray.push(route[i].path.segmentId);
  586. }
  587. segIDs.push(routeArray);
  588. }
  589. return segIDs;
  590. },
  591. /**
  592. * Gets the URL to use for the ajax request based on country.
  593. * @private
  594. * @return {String} Relative URl to use for route ajax request.
  595. */
  596. getURL: function () {
  597. if (W.model.countries.get(235) || W.model.countries.get(40)) {
  598. return '/RoutingManager/routingRequest';
  599. } else if (W.model.countries.get(106)) {
  600. return '/il-RoutingManager/routingRequest';
  601. } else {
  602. return '/row-RoutingManager/routingRequest';
  603. }
  604. },
  605. /**
  606. * Selects all segments on the route in the editor.
  607. * @param {Integer} routeIndex The index of the alternate route.
  608. * Default route to use is the first one, which is 0.
  609. */
  610. selectRouteSegments: function (routeIndex) {
  611. var i, n, seg,
  612. segIDs = this.getRouteSegmentIDs()[Math.floor(routeIndex) || 0],
  613. segments = [];
  614. if ('undefined' === typeof segIDs) {
  615. return;
  616. }
  617. for (i = 0, n = segIDs.length; i < n; i++) {
  618. seg = W.model.segments.get(segIDs[i]);
  619. if ('undefined' !== seg) {
  620. segments.push(seg);
  621. }
  622. }
  623. return W.selectionManager.select(segments);
  624. }
  625. };
  626. };
  627. function User(){
  628. this.Rank = function(){
  629. return W.loginManager.user.normalizedLevel;
  630. };
  631.  
  632. this.Username = function(){
  633. return W.loginManager.user.userName;
  634. };
  635.  
  636. this.isCM = function(){
  637. if(W.loginManager.user.editableCountryIDs.length > 0)
  638. return true;
  639. else
  640. return false;
  641. };
  642. this.isAM = function(){
  643. return W.loginManager.user.isAreaManager;
  644. };
  645. };
  646. function Require(){
  647. this.DragElement = function(){
  648. var myDragElement = OL.Class({
  649. started: !1,
  650. stopDown: !0,
  651. dragging: !1,
  652. touch: !1,
  653. last: null ,
  654. start: null ,
  655. lastMoveEvt: null ,
  656. oldOnselectstart: null ,
  657. interval: 0,
  658. timeoutId: null ,
  659. forced: !1,
  660. active: !1,
  661. initialize: function(e) {
  662. this.map = e,
  663. this.uniqueID = myDragElement.baseID--
  664. },
  665. callback: function(e, t) {
  666. if (this[e])
  667. return this[e].apply(this, t)
  668. },
  669. dragstart: function(e) {
  670. e.xy = new OL.Pixel(e.clientX - this.map.viewPortDiv.offsets[0],e.clientY - this.map.viewPortDiv.offsets[1]);
  671. var t = !0;
  672. return this.dragging = !1,
  673. (OL.Event.isLeftClick(e) || OL.Event.isSingleTouch(e)) && (this.started = !0,
  674. this.start = e.xy,
  675. this.last = e.xy,
  676. OL.Element.addClass(this.map.viewPortDiv, "olDragDown"),
  677. this.down(e),
  678. this.callback("down", [e.xy]),
  679. OL.Event.stop(e),
  680. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart ? document.onselectstart : OL.Function.True),
  681. document.onselectstart = OL.Function.False,
  682. t = !this.stopDown),
  683. t
  684. },
  685. forceStart: function() {
  686. var e = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
  687. return this.started = !0,
  688. this.endOnMouseUp = e,
  689. this.forced = !0,
  690. this.last = {
  691. x: 0,
  692. y: 0
  693. },
  694. this.callback("force")
  695. },
  696. forceEnd: function() {
  697. if (this.forced)
  698. return this.endDrag()
  699. },
  700. dragmove: function(e) {
  701. return this.map.viewPortDiv.offsets && (e.xy = new OL.Pixel(e.clientX - this.map.viewPortDiv.offsets[0],e.clientY - this.map.viewPortDiv.offsets[1])),
  702. this.lastMoveEvt = e,
  703. !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)),
  704. this.dragging = !0,
  705. this.move(e),
  706. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart,
  707. document.onselectstart = OL.Function.False),
  708. this.last = e.xy),
  709. !0
  710. },
  711. dragend: function(e) {
  712. if (e.xy = new OL.Pixel(e.clientX - this.map.viewPortDiv.offsets[0],e.clientY - this.map.viewPortDiv.offsets[1]),
  713. this.started) {
  714. var t = this.start !== this.last;
  715. this.endDrag(),
  716. this.up(e),
  717. this.callback("up", [e.xy]),
  718. t && this.callback("done", [e.xy])
  719. }
  720. return !0
  721. },
  722. endDrag: function() {
  723. this.started = !1,
  724. this.dragging = !1,
  725. this.forced = !1,
  726. OL.Element.removeClass(this.map.viewPortDiv, "olDragDown"),
  727. document.onselectstart = this.oldOnselectstart
  728. },
  729. down: function(e) {},
  730. move: function(e) {},
  731. up: function(e) {},
  732. out: function(e) {},
  733. mousedown: function(e) {
  734. return this.dragstart(e)
  735. },
  736. touchstart: function(e) {
  737. return this.touch || (this.touch = !0,
  738. this.map.events.un({
  739. mousedown: this.mousedown,
  740. mouseup: this.mouseup,
  741. mousemove: this.mousemove,
  742. click: this.click,
  743. scope: this
  744. })),
  745. this.dragstart(e)
  746. },
  747. mousemove: function(e) {
  748. return this.dragmove(e)
  749. },
  750. touchmove: function(e) {
  751. return this.dragmove(e)
  752. },
  753. removeTimeout: function() {
  754. if (this.timeoutId = null ,
  755. this.dragging)
  756. return this.mousemove(this.lastMoveEvt)
  757. },
  758. mouseup: function(e) {
  759. if (!this.forced || this.endOnMouseUp)
  760. return this.started ? this.dragend(e) : void 0
  761. },
  762. touchend: function(e) {
  763. if (e.xy = this.last,
  764. !this.forced)
  765. return this.dragend(e)
  766. },
  767. click: function(e) {
  768. return this.start === this.last
  769. },
  770. activate: function(e) {
  771. this.$el = e,
  772. this.active = !0;
  773. var t = $(this.map.viewPortDiv);
  774. return this.$el.on("mousedown.drag-" + this.uniqueID, $.proxy(this.mousedown, this)),
  775. this.$el.on("touchstart.drag-" + this.uniqueID, $.proxy(this.touchstart, this)),
  776. $(document).on("mouseup.drag-" + this.uniqueID, $.proxy(this.mouseup, this)),
  777. t.on("mousemove.drag-" + this.uniqueID, $.proxy(this.mousemove, this)),
  778. t.on("touchmove.drag-" + this.uniqueID, $.proxy(this.touchmove, this)),
  779. t.on("touchend.drag-" + this.uniqueID, $.proxy(this.touchend, this))
  780. },
  781. deactivate: function() {
  782. return this.active = !1,
  783. this.$el.off(".drag-" + this.uniqueID),
  784. $(this.map.viewPortDiv).off(".drag-" + this.uniqueID),
  785. $(document).off(".drag-" + this.uniqueID),
  786. this.touch = !1,
  787. this.started = !1,
  788. this.forced = !1,
  789. this.dragging = !1,
  790. this.start = null ,
  791. this.last = null ,
  792. OL.Element.removeClass(this.map.viewPortDiv, "olDragDown")
  793. },
  794. adjustXY: function(e) {
  795. var t = OL.Util.pagePosition(this.map.viewPortDiv);
  796. return e.xy.x -= t[0],
  797. e.xy.y -= t[1]
  798. },
  799. CLASS_NAME: "W.Handler.DragElement"
  800. });
  801. myDragElement.baseID = 0;
  802. return myDragElement;
  803. };
  804. this.DivIcon = OpenLayers.Class({
  805. className: null ,
  806. $div: null ,
  807. events: null ,
  808. initialize: function(e, t) {
  809. this.className = e,
  810. this.moveWithTransform = !!t,
  811. this.$div = $("<div />").addClass(e),
  812. this.div = this.$div.get(0),
  813. this.imageDiv = this.$div.get(0);
  814. },
  815. destroy: function() {
  816. this.erase(),
  817. this.$div = null;
  818. },
  819. clone: function() {
  820. return new i(this.className);
  821. },
  822. draw: function(e) {
  823. return this.moveWithTransform ? (this.$div.css({
  824. transform: "translate(" + e.x + "px, " + e.y + "px)"
  825. }),
  826. this.$div.css({
  827. position: "absolute"
  828. })) : this.$div.css({
  829. position: "absolute",
  830. left: e.x,
  831. top: e.y
  832. }),
  833. this.$div.get(0);
  834. },
  835. moveTo: function(e) {
  836. null !== e && (this.px = e),
  837. null === this.px ? this.display(!1) : this.moveWithTransform ? this.$div.css({
  838. transform: "translate(" + this.px.x + "px, " + this.px.y + "px)"
  839. }) : this.$div.css({
  840. left: this.px.x,
  841. top: this.px.y
  842. });
  843. },
  844. erase: function() {
  845. this.$div.remove();
  846. },
  847. display: function(e) {
  848. this.$div.toggle(e);
  849. },
  850. isDrawn: function() {
  851. return !!this.$div.parent().length;
  852. },
  853. bringToFront: function() {
  854. if (this.isDrawn()) {
  855. var e = this.$div.parent();
  856. this.$div.detach().appendTo(e);
  857. }
  858. },
  859. forceReflow: function() {
  860. return this.$div.get(0).offsetWidth;
  861. },
  862. CLASS_NAME: "Waze.DivIcon"
  863. });
  864. };
  865. function Util(){
  866. /**
  867. * Function to defer function execution until an element is present on
  868. * the page.
  869. * @function WazeWrapBeta.Util.waitForElement
  870. * @param {String} selector The CSS selector string or a jQuery object
  871. * to find before executing the callback.
  872. * @param {Function} callback The function to call when the page
  873. * element is detected.
  874. * @param {Object} [context] The context in which to call the callback.
  875. */
  876. this.waitForElement = function (selector, callback, context) {
  877. var jqObj;
  878.  
  879. if (!selector || typeof callback !== 'function') {
  880. return;
  881. }
  882.  
  883. jqObj = typeof selector === 'string' ?
  884. $(selector) : selector instanceof $ ? selector : null;
  885.  
  886. if (!jqObj.size()) {
  887. window.requestAnimationFrame(function () {
  888. WazeWrapBeta.Util.waitForElement(selector, callback, context);
  889. });
  890. } else {
  891. callback.call(context || callback);
  892. }
  893. };
  894.  
  895. /**
  896. * Function to track the ready state of the map.
  897. * @function WazeWrapBeta.Util.mapReady
  898. * @return {Boolean} Whether or not a map operation is pending or
  899. * undefined if the function has not yet seen a map ready event fired.
  900. */
  901. this.mapReady = function () {
  902. var mapReady = true;
  903. W.vent.on('operationPending', function () {
  904. mapReady = false;
  905. });
  906. W.vent.on('operationDone', function () {
  907. mapReady = true;
  908. });
  909. return function () {
  910. return mapReady;
  911. };
  912. } ();
  913.  
  914. /**
  915. * Function to track the ready state of the model.
  916. * @function WazeWrapBeta.Util.modelReady
  917. * @return {Boolean} Whether or not the model has loaded objects or
  918. * undefined if the function has not yet seen a model ready event fired.
  919. */
  920. this.modelReady = function () {
  921. var modelReady = true;
  922. W.model.events.register('mergestart', null, function () {
  923. modelReady = false;
  924. });
  925. W.model.events.register('mergeend', null, function () {
  926. modelReady = true;
  927. });
  928. return function () {
  929. return modelReady;
  930. };
  931. } ();
  932. };
  933.  
  934. function Interface() {
  935. /**
  936. * Generates id for message bars.
  937. * @private
  938. */
  939. var getNextID = function () {
  940. var id = 1;
  941. return function () {
  942. return id++;
  943. };
  944. } ();
  945. this.Shortcut = OL.Class(this, /** @lends WazeWrapBeta.Interface.Shortcut.prototype */ {
  946. name: null,
  947. desc: null,
  948. group: null,
  949. title: null,
  950. shortcut: {},
  951. callback: null,
  952. scope: null,
  953. groupExists: false,
  954. actionExists: false,
  955. eventExists: false,
  956. defaults: {
  957. group: 'default'
  958. },
  959. /**
  960. * Creates a new {WazeWrapBeta.Interface.Shortcut}.
  961. * @class
  962. * @name WazeWrapBeta.Interface.Shortcut
  963. * @param name {String} The name of the shortcut.
  964. * @param desc {String} The description to display for the shortcut
  965. * @param group {String} The name of the shortcut group.
  966. * @param title {String} The title to display for this group in the Keyboard shortcuts list
  967. * @param shortcut {String} The shortcut key(s). The shortcut
  968. * should be of the form 'i' where i is the keyboard shortuct or
  969. * include modifier keys such as 'CSA+i', where C = the control
  970. * key, S = the shift key, A = the alt key, and i = the desired
  971. * keyboard shortcut. The modifier keys are optional.
  972. * @param callback {Function} The function to be called by the
  973. * shortcut.
  974. * @param scope {Object} The object to be used as this by the
  975. * callback.
  976. * @return {WazeWrapBeta.Interface.Shortcut} The new shortcut object.
  977. * @example //Creates new shortcut and adds it to the map.
  978. * shortcut = new WazeWrapBeta.Interface.Shortcut('myName', 'myGroup', 'C+p', callbackFunc, null).add();
  979. */
  980. initialize: function (name, desc, group, title, shortcut, callback, scope) {
  981. if ('string' === typeof name && name.length > 0 &&
  982. 'string' === typeof shortcut &&
  983. 'function' === typeof callback) {
  984. this.name = name;
  985. this.desc = desc;
  986. this.group = group || this.defaults.group;
  987. this.title = title;
  988. this.callback = callback;
  989. this.shortcut[shortcut] = name;
  990. if ('object' !== typeof scope) {
  991. this.scope = null;
  992. } else {
  993. this.scope = scope;
  994. }
  995. return this;
  996. }
  997. },
  998. /**
  999. * Determines if the shortcut's group already exists.
  1000. * @private
  1001. */
  1002. doesGroupExist: function () {
  1003. this.groupExists = 'undefined' !== typeof W.accelerators.Groups[this.group] &&
  1004. undefined !== typeof W.accelerators.Groups[this.group].members;
  1005. return this.groupExists;
  1006. },
  1007. /**
  1008. * Determines if the shortcut's action already exists.
  1009. * @private
  1010. */
  1011. doesActionExist: function () {
  1012. this.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];
  1013. return this.actionExists;
  1014. },
  1015. /**
  1016. * Determines if the shortcut's event already exists.
  1017. * @private
  1018. */
  1019. doesEventExist: function () {
  1020. this.eventExists = 'undefined' !== typeof W.accelerators.events.listeners[this.name] &&
  1021. W.accelerators.events.listeners[this.name].length > 0 &&
  1022. this.callback === W.accelerators.events.listeners[this.name][0].func &&
  1023. this.scope === W.accelerators.events.listeners[this.name][0].obj;
  1024. return this.eventExists;
  1025. },
  1026. /**
  1027. * Creates the shortcut's group.
  1028. * @private
  1029. */
  1030. createGroup: function () {
  1031. W.accelerators.Groups[this.group] = [];
  1032. W.accelerators.Groups[this.group].members = [];
  1033. if(this.title && !I18n.translations.en.keyboard_shortcuts.groups[this.group]){
  1034. I18n.translations.en.keyboard_shortcuts.groups[this.group] = [];
  1035. I18n.translations.en.keyboard_shortcuts.groups[this.group].description = this.title;
  1036. I18n.translations.en.keyboard_shortcuts.groups[this.group].members = [];
  1037. }
  1038. },
  1039. /**
  1040. * Registers the shortcut's action.
  1041. * @private
  1042. */
  1043. addAction: function () {
  1044. if(this.title)
  1045. I18n.translations.en.keyboard_shortcuts.groups[this.group].members[this.name] = this.desc;
  1046. W.accelerators.addAction(this.name, { group: this.group });
  1047. },
  1048. /**
  1049. * Registers the shortcut's event.
  1050. * @private
  1051. */
  1052. addEvent: function () {
  1053. W.accelerators.events.register(this.name, this.scope, this.callback);
  1054. },
  1055. /**
  1056. * Registers the shortcut's keyboard shortcut.
  1057. * @private
  1058. */
  1059. registerShortcut: function () {
  1060. W.accelerators._registerShortcuts(this.shortcut);
  1061. },
  1062. /**
  1063. * Adds the keyboard shortcut to the map.
  1064. * @return {WazeWrapBeta.Interface.Shortcut} The keyboard shortcut.
  1065. */
  1066. add: function () {
  1067. /* If the group is not already defined, initialize the group. */
  1068. if (!this.doesGroupExist()) {
  1069. this.createGroup();
  1070. }
  1071.  
  1072. /* Clear existing actions with same name */
  1073. if (this.doesActionExist()) {
  1074. W.accelerators.Actions[this.name] = null;
  1075. }
  1076. this.addAction();
  1077.  
  1078. /* Register event only if it's not already registered */
  1079. if (!this.doesEventExist()) {
  1080. this.addEvent();
  1081. }
  1082.  
  1083. /* Finally, register the shortcut. */
  1084. this.registerShortcut();
  1085. return this;
  1086. },
  1087. /**
  1088. * Removes the keyboard shortcut from the map.
  1089. * @return {WazeWrapBeta.Interface.Shortcut} The keyboard shortcut.
  1090. */
  1091. remove: function () {
  1092. if (this.doesEventExist()) {
  1093. W.accelerators.events.unregister(this.name, this.scope, this.callback);
  1094. }
  1095. if (this.doesActionExist()) {
  1096. delete W.accelerators.Actions[this.name];
  1097. }
  1098. //remove shortcut?
  1099. return this;
  1100. },
  1101. /**
  1102. * Changes the keyboard shortcut and applies changes to the map.
  1103. * @return {WazeWrapBeta.Interface.Shortcut} The keyboard shortcut.
  1104. */
  1105. change: function (shortcut) {
  1106. if (shortcut) {
  1107. this.shortcut = {};
  1108. this.shortcut[shortcut] = this.name;
  1109. this.registerShortcut();
  1110. }
  1111. return this;
  1112. }
  1113. }),
  1114.  
  1115. this.Tab = OL.Class(this, {
  1116. /** @lends WazeWrapBeta.Interface.Tab */
  1117. TAB_SELECTOR: '#user-tabs ul.nav-tabs',
  1118. CONTENT_SELECTOR: '#user-info div.tab-content',
  1119. callback: null,
  1120. $content: null,
  1121. context: null,
  1122. $tab: null,
  1123. /**
  1124. * Creates a new WazeWrapBeta.Interface.Tab. The tab is appended to the WME
  1125. * editor sidebar and contains the passed HTML content.
  1126. * @class
  1127. * @name WazeWrapBeta.Interface.Tab
  1128. * @param {String} name The name of the tab. Should not contain any
  1129. * special characters.
  1130. * @param {String} content The HTML content of the tab.
  1131. * @param {Function} [callback] A function to call upon successfully
  1132. * appending the tab.
  1133. * @param {Object} [context] The context in which to call the callback
  1134. * function.
  1135. * @return {WazeWrapBeta.Interface.Tab} The new tab object.
  1136. * @example //Creates new tab and adds it to the page.
  1137. * new WazeWrapBeta.Interface.Tab('thebestscriptever', '<div>Hello World!</div>');
  1138. */
  1139. initialize: function (name, content, callback, context) {
  1140. var idName, i = 0;
  1141. if (name && 'string' === typeof name &&
  1142. content && 'string' === typeof content) {
  1143. if (callback && 'function' === typeof callback) {
  1144. this.callback = callback;
  1145. this.context = context || callback;
  1146. }
  1147. /* Sanitize name for html id attribute */
  1148. idName = name.toLowerCase().replace(/[^a-z-_]/g, '');
  1149. /* Make sure id will be unique on page */
  1150. while (
  1151. $('#sidepanel-' + (i ? idName + i : idName)).length > 0) {
  1152. i++;
  1153. }
  1154. if (i) {
  1155. idName = idName + i;
  1156. }
  1157. /* Create tab and content */
  1158. this.$tab = $('<li/>')
  1159. .append($('<a/>')
  1160. .attr({
  1161. 'href': '#sidepanel-' + idName,
  1162. 'data-toggle': 'tab',
  1163. })
  1164. .text(name));
  1165. this.$content = $('<div/>')
  1166. .addClass('tab-pane')
  1167. .attr('id', 'sidepanel-' + idName)
  1168. .html(content);
  1169.  
  1170. this.appendTab();
  1171. }
  1172. },
  1173.  
  1174. append: function (content) {
  1175. this.$content.append(content);
  1176. },
  1177.  
  1178. appendTab: function () {
  1179. WazeWrapBeta.Util.waitForElement(
  1180. this.TAB_SELECTOR + ',' + this.CONTENT_SELECTOR,
  1181. function () {
  1182. $(this.TAB_SELECTOR).append(this.$tab);
  1183. $(this.CONTENT_SELECTOR).first().append(this.$content);
  1184. if (this.callback) {
  1185. this.callback.call(this.context);
  1186. }
  1187. }, this);
  1188. },
  1189.  
  1190. clearContent: function () {
  1191. this.$content.empty();
  1192. },
  1193.  
  1194. destroy: function () {
  1195. this.$tab.remove();
  1196. this.$content.remove();
  1197. }
  1198. });
  1199.  
  1200. this.AddLayerCheckbox = function(group, checkboxText, checked, callback){
  1201. var normaliedText = checkboxText.toLowerCase().replace(/\s/g, '_');
  1202. var checkboxID = "layer-switcher-item_" + normaliedText;
  1203. console.log("Justin3");
  1204. var buildLayerItem = function(isChecked){
  1205. var groupPrefix = 'layer-switcher-group_';
  1206. var groupClass = groupPrefix + group.toLowerCase();
  1207. //W.app.on('change:mode', createLayerCheckbox)
  1208. var groupChildren = $("."+groupClass).parent().parent().find('.children').not('.extended');
  1209. $li = $('<li>');
  1210. $li.html([
  1211. '<div class="controls-container toggler">',
  1212. '<input type="checkbox" id="' + checkboxID + '" class="' + checkboxID + ' toggle">',
  1213. '<label for="' + checkboxID + '"><span class="label-text">' + checkboxText + '</span></label>',
  1214. '</div>',
  1215. ].join(' '));
  1216. groupChildren.append($li);
  1217. $('#' + checkboxID).prop('checked', isChecked);
  1218. $('#' + checkboxID).change(function(){callback(this.checked); sessionStorage[normalizedText] = this.checked;});
  1219. $('.' + groupClass).change(function(){$('#' + checkboxID).prop('disabled', !this.checked); callback(this.checked);});
  1220. }
  1221. console.log("Justin1");
  1222. Waze.app.modeController.model.bind('change:mode', function(){
  1223. alert("Testing!!!");
  1224. //console.log("Justin");
  1225. //console.log(sessionStorage[normalizedText]);
  1226. //console.log((sessionStorage[normalizedText]=='true'));
  1227. //buildLayerItem((sessionStorage[normalizedText]=='true'));
  1228. });
  1229. console.log("Justin2");
  1230. buildLayerItem(checked);
  1231. };
  1232. };
  1233.  
  1234. }.call(this));

QingJ © 2025

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