WME Utils - Google Link Enhancer

Adds some extra WME functionality related to Google place links.

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

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

  1. // ==UserScript==
  2. // @name WME Utils - Google Link Enhancer
  3. // @namespace WazeDev
  4. // @version 2025.04.10.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. this.#formatLinkElements();
  147. }
  148. }
  149.  
  150. enable() {
  151. if (!this.#enabled) {
  152. this.#interceptPlacesService();
  153. // Note: Using on() allows passing "this" as a variable, so it can be used in the handler function.
  154. $('#map').on('mouseenter', null, this, GLE.#onMapMouseenter);
  155. W.model.venues.on('objectschanged', this.#formatLinkElements, this);
  156. this.#processPlaces();
  157. this.#enabled = true;
  158. }
  159. }
  160.  
  161. disable() {
  162. if (this.#enabled) {
  163. $('#map').off('mouseenter', GLE.#onMapMouseenter);
  164. W.model.venues.off('objectschanged', this.#formatLinkElements, this);
  165. this.#enabled = false;
  166. }
  167. }
  168.  
  169. // The distance (in meters) before flagging a Waze place that is too far from the linked Google place.
  170. // Area places use distanceLimit, plus the distance from the centroid of the AP to its furthest node.
  171. get distanceLimit() {
  172. return this.#distanceLimit;
  173. }
  174.  
  175. set distanceLimit(value) {
  176. this.#distanceLimit = value;
  177. }
  178.  
  179. get showTempClosedPOIs() {
  180. return this.#showTempClosedPOIs;
  181. }
  182.  
  183. set showTempClosedPOIs(value) {
  184. this.#showTempClosedPOIs = value;
  185. }
  186.  
  187. // Borrowed from WazeWrap
  188. static #distanceBetweenPoints(point1, point2) {
  189. const line = new OpenLayers.Geometry.LineString([point1, point2]);
  190. const length = line.getGeodesicLength(W.map.getProjectionObject());
  191. return length; // multiply by 3.28084 to convert to feet
  192. }
  193.  
  194. #isLinkTooFar(link, venue) {
  195. if (link.loc) {
  196. const linkPt = new OpenLayers.Geometry.Point(link.loc.lng, link.loc.lat);
  197. linkPt.transform(W.Config.map.projection.remote, W.map.getProjectionObject());
  198. let venuePt;
  199. let distanceLim = this.distanceLimit;
  200. if (venue.isPoint()) {
  201. venuePt = venue.geometry.getCentroid();
  202. } else {
  203. const bounds = venue.geometry.getBounds();
  204. const center = bounds.getCenterLonLat();
  205. venuePt = new OpenLayers.Geometry.Point(center.lon, center.lat);
  206. const topRightPt = new OpenLayers.Geometry.Point(bounds.right, bounds.top);
  207. distanceLim += GLE.#distanceBetweenPoints(venuePt, topRightPt);
  208. }
  209. const distance = GLE.#distanceBetweenPoints(linkPt, venuePt);
  210. return distance > distanceLim;
  211. }
  212. return false;
  213. }
  214.  
  215. #processPlaces() {
  216. if (this.#enabled) {
  217. try {
  218. const that = this;
  219. // Get a list of already-linked id's
  220. const existingLinks = GoogleLinkEnhancer.#getExistingLinks();
  221. this.#mapLayer.removeAllFeatures();
  222. const drawnLinks = [];
  223. W.model.venues.getObjectArray().forEach(venue => {
  224. const promises = [];
  225. venue.attributes.externalProviderIDs.forEach(provID => {
  226. const id = provID.attributes.uuid;
  227.  
  228. // Check for duplicate links
  229. const linkInfo = existingLinks[id];
  230. if (linkInfo.count > 1) {
  231. const geometry = venue.isPoint() ? venue.geometry.getCentroid() : venue.geometry.clone();
  232. const width = venue.isPoint() ? '4' : '12';
  233. const color = '#fb8d00';
  234. const features = [new OpenLayers.Feature.Vector(geometry, {
  235. strokeWidth: width, strokeColor: color
  236. })];
  237. const lineStart = geometry.getCentroid();
  238. linkInfo.venues.forEach(linkVenue => {
  239. if (linkVenue !== venue
  240. && !drawnLinks.some(dl => (dl[0] === venue && dl[1] === linkVenue) || (dl[0] === linkVenue && dl[1] === venue))) {
  241. features.push(
  242. new OpenLayers.Feature.Vector(
  243. new OpenLayers.Geometry.LineString([lineStart, linkVenue.geometry.getCentroid()]),
  244. {
  245. strokeWidth: 4,
  246. strokeColor: color,
  247. strokeDashstyle: '12 12'
  248. }
  249. )
  250. );
  251. drawnLinks.push([venue, linkVenue]);
  252. }
  253. });
  254. that.#mapLayer.addFeatures(features);
  255. }
  256. });
  257.  
  258. // Process all results of link lookups and add a highlight feature if needed.
  259. Promise.all(promises).then(results => {
  260. let strokeColor = null;
  261. let strokeDashStyle = 'solid';
  262. if (!that.#DISABLE_CLOSED_PLACES && results.some(res => res.permclosed)) {
  263. if (/^(\[|\()?(permanently )?closed(\]|\)| -)/i.test(venue.attributes.name)
  264. || /(\(|- |\[)(permanently )?closed(\)|\])?$/i.test(venue.attributes.name)) {
  265. strokeDashStyle = venue.isPoint() ? '2 6' : '2 16';
  266. }
  267. strokeColor = '#F00';
  268. } else if (results.some(res => that.#isLinkTooFar(res, venue))) {
  269. strokeColor = '#0FF';
  270. } else if (!that.#DISABLE_CLOSED_PLACES && that.#showTempClosedPOIs && results.some(res => res.tempclosed)) {
  271. if (/^(\[|\()?(temporarily )?closed(\]|\)| -)/i.test(venue.attributes.name)
  272. || /(\(|- |\[)(temporarily )?closed(\)|\])?$/i.test(venue.attributes.name)) {
  273. strokeDashStyle = venue.isPoint() ? '2 6' : '2 16';
  274. }
  275. strokeColor = '#FD3';
  276. } else if (results.some(res => res.notFound)) {
  277. strokeColor = '#F0F';
  278. }
  279. if (strokeColor) {
  280. const style = {
  281. strokeWidth: venue.isPoint() ? '4' : '12',
  282. strokeColor,
  283. strokeDashStyle
  284. };
  285. const geometry = venue.isPoint() ? venue.geometry.getCentroid() : venue.geometry.clone();
  286. that.#mapLayer.addFeatures([new OpenLayers.Feature.Vector(geometry, style)]);
  287. }
  288. });
  289. });
  290. } catch (ex) {
  291. console.error('PIE (Google Link Enhancer) error:', ex);
  292. }
  293. }
  294. }
  295.  
  296. static #onMapMouseenter(event) {
  297. // If the point isn't destroyed yet, destroy it when mousing over the map.
  298. event.data.#destroyPoint();
  299. }
  300.  
  301. async #formatLinkElements() {
  302. const $links = $('#edit-panel').find(this.#EXT_PROV_ELEM_QUERY);
  303. if ($links.length) {
  304. const existingLinks = GLE.#getExistingLinks();
  305.  
  306. // fetch all links first
  307. const promises = [];
  308. const extProvElements = [];
  309. $links.each((ix, linkEl) => {
  310. const $linkEl = $(linkEl);
  311. extProvElements.push($linkEl);
  312.  
  313. const id = GLE.#getIdFromElement($linkEl);
  314. promises.push(this.linkCache.getPlace(id));
  315. });
  316. const links = await Promise.all(promises);
  317.  
  318. extProvElements.forEach(($extProvElem, i) => {
  319. const id = GLE.#getIdFromElement($extProvElem);
  320.  
  321. if (!id) return;
  322.  
  323. const link = links[i];
  324. if (existingLinks[id] && existingLinks[id].count > 1 && existingLinks[id].isThisVenue) {
  325. setTimeout(() => {
  326. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FFA500' }).attr({
  327. title: this.strings.linkedToXPlaces.replace('{0}', existingLinks[id].count)
  328. });
  329. }, 50);
  330. }
  331. this.#addHoverEvent($extProvElem);
  332. if (link) {
  333. if (link.permclosed && !this.#DISABLE_CLOSED_PLACES) {
  334. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FAA' }).attr('title', this.strings.permClosedPlace);
  335. } else if (link.tempclosed && !this.#DISABLE_CLOSED_PLACES) {
  336. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FFA' }).attr('title', this.strings.tempClosedPlace);
  337. } else if (link.notFound) {
  338. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#F0F' }).attr('title', this.strings.badLink);
  339. } else {
  340. const venue = W.selectionManager.getSelectedDataModelObjects()[0];
  341. if (this.#isLinkTooFar(link, venue)) {
  342. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#0FF' }).attr('title', this.strings.tooFar.replace('{0}', this.distanceLimit));
  343. } else { // reset in case we just deleted another provider
  344. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '' }).attr('title', '');
  345. }
  346. }
  347. }
  348. });
  349. }
  350. }
  351.  
  352. static #getExistingLinks() {
  353. const existingLinks = {};
  354. const thisVenue = W.selectionManager.getSelectedDataModelObjects()[0];
  355. W.model.venues.getObjectArray().forEach(venue => {
  356. const isThisVenue = venue === thisVenue;
  357. const thisPlaceIDs = [];
  358. venue.attributes.externalProviderIDs.forEach(provID => {
  359. const id = provID.attributes.uuid;
  360. if (!thisPlaceIDs.includes(id)) {
  361. thisPlaceIDs.push(id);
  362. let link = existingLinks[id];
  363. if (link) {
  364. link.count++;
  365. link.venues.push(venue);
  366. } else {
  367. link = { count: 1, venues: [venue] };
  368. existingLinks[id] = link;
  369. if (provID.attributes.url != null) {
  370. const u = provID.attributes.url.replace('https://maps.google.com/?', '');
  371. link.url = u;
  372. }
  373. }
  374. link.isThisVenue = link.isThisVenue || isThisVenue;
  375. }
  376. });
  377. });
  378. return existingLinks;
  379. }
  380.  
  381. // Remove the POI point from the map.
  382. #destroyPoint() {
  383. if (this.#ptFeature) {
  384. this.#ptFeature.destroy();
  385. this.#ptFeature = null;
  386. this.#lineFeature.destroy();
  387. this.#lineFeature = null;
  388. }
  389. }
  390.  
  391. static #getOLMapExtent() {
  392. let extent = W.map.getExtent();
  393. if (Array.isArray(extent)) {
  394. extent = new OpenLayers.Bounds(extent);
  395. extent.transform('EPSG:4326', 'EPSG:3857');
  396. }
  397. return extent;
  398. }
  399.  
  400. // Add the POI point to the map.
  401. async #addPoint(id) {
  402. if (!id) return;
  403. const link = await this.linkCache.getPlace(id);
  404. if (link) {
  405. if (!link.notFound) {
  406. const coord = link.loc;
  407. const poiPt = new OpenLayers.Geometry.Point(coord.lng, coord.lat);
  408. poiPt.transform(W.Config.map.projection.remote, W.map.getProjectionObject().projCode);
  409. const placeGeom = W.selectionManager.getSelectedDataModelObjects()[0].geometry.getCentroid();
  410. const placePt = new OpenLayers.Geometry.Point(placeGeom.x, placeGeom.y);
  411. const ext = GLE.#getOLMapExtent();
  412. const lsBounds = new OpenLayers.Geometry.LineString([
  413. new OpenLayers.Geometry.Point(ext.left, ext.bottom),
  414. new OpenLayers.Geometry.Point(ext.left, ext.top),
  415. new OpenLayers.Geometry.Point(ext.right, ext.top),
  416. new OpenLayers.Geometry.Point(ext.right, ext.bottom),
  417. new OpenLayers.Geometry.Point(ext.left, ext.bottom)]);
  418. let lsLine = new OpenLayers.Geometry.LineString([placePt, poiPt]);
  419.  
  420. // If the line extends outside the bounds, split it so we don't draw a line across the world.
  421. const splits = lsLine.splitWith(lsBounds);
  422. let label = '';
  423. if (splits) {
  424. let splitPoints;
  425. splits.forEach(split => {
  426. split.components.forEach(component => {
  427. if (component.x === placePt.x && component.y === placePt.y) splitPoints = split;
  428. });
  429. });
  430. lsLine = new OpenLayers.Geometry.LineString([splitPoints.components[0], splitPoints.components[1]]);
  431. let distance = GLE.#distanceBetweenPoints(poiPt, placePt);
  432. let unitConversion;
  433. let unit1;
  434. let unit2;
  435. if (W.model.isImperial) {
  436. distance *= 3.28084;
  437. unitConversion = 5280;
  438. unit1 = ' ft';
  439. unit2 = ' mi';
  440. } else {
  441. unitConversion = 1000;
  442. unit1 = ' m';
  443. unit2 = ' km';
  444. }
  445. if (distance > unitConversion * 10) {
  446. label = Math.round(distance / unitConversion) + unit2;
  447. } else if (distance > 1000) {
  448. label = (Math.round(distance / (unitConversion / 10)) / 10) + unit2;
  449. } else {
  450. label = Math.round(distance) + unit1;
  451. }
  452. }
  453.  
  454. this.#destroyPoint(); // Just in case it still exists.
  455. this.#ptFeature = new OpenLayers.Feature.Vector(poiPt, { poiCoord: true }, {
  456. pointRadius: 6,
  457. strokeWidth: 30,
  458. strokeColor: '#FF0',
  459. fillColor: '#FF0',
  460. strokeOpacity: 0.5
  461. });
  462. this.#lineFeature = new OpenLayers.Feature.Vector(lsLine, {}, {
  463. strokeWidth: 3,
  464. strokeDashstyle: '12 8',
  465. strokeColor: '#FF0',
  466. label,
  467. labelYOffset: 45,
  468. fontColor: '#FF0',
  469. fontWeight: 'bold',
  470. labelOutlineColor: '#000',
  471. labelOutlineWidth: 4,
  472. fontSize: '18'
  473. });
  474. W.map.getLayerByUniqueName('venues').addFeatures([this.#ptFeature, this.#lineFeature]);
  475. this.#timeoutDestroyPoint();
  476. }
  477. } else {
  478. // this.#getLinkInfoAsync(id).then(res => {
  479. // if (res.error || res.apiDisabled) {
  480. // // API was temporarily disabled. Ignore for now.
  481. // } else {
  482. // this.#addPoint(id);
  483. // }
  484. // });
  485. }
  486. }
  487.  
  488. // Destroy the point after some time, if it hasn't been destroyed already.
  489. #timeoutDestroyPoint() {
  490. if (this.#timeoutID) clearTimeout(this.#timeoutID);
  491. this.#timeoutID = setTimeout(() => this.#destroyPoint(), 4000);
  492. }
  493.  
  494. static #getIdFromElement($el) {
  495. const providerIndex = $el.parent().children().toArray().indexOf($el[0]);
  496. return W.selectionManager.getSelectedDataModelObjects()[0].getExternalProviderIDs()[providerIndex]?.attributes.uuid;
  497. }
  498.  
  499. #addHoverEvent($el) {
  500. $el.hover(() => this.#addPoint(GLE.#getIdFromElement($el)), () => this.#destroyPoint());
  501. }
  502.  
  503. #interceptPlacesService() {
  504. if (typeof google === 'undefined' || !google.maps || !google.maps.places || !google.maps.places.PlacesService) {
  505. console.debug('Google Maps PlacesService not loaded yet.');
  506. setTimeout(this.#interceptPlacesService.bind(this), 500); // Retry until it loads
  507. return;
  508. }
  509.  
  510. const originalGetDetails = google.maps.places.PlacesService.prototype.getDetails;
  511. const that = this;
  512. google.maps.places.PlacesService.prototype.getDetails = function interceptedGetDetails(request, callback) {
  513. console.log('Intercepted getDetails call:', request);
  514.  
  515. const customCallback = function(result, status) {
  516. console.log('Intercepted getDetails response:', result, status);
  517. const link = {};
  518. switch (status) {
  519. case google.maps.places.PlacesServiceStatus.OK: {
  520. const loc = result.geometry.location;
  521. link.loc = { lng: loc.lng(), lat: loc.lat() };
  522. if (result.business_status === google.maps.places.BusinessStatus.CLOSED_PERMANENTLY) {
  523. link.permclosed = true;
  524. } else if (result.business_status === google.maps.places.BusinessStatus.CLOSED_TEMPORARILY) {
  525. link.tempclosed = true;
  526. }
  527. that.linkCache.addPlace(request.placeId, link);
  528. break;
  529. }
  530. case google.maps.places.PlacesServiceStatus.NOT_FOUND:
  531. link.notfound = true;
  532. that.linkCache.addPlace(request.placeId, link);
  533. break;
  534. default:
  535. link.error = status;
  536. }
  537. callback(result, status); // Pass the result to the original callback
  538. };
  539.  
  540. return originalGetDetails.call(this, request, customCallback);
  541. };
  542.  
  543. console.log('Google Maps PlacesService.getDetails intercepted successfully.');
  544. }
  545. }
  546.  
  547. return GLE;
  548. }());