wLib

A WME developers library

当前为 2015-09-24 提交的版本,查看 最新版本

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

  1. // ==UserScript==
  2. // @name wLib
  3. // @description A WME developers library
  4. // @version 0.1.1
  5. // @author SAR85
  6. // @copyright SAR85
  7. // @license CC BY-NC-ND
  8. // @grant none
  9. // @include https://www.waze.com/editor/*
  10. // @include https://www.waze.com/*/editor/*
  11. // @include https://editor-beta.waze.com/*
  12. // @namespace https://gf.qytechs.cn/users/9321
  13. // ==/UserScript==
  14.  
  15. /* global W */
  16. /* global OL */
  17. /* global wLib */
  18. /* global $ */
  19.  
  20. (function () {
  21. /**
  22. * The wLib namespace.
  23. * @namespace
  24. * @global
  25. */
  26. this.wLib = { VERSION: '0.1' };
  27. }).call(this);
  28.  
  29. /*** GEOMETRY ***/
  30. (function () {
  31. /**
  32. * Namespace for functions related to geometry.
  33. * @memberof wLib
  34. * @namespace
  35. * @name wLib.Geometry
  36. */
  37. this.Geometry = {
  38. /**
  39. * Determines if an {OpenLayers.Geometry} is within the map view.
  40. * @memberof wLib.Geometry
  41. * @param geometry {OpenLayers.Geometry}
  42. * @return {Boolean} Whether or not the geometry is in the map extent.
  43. */
  44. isGeometryInMapExtent: function (geometry) {
  45. 'use strict';
  46. return geometry && geometry.getBounds &&
  47. W.map.getExtent().intersectsBounds(geometry.getBounds())
  48. },
  49. /**
  50. * Determines if an {OpenLayers.LonLat} is within the map view.
  51. * @memberof wLib.Geometry
  52. * @param {OpenLayers.LonLat} lonlat
  53. * @return {Boolean} Whether or not the LonLat is in the map extent.
  54. */
  55. isLonLatInMapExtent: function (lonlat) {
  56. 'use strict';
  57. return lonlat && W.map.getExtent().containsLonLat(lonlat);
  58. }
  59. };
  60. }).call(wLib);
  61.  
  62. /*** MODEL ***/
  63. (function () {
  64. /**
  65. * Namespace for functions related to the model.
  66. * @memberof wLib
  67. * @namespace
  68. * @name wLib.Model
  69. */
  70. this.Model = {};
  71.  
  72. /**
  73. * Gets the IDs of any selected segments.
  74. * @memberof wLib.Model
  75. * @return {Array} Array containing the IDs of selected segments.
  76. */
  77. this.Model.getSelectedSegmentIDs = function () {
  78. 'use strict';
  79. var i, n, selectedItems, item, segments = [];
  80. if (!W.selectionManager.hasSelectedItems()) {
  81. return false;
  82. } else {
  83. selectedItems = W.selectionManager.selectedItems;
  84. for (i = 0, n = selectedItems.length; i < n; i++) {
  85. item = selectedItems[i].model;
  86. if ('segment' === item.type) {
  87. segments.push(item.attributes.id);
  88. }
  89. }
  90. return segments.length === 0 ? false : segments;
  91. }
  92. };
  93.  
  94. /**
  95. * Retrives a route from the Waze Live Map.
  96. * @class
  97. * @name wLib.Model.RouteSelection
  98. * @param firstSegment The segment to use as the start of the route.
  99. * @param lastSegment The segment to use as the destination for the route.
  100. * @param {Array|Function} callback A function or array of funcitons to be executed after the route
  101. * is retrieved. 'This' in the callback functions will refer to the RouteSelection object.
  102. * @param {Object} options A hash of options for determining route. Valid options are:
  103. * fastest: {Boolean} Whether or not the fastest route should be used. Default is false,
  104. * which selects the shortest route.
  105. * freeways: {Boolean} Whether or not to avoid freeways. Default is false.
  106. * dirt: {Boolean} Whether or not to avoid dirt roads. Default is false.
  107. * longtrails: {Boolean} Whether or not to avoid long dirt roads. Default is false.
  108. * uturns: {Boolean} Whether or not to allow U-turns. Default is true.
  109. * @return {wLib.Model.RouteSelection} The new RouteSelection object.
  110. * @example: // The following example will retrieve a route from the Live Map and select the segments in the route.
  111. * selection = W.selectionManager.selectedItems;
  112. * myRoute = new wLib.Model.RouteSelection(selection[0], selection[1], function(){this.selectRouteSegments();}, {fastest: true});
  113. */
  114. this.Model.RouteSelection = function (firstSegment, lastSegment, callback, options) {
  115. var i,
  116. n,
  117. start = this.getSegmentCenterLonLat(firstSegment),
  118. end = this.getSegmentCenterLonLat(lastSegment);
  119. this.options = {
  120. fastest: options && options.fastest || false,
  121. freeways: options && options.freeways || false,
  122. dirt: options && options.dirt || false,
  123. longtrails: options && options.longtrails || false,
  124. uturns: options && options.uturns || true
  125. };
  126. this.requestData = {
  127. from: 'x:' + start.x + ' y:' + start.y + ' bd:true',
  128. to: 'x:' + end.x + ' y:' + end.y + ' bd:true',
  129. returnJSON: true,
  130. returnGeometries: true,
  131. returnInstructions: false,
  132. type: this.options.fastest ? 'HISTORIC_TIME' : 'DISTANCE',
  133. clientVersion: '4.0.0',
  134. timeout: 60000,
  135. nPaths: 3,
  136. options: this.setRequestOptions(this.options)
  137. };
  138. this.callbacks = [];
  139. if (callback) {
  140. if (!(callback instanceof Array)) {
  141. callback = [callback];
  142. }
  143. for (i = 0, n = callback.length; i < n; i++) {
  144. if ('function' === typeof callback[i]) {
  145. this.callbacks.push(callback[i])
  146. }
  147. }
  148. }
  149. this.routeData = null;
  150. this.getRouteData();
  151. };
  152. this.Model.RouteSelection.prototype = /** @lends wLib.Model.RouteSelection.prototype */ {
  153. /**
  154. * Formats the routing options string for the ajax request.
  155. * @private
  156. * @param {Object} options Object containing the routing options.
  157. * @return {String} String containing routing options.
  158. */
  159. setRequestOptions: function (options) {
  160. return 'AVOID_TOLL_ROADS:' + (options.tolls ? 't' : 'f') + ',' +
  161. 'AVOID_PRIMARIES:' + (options.freeways ? 't' : 'f') + ',' +
  162. 'AVOID_TRAILS:' + (options.dirt ? 't' : 'f') + ',' +
  163. 'AVOID_LONG_TRAILS:' + (options.longtrails ? 't' : 'f') + ',' +
  164. 'ALLOW_UTURNS:' + (options.uturns ? 't' : 'f');
  165. },
  166. /**
  167. * Gets the center of a segment in LonLat form.
  168. * @private
  169. * @param segment A Waze model segment object.
  170. * @return {OpenLayers.LonLat} The LonLat object corresponding to the
  171. * center of the segment.
  172. */
  173. getSegmentCenterLonLat: function (segment) {
  174. var x, y, componentsLength, midPoint;
  175. if (segment) {
  176. componentsLength = segment.geometry.components.length;
  177. midPoint = Math.floor(componentsLength / 2);
  178. if (componentsLength % 2 === 1) {
  179. x = segment.geometry.components[midPoint].x;
  180. y = segment.geometry.components[midPoint].y;
  181. } else {
  182. x = (segment.geometry.components[midPoint - 1].x +
  183. segment.geometry.components[midPoint].x) / 2;
  184. y = (segment.geometry.components[midPoint - 1].y +
  185. segment.geometry.components[midPoint].y) / 2;
  186. }
  187. return new OL.Geometry.Point(x, y).transform(W.map.getProjectionObject(), 'EPSG:4326');
  188. }
  189.  
  190. },
  191. /**
  192. * Gets the route from Live Map and executes any callbacks upon success.
  193. * @private
  194. * @returns The ajax request object. The responseJSON property of the returned object
  195. * contains the route information.
  196. *
  197. */
  198. getRouteData: function () {
  199. var i,
  200. n,
  201. that = this;
  202. return $.ajax({
  203. dataType: "json",
  204. url: this.getURL(),
  205. data: this.requestData,
  206. dataFilter: function (data, dataType) {
  207. return data.replace(/NaN/g, '0');
  208. },
  209. success: function (data) {
  210. that.routeData = data;
  211. for (i = 0, n = that.callbacks.length; i < n; i++) {
  212. that.callbacks[i].call(that);
  213. }
  214. }
  215. });
  216. },
  217. /**
  218. * Extracts the IDs from all segments on the route.
  219. * @private
  220. * @return {Array} Array containing an array of segment IDs for
  221. * each route alternative.
  222. */
  223. getRouteSegmentIDs: function () {
  224. var i, j, route, len1, len2, segIDs = [],
  225. routeArray = [],
  226. data = this.routeData;
  227. if ('undefined' !== typeof data.alternatives) {
  228. for (i = 0, len1 = data.alternatives.length; i < len1; i++) {
  229. route = data.alternatives[i].response.results;
  230. for (j = 0, len2 = route.length; j < len2; j++) {
  231. routeArray.push(route[j].path.segmentId);
  232. }
  233. segIDs.push(routeArray);
  234. routeArray = [];
  235. }
  236. } else {
  237. route = data.response.results;
  238. for (i = 0, len1 = route.length; i < len1; i++) {
  239. routeArray.push(route[i].path.segmentId);
  240. }
  241. segIDs.push(routeArray);
  242. }
  243. return segIDs;
  244. },
  245. /**
  246. * Gets the URL to use for the ajax request based on country.
  247. * @private
  248. * @return {String} Relative URl to use for route ajax request.
  249. */
  250. getURL: function () {
  251. if (W.model.countries.get(235) || W.model.countries.get(40)) {
  252. return '/RoutingManager/routingRequest';
  253. } else if (W.model.countries.get(106)) {
  254. return '/il-RoutingManager/routingRequest';
  255. } else {
  256. return '/row-RoutingManager/routingRequest';
  257. }
  258. },
  259. /**
  260. * Selects all segments on the route in the editor.
  261. * @param {Integer} routeIndex The index of the alternate route.
  262. * Default route to use is the first one, which is 0.
  263. */
  264. selectRouteSegments: function (routeIndex) {
  265. var i, n, seg,
  266. segIDs = this.getRouteSegmentIDs()[Math.floor(routeIndex) || 0],
  267. segments = [];
  268. if (undefined === typeof segIDs) {
  269. return;
  270. }
  271. for (i = 0, n = segIDs.length; i < n; i++) {
  272. seg = W.model.segments.get(segIDs[i])
  273. if (undefined !== seg) {
  274. segments.push(seg);
  275. }
  276. }
  277. return W.selectionManager.select(segments);
  278. }
  279. };
  280. }).call(wLib);
  281.  
  282. /*** INTERFACE ***/
  283. (function () {
  284. /**
  285. * Namespace for functions related to the WME interface
  286. * @memberof wLib
  287. * @namespace
  288. * @name wLib.Interface
  289. */
  290. this.Interface = {};
  291.  
  292. this.Interface.MessageBar = OL.Class(this.Interface,
  293. /** @lends wLib.Interface.MessageBar.prototype */ {
  294. $el: null,
  295. messages: {
  296. exampleMessage: {
  297. messageType: 'info',
  298. messageText: 'This is an example message.',
  299. displayDuration: 5000,
  300. skipPrefix: true
  301. }
  302. },
  303. options: {
  304. messagePrefix: null,
  305. displayDuration: 2000
  306. },
  307. styles: {
  308. defaultStyle: {
  309. 'border-radius': 'inherit',
  310. 'background-color': 'rgba(0,0,0,0.7)'
  311. },
  312. error: {
  313. 'border-radius': 'inherit',
  314. 'background-color': 'rgba(180,0,0,0.9)',
  315. 'color': 'black'
  316. },
  317. warn: {
  318. 'border-radius': 'inherit',
  319. 'background-color': 'rgba(230,230,0,0.9)',
  320. 'color': 'black'
  321. },
  322. info: {
  323. 'border-radius': 'inherit',
  324. 'background-color': 'rgba(0,0,230,0.9)'
  325. }
  326. },
  327. /**
  328. * Creates a new {wLib.Interface.MessageBar}.
  329. * @class
  330. * @name wLib.Interface.MessageBar
  331. * @param options {Object} Object containing options to use for the message bar.
  332. * Valid options are: messagePrefix (prefix to prepend to each message; can be
  333. * disabled per message by using skipPrefix), displayDuration (default duration to
  334. * display messages, styles (object with keys representing messageType names and values
  335. * containing objects with css properties for the messageType.)
  336. */
  337. initialize: function (options) {
  338. var $insertTarget = $('#search'),
  339. divStyle = {
  340. 'margin': 'auto',
  341. 'border-radius': '10px',
  342. 'text-align': 'center',
  343. 'width': '40%',
  344. 'font-size': '1em',
  345. 'font-weight': 'bold',
  346. 'color': 'white'
  347. };
  348. OL.Util.extend(this.options, options);
  349. if (this.options.styles) {
  350. OL.Util.extend(this.styles, this.options.styles);
  351. }
  352. if (this.options.messages) {
  353. OL.Util.extend(this.messages, this.options.messages);
  354. }
  355. this.$el = $('<div/>').css(divStyle);
  356. if ($insertTarget.length > 0) {
  357. this.$el.insertAfter($insertTarget);
  358. } else {
  359. console.error('wLib: Unable to find insertTarget for MessageBar.');
  360. }
  361. },
  362. /**
  363. * Adds a style for a message type.
  364. * @param name {String} The name of the messageType.
  365. * @param style {Object} Object containing css properties and values to use
  366. * for the new messageType.
  367. */
  368. addMessageType: function (name, style) {
  369. this.styles[name] = style;
  370. return this;
  371. },
  372. /**
  373. * Removes the message bar from the page.
  374. */
  375. destroy: function () {
  376. this.$el.remove();
  377. },
  378. /**
  379. * Displays a message.
  380. * @private
  381. * @param message The message object or the name of the message to look up.
  382. * @param lookupName {Boolean} If true, message parameter should be string
  383. * and this string is used as message name to look up in saved messages.
  384. */
  385. displayMessage: function (message, lookupName) {
  386. var messageText = '',
  387. style,
  388. duration,
  389. $messageEl = $('<p/>');
  390. // Lookup saved message by name if option is specified.
  391. if (lookupName) {
  392. if (this.messages[message]) {
  393. message = this.messages[message];
  394. } else {
  395. console.debug('wLib: MessageBar: saved message not found.');
  396. return;
  397. }
  398. }
  399. // Make sure message has at least text.
  400. if (!message.messageText) {
  401. return;
  402. }
  403. // Append prefix if one exists and skipPrefix is not specified.
  404. if (!message.skipPrefix && this.options.messagePrefix) {
  405. messageText = this.options.messagePrefix + ' ';
  406. }
  407. // Add messageText
  408. messageText += message.messageText;
  409. // Set style
  410. style = (message.messageType && this.styles[message.messageType]) ?
  411. this.styles[message.messageType] : this.styles.defaultStyle;
  412. // Set duration
  413. duration = (message.displayDuration && !isNaN(message.displayDuration)) ?
  414. message.displayDuration : this.options.displayDuration;
  415. // Update element attributes and add to page
  416. $messageEl.css(style).text(messageText).appendTo(this.$el);
  417. // Display message
  418. $messageEl.fadeIn('fast').delay(duration).fadeOut('slow').remove();
  419. },
  420. /**
  421. * Hides the display.
  422. * @private
  423. */
  424. hideMessage: function ($messageEl, wait) {
  425. setTimeout(function () {
  426. this.$el.fadeOut('slow');
  427. $messageEl.remove();
  428. }, wait);
  429. },
  430. /**
  431. * Displays a message in the message bar.
  432. * @param messageText {String} The text of the message to display.
  433. * @param options {Object} Object containing message options. Valid
  434. * options are messageType (corresponds to the style to use), and
  435. * displayDuration (how long to display message in milliseconds).
  436. */
  437. postNewMessage: function (messageText, options) {
  438. var newMessage = {};
  439. if (messageText) {
  440. newMessage.messageText = messageText;
  441. if (options) {
  442. OL.Util.extend(newMessage, options);
  443. }
  444. }
  445. this.displayMessage(newMessage);
  446. return this;
  447. },
  448. /**
  449. * Displays a saved message in the message bar.
  450. * @param messageName {String} The name of the saved message to display.
  451. */
  452. postSavedMessage: function (messageName) {
  453. if (messageName) {
  454. this.displayMessage(messageName, true);
  455. }
  456. return this;
  457. },
  458. /**
  459. * Adds message to saved messages.
  460. * @param messageName {String} The name of the new message to save.
  461. * @param options {Object} Object containing message options. Valid
  462. * options are messageType (corresponds to the style to use), messageText
  463. * (the content of the message), and displayDuration (how long to display
  464. * message in milliseconds).
  465. */
  466. saveMessage: function (messageName, options) {
  467. var newMessage = {};
  468. if (messageName && options && options.messageText) {
  469. OL.Util.extend(newMessage, options);
  470. this.messages[messageName] = newMessage;
  471. } else {
  472. console.debug('wLib: MessageBar: error saving message.')
  473. }
  474. return this;
  475. },
  476. });
  477.  
  478. this.Interface.Shortcut = OL.Class(this.Interface,
  479. /** @lends wLib.Interface.Shortcut.prototype */ {
  480. name: null,
  481. group: null,
  482. shortcut: {},
  483. callback: null,
  484. scope: null,
  485. groupExists: false,
  486. actionExists: false,
  487. eventExists: false,
  488. /**
  489. * Creates a new {wLib.Interface.Shortcut}.
  490. * @class
  491. * @name wLib.Interface.Shortcut
  492. * @param name {String} The name of the shortcut.
  493. * @param group {String} The name of the shortcut group.
  494. * @param shortcut {String} The shortcut key(s). The shortcut should be of the form
  495. * 'i' where i is the keyboard shortuct or include modifier keys such as'CSA+i',
  496. * where C = the control key, S = the shift key, A = the alt key, and
  497. * i = the desired keyboard shortcut. The modifier keys are optional.
  498. * @param callback {Function} The function to be called by the shortcut.
  499. * @param scope {Object} The object to be used as this by the callback.
  500. * @return {wLib.Interface.Shortcut} The new shortcut object.
  501. * @example //Creates new shortcut and adds it to the map.
  502. * shortcut = new wLib.Interface.Shortcut('myName', 'myGroup', 'C+p', callbackFunc, null).add();
  503. */
  504. initialize: function (name, group, shortcut, callback, scope) {
  505. var defaults = { group: 'default' };
  506. this.CLASS_NAME = 'wLib Shortcut';
  507. if ('string' === typeof name && name.length > 0 &&
  508. 'string' === typeof shortcut && shortcut.length > 0 &&
  509. 'function' === typeof callback) {
  510. this.name = name;
  511. this.group = group || defaults.group;
  512. this.callback = callback;
  513. this.shortcut[shortcut] = name;
  514. if ('object' !== typeof scope) {
  515. this.scope = null;
  516. } else {
  517. this.scope = scope;
  518. }
  519. return this;
  520. }
  521. },
  522. /**
  523. * Determines if the shortcut's group already exists.
  524. * @private
  525. */
  526. doesGroupExist: function () {
  527. this.groupExists = 'undefined' !== typeof W.accelerators.Groups[this.group] &&
  528. undefined !== typeof W.accelerators.Groups[this.group].members &&
  529. W.accelerators.Groups[this.group].length > 0;
  530. return this.groupExists;
  531. },
  532. /**
  533. * Determines if the shortcut's action already exists.
  534. * @private
  535. */
  536. doesActionExist: function () {
  537. this.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];
  538. return this.actionExists;
  539. },
  540. /**
  541. * Determines if the shortcut's event already exists.
  542. * @private
  543. */
  544. doesEventExist: function () {
  545. this.eventExists = 'undefined' !== typeof W.accelerators.events.listeners[this.name] &&
  546. W.accelerators.events.listeners[this.name].length > 0 &&
  547. this.callback === W.accelerators.events.listeners[this.name][0].func &&
  548. this.scope === W.accelerators.events.listeners[this.name][0].obj;
  549. return this.eventExists;
  550. },
  551. /**
  552. * Creates the shortcut's group.
  553. * @private
  554. */
  555. createGroup: function () {
  556. W.accelerators.Groups[this.group] = [];
  557. W.accelerators.Groups[this.group].members = [];
  558. },
  559. /**
  560. * Registers the shortcut's action.
  561. * @private
  562. */
  563. addAction: function () {
  564. W.accelerators.addAction(this.name, { group: this.group });
  565. },
  566. /**
  567. * Registers the shortcut's event.
  568. * @private
  569. */
  570. addEvent: function () {
  571. W.accelerators.events.register(this.name, this.scope, this.callback);
  572. },
  573. /**
  574. * Registers the shortcut's keyboard shortcut.
  575. * @private
  576. */
  577. registerShortcut: function () {
  578. W.accelerators.registerShortcuts(this.shortcut);
  579. },
  580. /**
  581. * Adds the keyboard shortcut to the map.
  582. * @return {wLib.Interface.Shortcut} The keyboard shortcut.
  583. */
  584. add: function () {
  585. /* If the group is not already defined, initialize the group. */
  586. if (!this.doesGroupExist()) {
  587. this.createGroup();
  588. }
  589.  
  590. /* Clear existing actions with same name */
  591. if (this.doesActionExist()) {
  592. W.accelerators.Actions[this.name] = null;
  593. }
  594. this.addAction();
  595.  
  596. /* Register event only if it's not already registered */
  597. if (!this.doesEventExist()) {
  598. this.addEvent();
  599. }
  600.  
  601. /* Finally, register the shortcut. */
  602. this.registerShortcut();
  603. return this;
  604. },
  605. /**
  606. * Removes the keyboard shortcut from the map.
  607. * @return {wLib.Interface.Shortcut} The keyboard shortcut.
  608. */
  609. remove: function () {
  610. if (this.doesEventExist()) {
  611. W.accelerators.events.unregister(this.name, this.scope, this.callback);
  612. }
  613. if (this.doesActionExist()) {
  614. delete W.accelerators.Actions[this.name];
  615. }
  616. //remove shortcut?
  617. return this;
  618. },
  619. /**
  620. * Changes the keyboard shortcut and applies changes to the map.
  621. * @return {wLib.Interface.Shortcut} The keyboard shortcut.
  622. */
  623. change: function (shortcut) {
  624. if (shortcut) {
  625. this.shortcut = {};
  626. this.shortcut[shortcut] = this.name;
  627. this.registerShortcut();
  628. }
  629. return this;
  630. }
  631. });
  632. }).call(wLib);
  633.  
  634. /*** Utilities ***/
  635. (function () {
  636. /**
  637. * Namespace for utility functions.
  638. * @memberof wLib
  639. * @namespace
  640. * @name wLib.Util
  641. */
  642. this.Util = {};
  643.  
  644. /**
  645. * Checks if the argument is a plain object.
  646. * @memberof wLib.Util
  647. * @param item {Any} The item to test.
  648. * @return {Boolean} True if item is plain object.
  649. */
  650. this.Util.isObject = function (item) {
  651. return item && 'object' === typeof item && !Array.isArray(item);
  652. }
  653. }).call(wLib);
  654.  
  655. /*** API ***/
  656. (function () {
  657.  
  658. /**
  659. * Namespace for functions related to WME actions.
  660. * @memberof wLib
  661. * @namespace
  662. * @name wLib.api
  663. */
  664. this.api = {};
  665. }).call(wLib);

QingJ © 2025

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