wLib

A WME developers library

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/9794/76145/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.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: 5000
  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
  419. .fadeIn('fast')
  420. .delay(duration)
  421. .fadeOut('slow', function () {
  422. $(this).remove();
  423. });
  424. },
  425. /**
  426. * Hides the display.
  427. * @private
  428. */
  429. hideMessage: function ($messageEl, wait) {
  430. setTimeout(function () {
  431. this.$el.fadeOut('slow');
  432. $messageEl.remove();
  433. }, wait);
  434. },
  435. /**
  436. * Displays a message in the message bar.
  437. * @param messageText {String} The text of the message to display.
  438. * @param options {Object} Object containing message options. Valid
  439. * options are messageType (corresponds to the style to use), and
  440. * displayDuration (how long to display message in milliseconds).
  441. */
  442. postNewMessage: function (messageText, options) {
  443. var newMessage = {};
  444. if (messageText) {
  445. newMessage.messageText = messageText;
  446. if (options) {
  447. OL.Util.extend(newMessage, options);
  448. }
  449. }
  450. this.displayMessage(newMessage);
  451. return this;
  452. },
  453. /**
  454. * Displays a saved message in the message bar.
  455. * @param messageName {String} The name of the saved message to display.
  456. */
  457. postSavedMessage: function (messageName) {
  458. if (messageName) {
  459. this.displayMessage(messageName, true);
  460. }
  461. return this;
  462. },
  463. /**
  464. * Adds message to saved messages.
  465. * @param messageName {String} The name of the new message to save.
  466. * @param options {Object} Object containing message options. Valid
  467. * options are messageType (corresponds to the style to use), messageText
  468. * (the content of the message), and displayDuration (how long to display
  469. * message in milliseconds).
  470. */
  471. saveMessage: function (messageName, options) {
  472. var newMessage = {};
  473. if (messageName && options && options.messageText) {
  474. OL.Util.extend(newMessage, options);
  475. this.messages[messageName] = newMessage;
  476. } else {
  477. console.debug('wLib: MessageBar: error saving message.')
  478. }
  479. return this;
  480. },
  481. });
  482.  
  483. this.Interface.Shortcut = OL.Class(this.Interface,
  484. /** @lends wLib.Interface.Shortcut.prototype */ {
  485. name: null,
  486. group: null,
  487. shortcut: {},
  488. callback: null,
  489. scope: null,
  490. groupExists: false,
  491. actionExists: false,
  492. eventExists: false,
  493. /**
  494. * Creates a new {wLib.Interface.Shortcut}.
  495. * @class
  496. * @name wLib.Interface.Shortcut
  497. * @param name {String} The name of the shortcut.
  498. * @param group {String} The name of the shortcut group.
  499. * @param shortcut {String} The shortcut key(s). The shortcut should be of the form
  500. * 'i' where i is the keyboard shortuct or include modifier keys such as'CSA+i',
  501. * where C = the control key, S = the shift key, A = the alt key, and
  502. * i = the desired keyboard shortcut. The modifier keys are optional.
  503. * @param callback {Function} The function to be called by the shortcut.
  504. * @param scope {Object} The object to be used as this by the callback.
  505. * @return {wLib.Interface.Shortcut} The new shortcut object.
  506. * @example //Creates new shortcut and adds it to the map.
  507. * shortcut = new wLib.Interface.Shortcut('myName', 'myGroup', 'C+p', callbackFunc, null).add();
  508. */
  509. initialize: function (name, group, shortcut, callback, scope) {
  510. var defaults = { group: 'default' };
  511. this.CLASS_NAME = 'wLib Shortcut';
  512. if ('string' === typeof name && name.length > 0 &&
  513. 'string' === typeof shortcut && shortcut.length > 0 &&
  514. 'function' === typeof callback) {
  515. this.name = name;
  516. this.group = group || defaults.group;
  517. this.callback = callback;
  518. this.shortcut[shortcut] = name;
  519. if ('object' !== typeof scope) {
  520. this.scope = null;
  521. } else {
  522. this.scope = scope;
  523. }
  524. return this;
  525. }
  526. },
  527. /**
  528. * Determines if the shortcut's group already exists.
  529. * @private
  530. */
  531. doesGroupExist: function () {
  532. this.groupExists = 'undefined' !== typeof W.accelerators.Groups[this.group] &&
  533. undefined !== typeof W.accelerators.Groups[this.group].members &&
  534. W.accelerators.Groups[this.group].length > 0;
  535. return this.groupExists;
  536. },
  537. /**
  538. * Determines if the shortcut's action already exists.
  539. * @private
  540. */
  541. doesActionExist: function () {
  542. this.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];
  543. return this.actionExists;
  544. },
  545. /**
  546. * Determines if the shortcut's event already exists.
  547. * @private
  548. */
  549. doesEventExist: function () {
  550. this.eventExists = 'undefined' !== typeof W.accelerators.events.listeners[this.name] &&
  551. W.accelerators.events.listeners[this.name].length > 0 &&
  552. this.callback === W.accelerators.events.listeners[this.name][0].func &&
  553. this.scope === W.accelerators.events.listeners[this.name][0].obj;
  554. return this.eventExists;
  555. },
  556. /**
  557. * Creates the shortcut's group.
  558. * @private
  559. */
  560. createGroup: function () {
  561. W.accelerators.Groups[this.group] = [];
  562. W.accelerators.Groups[this.group].members = [];
  563. },
  564. /**
  565. * Registers the shortcut's action.
  566. * @private
  567. */
  568. addAction: function () {
  569. W.accelerators.addAction(this.name, { group: this.group });
  570. },
  571. /**
  572. * Registers the shortcut's event.
  573. * @private
  574. */
  575. addEvent: function () {
  576. W.accelerators.events.register(this.name, this.scope, this.callback);
  577. },
  578. /**
  579. * Registers the shortcut's keyboard shortcut.
  580. * @private
  581. */
  582. registerShortcut: function () {
  583. W.accelerators.registerShortcuts(this.shortcut);
  584. },
  585. /**
  586. * Adds the keyboard shortcut to the map.
  587. * @return {wLib.Interface.Shortcut} The keyboard shortcut.
  588. */
  589. add: function () {
  590. /* If the group is not already defined, initialize the group. */
  591. if (!this.doesGroupExist()) {
  592. this.createGroup();
  593. }
  594.  
  595. /* Clear existing actions with same name */
  596. if (this.doesActionExist()) {
  597. W.accelerators.Actions[this.name] = null;
  598. }
  599. this.addAction();
  600.  
  601. /* Register event only if it's not already registered */
  602. if (!this.doesEventExist()) {
  603. this.addEvent();
  604. }
  605.  
  606. /* Finally, register the shortcut. */
  607. this.registerShortcut();
  608. return this;
  609. },
  610. /**
  611. * Removes the keyboard shortcut from the map.
  612. * @return {wLib.Interface.Shortcut} The keyboard shortcut.
  613. */
  614. remove: function () {
  615. if (this.doesEventExist()) {
  616. W.accelerators.events.unregister(this.name, this.scope, this.callback);
  617. }
  618. if (this.doesActionExist()) {
  619. delete W.accelerators.Actions[this.name];
  620. }
  621. //remove shortcut?
  622. return this;
  623. },
  624. /**
  625. * Changes the keyboard shortcut and applies changes to the map.
  626. * @return {wLib.Interface.Shortcut} The keyboard shortcut.
  627. */
  628. change: function (shortcut) {
  629. if (shortcut) {
  630. this.shortcut = {};
  631. this.shortcut[shortcut] = this.name;
  632. this.registerShortcut();
  633. }
  634. return this;
  635. }
  636. });
  637. }).call(wLib);
  638.  
  639. /*** Utilities ***/
  640. (function () {
  641. /**
  642. * Namespace for utility functions.
  643. * @memberof wLib
  644. * @namespace
  645. * @name wLib.Util
  646. */
  647. this.Util = {};
  648.  
  649. /**
  650. * Checks if the argument is a plain object.
  651. * @memberof wLib.Util
  652. * @param item {Any} The item to test.
  653. * @return {Boolean} True if item is plain object.
  654. */
  655. this.Util.isObject = function (item) {
  656. return item && 'object' === typeof item && !Array.isArray(item);
  657. }
  658. }).call(wLib);
  659.  
  660. /*** API ***/
  661. (function () {
  662.  
  663. /**
  664. * Namespace for functions related to WME actions.
  665. * @memberof wLib
  666. * @namespace
  667. * @name wLib.api
  668. */
  669. this.api = {};
  670. }).call(wLib);

QingJ © 2025

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