WME Utils - Google Link Enhancer

Adds some extra WME functionality related to Google place links.

当前为 2025-04-11 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/39208/1569376/WME%20Utils%20-%20Google%20Link%20Enhancer.js

  1. // ==UserScript==
  2. // @name WME Utils - Google Link Enhancer
  3. // @namespace WazeDev
  4. // @version 2025.04.11.000
  5. // @description Adds some extra WME functionality related to Google place links.
  6. // @author MapOMatic, WazeDev group
  7. // @include /^https:\/\/(www|beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/?.*$/
  8. // @license GNU GPLv3
  9. // ==/UserScript==
  10.  
  11. /* global OpenLayers */
  12. /* global W */
  13. /* global google */
  14.  
  15. /* eslint-disable max-classes-per-file */
  16.  
  17. // eslint-disable-next-line func-names
  18. const GoogleLinkEnhancer = (function() {
  19. 'use strict';
  20.  
  21. class GooglePlaceCache {
  22. constructor() {
  23. this.cache = new Map();
  24. this.pendingPromises = new Map();
  25. }
  26.  
  27. async getPlace(placeId) {
  28. if (this.cache.has(placeId)) {
  29. return this.cache.get(placeId);
  30. }
  31.  
  32. if (!this.pendingPromises.has(placeId)) {
  33. let resolveFn;
  34. let rejectFn;
  35. const promise = new Promise((resolve, reject) => {
  36. resolveFn = resolve;
  37. rejectFn = reject;
  38.  
  39. // Set a timeout to reject the promise if not resolved in 3 seconds
  40. setTimeout(() => {
  41. if (this.pendingPromises.has(placeId)) {
  42. this.pendingPromises.delete(placeId);
  43. rejectFn(new Error(`Timeout: Place ${placeId} not found within 3 seconds`));
  44. }
  45. }, 3000);
  46. });
  47.  
  48. this.pendingPromises.set(placeId, { promise, resolve: resolveFn, reject: rejectFn });
  49. }
  50.  
  51. return this.pendingPromises.get(placeId).promise;
  52. }
  53.  
  54. addPlace(placeId, properties) {
  55. this.cache.set(placeId, properties);
  56.  
  57. if (this.pendingPromises.has(placeId)) {
  58. this.pendingPromises.get(placeId).resolve(properties);
  59. this.pendingPromises.delete(placeId);
  60. }
  61. }
  62. }
  63. class GLE {
  64. #DISABLE_CLOSED_PLACES = false; // Set to TRUE if the feature needs to be temporarily disabled, e.g. during the COVID-19 pandemic.
  65. #EXT_PROV_ELEM_QUERY = 'wz-list-item.external-provider';
  66. #EXT_PROV_ELEM_EDIT_QUERY = 'wz-list-item.external-provider-edit';
  67. #EXT_PROV_ELEM_CONTENT_QUERY = 'div.external-provider-content';
  68.  
  69. linkCache;
  70. #enabled = false;
  71. #mapLayer = null;
  72. #distanceLimit = 400; // Default distance (meters) when Waze place is flagged for being too far from Google place.
  73. // Area place is calculated as #distanceLimit + <distance between centroid and furthest node>
  74. #showTempClosedPOIs = true;
  75. #originalHeadAppendChildMethod;
  76. #ptFeature;
  77. #lineFeature;
  78. #timeoutID;
  79. strings = {
  80. permClosedPlace: 'Google indicates this place is permanently closed.\nVerify with other sources or your editor community before deleting.',
  81. tempClosedPlace: 'Google indicates this place is temporarily closed.',
  82. multiLinked: 'Linked more than once already. Please find and remove multiple links.',
  83. linkedToThisPlace: 'Already linked to this place',
  84. linkedNearby: 'Already linked to a nearby place',
  85. linkedToXPlaces: 'This is linked to {0} places',
  86. badLink: 'Invalid Google link. Please remove it.',
  87. tooFar: 'The Google linked place is more than {0} meters from the Waze place. Please verify the link is correct.'
  88. };
  89.  
  90. /* eslint-enable no-unused-vars */
  91. constructor() {
  92. this.linkCache = new GooglePlaceCache();
  93. this.#initLayer();
  94.  
  95. // NOTE: Arrow functions are necessary for calling methods on object instances.
  96. // This could be made more efficient by only processing the relevant places.
  97. W.model.events.register('mergeend', null, () => { this.#processPlaces(); });
  98. W.model.venues.on('objectschanged', () => { this.#processPlaces(); });
  99. W.model.venues.on('objectsremoved', () => { this.#processPlaces(); });
  100. W.model.venues.on('objectsadded', () => { this.#processPlaces(); });
  101.  
  102. // This is a special event that will be triggered when DOM elements are destroyed.
  103. /* eslint-disable wrap-iife, func-names, object-shorthand */
  104. (function($) {
  105. $.event.special.destroyed = {
  106. remove: function(o) {
  107. if (o.handler && o.type !== 'destroyed') {
  108. o.handler();
  109. }
  110. }
  111. };
  112. })(jQuery);
  113. /* eslint-enable wrap-iife, func-names, object-shorthand */
  114.  
  115. // In case a place is already selected on load.
  116. const selObjects = W.selectionManager.getSelectedDataModelObjects();
  117. if (selObjects.length && selObjects[0].type === 'venue') {
  118. this.#formatLinkElements();
  119. }
  120.  
  121. W.selectionManager.events.register('selectionchanged', null, this.#onWmeSelectionChanged.bind(this));
  122. }
  123.  
  124. #initLayer() {
  125. this.#mapLayer = new OpenLayers.Layer.Vector('Google Link Enhancements.', {
  126. uniqueName: '___GoogleLinkEnhancements',
  127. displayInLayerSwitcher: true,
  128. styleMap: new OpenLayers.StyleMap({
  129. default: {
  130. strokeColor: '${strokeColor}',
  131. strokeWidth: '${strokeWidth}',
  132. strokeDashstyle: '${strokeDashstyle}',
  133. pointRadius: '15',
  134. fillOpacity: '0'
  135. }
  136. })
  137. });
  138.  
  139. this.#mapLayer.setOpacity(0.8);
  140. W.map.addLayer(this.#mapLayer);
  141. }
  142.  
  143. #onWmeSelectionChanged() {
  144. if (this.#enabled) {
  145. this.#destroyPoint();
  146. const selected = W.selectionManager.getSelectedDataModelObjects();
  147. if (selected[0]?.type === 'venue') {
  148. this.#formatLinkElements();
  149. }
  150. }
  151. }
  152.  
  153. enable() {
  154. if (!this.#enabled) {
  155. this.#interceptPlacesService();
  156. // Note: Using on() allows passing "this" as a variable, so it can be used in the handler function.
  157. $('#map').on('mouseenter', null, this, GLE.#onMapMouseenter);
  158. W.model.venues.on('objectschanged', this.#formatLinkElements, this);
  159. this.#processPlaces();
  160. this.#enabled = true;
  161. }
  162. }
  163.  
  164. disable() {
  165. if (this.#enabled) {
  166. $('#map').off('mouseenter', GLE.#onMapMouseenter);
  167. W.model.venues.off('objectschanged', this.#formatLinkElements, this);
  168. this.#enabled = false;
  169. }
  170. }
  171.  
  172. // The distance (in meters) before flagging a Waze place that is too far from the linked Google place.
  173. // Area places use distanceLimit, plus the distance from the centroid of the AP to its furthest node.
  174. get distanceLimit() {
  175. return this.#distanceLimit;
  176. }
  177.  
  178. set distanceLimit(value) {
  179. this.#distanceLimit = value;
  180. }
  181.  
  182. get showTempClosedPOIs() {
  183. return this.#showTempClosedPOIs;
  184. }
  185.  
  186. set showTempClosedPOIs(value) {
  187. this.#showTempClosedPOIs = value;
  188. }
  189.  
  190. // Borrowed from WazeWrap
  191. static #distanceBetweenPoints(point1, point2) {
  192. const line = new OpenLayers.Geometry.LineString([point1, point2]);
  193. const length = line.getGeodesicLength(W.map.getProjectionObject());
  194. return length; // multiply by 3.28084 to convert to feet
  195. }
  196.  
  197. #isLinkTooFar(link, venue) {
  198. if (link.loc) {
  199. const linkPt = new OpenLayers.Geometry.Point(link.loc.lng, link.loc.lat);
  200. linkPt.transform(W.Config.map.projection.remote, W.map.getProjectionObject());
  201. let venuePt;
  202. let distanceLim = this.distanceLimit;
  203. if (venue.isPoint()) {
  204. venuePt = venue.geometry.getCentroid();
  205. } else {
  206. const bounds = venue.geometry.getBounds();
  207. const center = bounds.getCenterLonLat();
  208. venuePt = new OpenLayers.Geometry.Point(center.lon, center.lat);
  209. const topRightPt = new OpenLayers.Geometry.Point(bounds.right, bounds.top);
  210. distanceLim += GLE.#distanceBetweenPoints(venuePt, topRightPt);
  211. }
  212. const distance = GLE.#distanceBetweenPoints(linkPt, venuePt);
  213. return distance > distanceLim;
  214. }
  215. return false;
  216. }
  217.  
  218. #processPlaces() {
  219. if (this.#enabled) {
  220. try {
  221. const that = this;
  222. // Get a list of already-linked id's
  223. const existingLinks = GoogleLinkEnhancer.#getExistingLinks();
  224. this.#mapLayer.removeAllFeatures();
  225. const drawnLinks = [];
  226. W.model.venues.getObjectArray().forEach(venue => {
  227. const promises = [];
  228. venue.attributes.externalProviderIDs.forEach(provID => {
  229. const id = provID.attributes.uuid;
  230.  
  231. // Check for duplicate links
  232. const linkInfo = existingLinks[id];
  233. if (linkInfo.count > 1) {
  234. const geometry = venue.isPoint() ? venue.geometry.getCentroid() : venue.geometry.clone();
  235. const width = venue.isPoint() ? '4' : '12';
  236. const color = '#fb8d00';
  237. const features = [new OpenLayers.Feature.Vector(geometry, {
  238. strokeWidth: width, strokeColor: color
  239. })];
  240. const lineStart = geometry.getCentroid();
  241. linkInfo.venues.forEach(linkVenue => {
  242. if (linkVenue !== venue
  243. && !drawnLinks.some(dl => (dl[0] === venue && dl[1] === linkVenue) || (dl[0] === linkVenue && dl[1] === venue))) {
  244. features.push(
  245. new OpenLayers.Feature.Vector(
  246. new OpenLayers.Geometry.LineString([lineStart, linkVenue.geometry.getCentroid()]),
  247. {
  248. strokeWidth: 4,
  249. strokeColor: color,
  250. strokeDashstyle: '12 12'
  251. }
  252. )
  253. );
  254. drawnLinks.push([venue, linkVenue]);
  255. }
  256. });
  257. that.#mapLayer.addFeatures(features);
  258. }
  259. });
  260.  
  261. // Process all results of link lookups and add a highlight feature if needed.
  262. Promise.all(promises).then(results => {
  263. let strokeColor = null;
  264. let strokeDashStyle = 'solid';
  265. if (!that.#DISABLE_CLOSED_PLACES && results.some(res => res.permclosed)) {
  266. if (/^(\[|\()?(permanently )?closed(\]|\)| -)/i.test(venue.attributes.name)
  267. || /(\(|- |\[)(permanently )?closed(\)|\])?$/i.test(venue.attributes.name)) {
  268. strokeDashStyle = venue.isPoint() ? '2 6' : '2 16';
  269. }
  270. strokeColor = '#F00';
  271. } else if (results.some(res => that.#isLinkTooFar(res, venue))) {
  272. strokeColor = '#0FF';
  273. } else if (!that.#DISABLE_CLOSED_PLACES && that.#showTempClosedPOIs && results.some(res => res.tempclosed)) {
  274. if (/^(\[|\()?(temporarily )?closed(\]|\)| -)/i.test(venue.attributes.name)
  275. || /(\(|- |\[)(temporarily )?closed(\)|\])?$/i.test(venue.attributes.name)) {
  276. strokeDashStyle = venue.isPoint() ? '2 6' : '2 16';
  277. }
  278. strokeColor = '#FD3';
  279. } else if (results.some(res => res.notFound)) {
  280. strokeColor = '#F0F';
  281. }
  282. if (strokeColor) {
  283. const style = {
  284. strokeWidth: venue.isPoint() ? '4' : '12',
  285. strokeColor,
  286. strokeDashStyle
  287. };
  288. const geometry = venue.isPoint() ? venue.geometry.getCentroid() : venue.geometry.clone();
  289. that.#mapLayer.addFeatures([new OpenLayers.Feature.Vector(geometry, style)]);
  290. }
  291. });
  292. });
  293. } catch (ex) {
  294. console.error('PIE (Google Link Enhancer) error:', ex);
  295. }
  296. }
  297. }
  298.  
  299. static #onMapMouseenter(event) {
  300. // If the point isn't destroyed yet, destroy it when mousing over the map.
  301. event.data.#destroyPoint();
  302. }
  303.  
  304. async #formatLinkElements() {
  305. const $links = $('#edit-panel').find(this.#EXT_PROV_ELEM_QUERY);
  306. if ($links.length) {
  307. const existingLinks = GLE.#getExistingLinks();
  308.  
  309. // fetch all links first
  310. const promises = [];
  311. const extProvElements = [];
  312. $links.each((ix, linkEl) => {
  313. const $linkEl = $(linkEl);
  314. extProvElements.push($linkEl);
  315.  
  316. const id = GLE.#getIdFromElement($linkEl);
  317. promises.push(this.linkCache.getPlace(id));
  318. });
  319. const links = await Promise.all(promises);
  320.  
  321. extProvElements.forEach(($extProvElem, i) => {
  322. const id = GLE.#getIdFromElement($extProvElem);
  323.  
  324. if (!id) return;
  325.  
  326. const link = links[i];
  327. if (existingLinks[id] && existingLinks[id].count > 1 && existingLinks[id].isThisVenue) {
  328. setTimeout(() => {
  329. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FFA500' }).attr({
  330. title: this.strings.linkedToXPlaces.replace('{0}', existingLinks[id].count)
  331. });
  332. }, 50);
  333. }
  334. this.#addHoverEvent($extProvElem);
  335. if (link) {
  336. if (link.permclosed && !this.#DISABLE_CLOSED_PLACES) {
  337. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FAA' }).attr('title', this.strings.permClosedPlace);
  338. } else if (link.tempclosed && !this.#DISABLE_CLOSED_PLACES) {
  339. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FFA' }).attr('title', this.strings.tempClosedPlace);
  340. } else if (link.notFound) {
  341. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#F0F' }).attr('title', this.strings.badLink);
  342. } else {
  343. const venue = W.selectionManager.getSelectedDataModelObjects()[0];
  344. if (this.#isLinkTooFar(link, venue)) {
  345. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#0FF' }).attr('title', this.strings.tooFar.replace('{0}', this.distanceLimit));
  346. } else { // reset in case we just deleted another provider
  347. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '' }).attr('title', '');
  348. }
  349. }
  350. }
  351. });
  352. }
  353. }
  354.  
  355. static #getExistingLinks() {
  356. const existingLinks = {};
  357. const thisVenue = W.selectionManager.getSelectedDataModelObjects()[0];
  358. W.model.venues.getObjectArray().forEach(venue => {
  359. const isThisVenue = venue === thisVenue;
  360. const thisPlaceIDs = [];
  361. venue.attributes.externalProviderIDs.forEach(provID => {
  362. const id = provID.attributes.uuid;
  363. if (!thisPlaceIDs.includes(id)) {
  364. thisPlaceIDs.push(id);
  365. let link = existingLinks[id];
  366. if (link) {
  367. link.count++;
  368. link.venues.push(venue);
  369. } else {
  370. link = { count: 1, venues: [venue] };
  371. existingLinks[id] = link;
  372. if (provID.attributes.url != null) {
  373. const u = provID.attributes.url.replace('https://maps.google.com/?', '');
  374. link.url = u;
  375. }
  376. }
  377. link.isThisVenue = link.isThisVenue || isThisVenue;
  378. }
  379. });
  380. });
  381. return existingLinks;
  382. }
  383.  
  384. // Remove the POI point from the map.
  385. #destroyPoint() {
  386. if (this.#ptFeature) {
  387. this.#ptFeature.destroy();
  388. this.#ptFeature = null;
  389. this.#lineFeature.destroy();
  390. this.#lineFeature = null;
  391. }
  392. }
  393.  
  394. static #getOLMapExtent() {
  395. let extent = W.map.getExtent();
  396. if (Array.isArray(extent)) {
  397. extent = new OpenLayers.Bounds(extent);
  398. extent.transform('EPSG:4326', 'EPSG:3857');
  399. }
  400. return extent;
  401. }
  402.  
  403. // Add the POI point to the map.
  404. async #addPoint(id) {
  405. if (!id) return;
  406. const link = await this.linkCache.getPlace(id);
  407. if (link) {
  408. if (!link.notFound) {
  409. const coord = link.loc;
  410. const poiPt = new OpenLayers.Geometry.Point(coord.lng, coord.lat);
  411. poiPt.transform(W.Config.map.projection.remote, W.map.getProjectionObject().projCode);
  412. const placeGeom = W.selectionManager.getSelectedDataModelObjects()[0].geometry.getCentroid();
  413. const placePt = new OpenLayers.Geometry.Point(placeGeom.x, placeGeom.y);
  414. const ext = GLE.#getOLMapExtent();
  415. const lsBounds = new OpenLayers.Geometry.LineString([
  416. new OpenLayers.Geometry.Point(ext.left, ext.bottom),
  417. new OpenLayers.Geometry.Point(ext.left, ext.top),
  418. new OpenLayers.Geometry.Point(ext.right, ext.top),
  419. new OpenLayers.Geometry.Point(ext.right, ext.bottom),
  420. new OpenLayers.Geometry.Point(ext.left, ext.bottom)]);
  421. let lsLine = new OpenLayers.Geometry.LineString([placePt, poiPt]);
  422.  
  423. // If the line extends outside the bounds, split it so we don't draw a line across the world.
  424. const splits = lsLine.splitWith(lsBounds);
  425. let label = '';
  426. if (splits) {
  427. let splitPoints;
  428. splits.forEach(split => {
  429. split.components.forEach(component => {
  430. if (component.x === placePt.x && component.y === placePt.y) splitPoints = split;
  431. });
  432. });
  433. lsLine = new OpenLayers.Geometry.LineString([splitPoints.components[0], splitPoints.components[1]]);
  434. let distance = GLE.#distanceBetweenPoints(poiPt, placePt);
  435. let unitConversion;
  436. let unit1;
  437. let unit2;
  438. if (W.model.isImperial) {
  439. distance *= 3.28084;
  440. unitConversion = 5280;
  441. unit1 = ' ft';
  442. unit2 = ' mi';
  443. } else {
  444. unitConversion = 1000;
  445. unit1 = ' m';
  446. unit2 = ' km';
  447. }
  448. if (distance > unitConversion * 10) {
  449. label = Math.round(distance / unitConversion) + unit2;
  450. } else if (distance > 1000) {
  451. label = (Math.round(distance / (unitConversion / 10)) / 10) + unit2;
  452. } else {
  453. label = Math.round(distance) + unit1;
  454. }
  455. }
  456.  
  457. this.#destroyPoint(); // Just in case it still exists.
  458. this.#ptFeature = new OpenLayers.Feature.Vector(poiPt, { poiCoord: true }, {
  459. pointRadius: 6,
  460. strokeWidth: 30,
  461. strokeColor: '#FF0',
  462. fillColor: '#FF0',
  463. strokeOpacity: 0.5
  464. });
  465. this.#lineFeature = new OpenLayers.Feature.Vector(lsLine, {}, {
  466. strokeWidth: 3,
  467. strokeDashstyle: '12 8',
  468. strokeColor: '#FF0',
  469. label,
  470. labelYOffset: 45,
  471. fontColor: '#FF0',
  472. fontWeight: 'bold',
  473. labelOutlineColor: '#000',
  474. labelOutlineWidth: 4,
  475. fontSize: '18'
  476. });
  477. W.map.getLayerByUniqueName('venues').addFeatures([this.#ptFeature, this.#lineFeature]);
  478. this.#timeoutDestroyPoint();
  479. }
  480. } else {
  481. // this.#getLinkInfoAsync(id).then(res => {
  482. // if (res.error || res.apiDisabled) {
  483. // // API was temporarily disabled. Ignore for now.
  484. // } else {
  485. // this.#addPoint(id);
  486. // }
  487. // });
  488. }
  489. }
  490.  
  491. // Destroy the point after some time, if it hasn't been destroyed already.
  492. #timeoutDestroyPoint() {
  493. if (this.#timeoutID) clearTimeout(this.#timeoutID);
  494. this.#timeoutID = setTimeout(() => this.#destroyPoint(), 4000);
  495. }
  496.  
  497. static #getIdFromElement($el) {
  498. const providerIndex = $el.parent().children().toArray().indexOf($el[0]);
  499. return W.selectionManager.getSelectedDataModelObjects()[0].getExternalProviderIDs()[providerIndex]?.attributes.uuid;
  500. }
  501.  
  502. #addHoverEvent($el) {
  503. $el.hover(() => this.#addPoint(GLE.#getIdFromElement($el)), () => this.#destroyPoint());
  504. }
  505.  
  506. #interceptPlacesService() {
  507. if (typeof google === 'undefined' || !google.maps || !google.maps.places || !google.maps.places.PlacesService) {
  508. console.debug('Google Maps PlacesService not loaded yet.');
  509. setTimeout(this.#interceptPlacesService.bind(this), 500); // Retry until it loads
  510. return;
  511. }
  512.  
  513. const originalGetDetails = google.maps.places.PlacesService.prototype.getDetails;
  514. const that = this;
  515. google.maps.places.PlacesService.prototype.getDetails = function interceptedGetDetails(request, callback) {
  516. console.log('Intercepted getDetails call:', request);
  517.  
  518. const customCallback = function(result, status) {
  519. console.log('Intercepted getDetails response:', result, status);
  520. const link = {};
  521. switch (status) {
  522. case google.maps.places.PlacesServiceStatus.OK: {
  523. const loc = result.geometry.location;
  524. link.loc = { lng: loc.lng(), lat: loc.lat() };
  525. if (result.business_status === google.maps.places.BusinessStatus.CLOSED_PERMANENTLY) {
  526. link.permclosed = true;
  527. } else if (result.business_status === google.maps.places.BusinessStatus.CLOSED_TEMPORARILY) {
  528. link.tempclosed = true;
  529. }
  530. that.linkCache.addPlace(request.placeId, link);
  531. break;
  532. }
  533. case google.maps.places.PlacesServiceStatus.NOT_FOUND:
  534. link.notfound = true;
  535. that.linkCache.addPlace(request.placeId, link);
  536. break;
  537. default:
  538. link.error = status;
  539. }
  540. callback(result, status); // Pass the result to the original callback
  541. };
  542.  
  543. return originalGetDetails.call(this, request, customCallback);
  544. };
  545.  
  546. console.log('Google Maps PlacesService.getDetails intercepted successfully.');
  547. }
  548. }
  549.  
  550. return GLE;
  551. }());