WME Utils - Google Link Enhancer

Adds some extra WME functionality related to Google place links.

当前为 2023-05-22 提交的版本,查看 最新版本

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

  1. // ==UserScript==
  2. // @name WME Utils - Google Link Enhancer
  3. // @namespace WazeDev
  4. // @version 2023.05.22.001
  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 */
  16. /* eslint-disable no-unused-vars */
  17. class GoogleLinkEnhancer {
  18. #DISABLE_CLOSED_PLACES = false; // Set to TRUE if the feature needs to be temporarily disabled, e.g. during the COVID-19 pandemic.
  19. #EXT_PROV_ELEM_QUERY = 'wz-list-item.external-provider';
  20. #EXT_PROV_ELEM_EDIT_QUERY = 'wz-list-item.external-provider-edit';
  21. #EXT_PROV_ELEM_CONTENT_QUERY = 'div.external-provider-content';
  22. #LINK_CACHE_NAME = 'gle_link_cache';
  23. #LINK_CACHE_CLEAN_INTERVAL_MIN = 1; // Interval to remove old links and save new ones.
  24. #LINK_CACHE_LIFESPAN_HR = 6; // Remove old links when they exceed this time limit.
  25.  
  26. #linkCache;
  27. #enabled = false;
  28. #disableApiUntil = null; // When a serious API error occurs (OVER_QUERY_LIMIT, REQUEST_DENIED), set this to a time in the future.
  29. #mapLayer = null;
  30. #distanceLimit = 400; // Default distance (meters) when Waze place is flagged for being too far from Google place.
  31. // Area place is calculated as #distanceLimit + <distance between centroid and furthest node>
  32. #showTempClosedPOIs = true;
  33. #placesService;
  34. #linkObserver;
  35. #modeObserver;
  36. #searchResultsObserver;
  37. #lzString;
  38. #cacheCleanIntervalID;
  39. #originalHeadAppendChildMethod;
  40. #ptFeature;
  41. #lineFeature;
  42. #timeoutID;
  43. strings = {
  44. permClosedPlace: 'Google indicates this place is permanently closed.\nVerify with other sources or your editor community before deleting.',
  45. tempClosedPlace: 'Google indicates this place is temporarily closed.',
  46. multiLinked: 'Linked more than once already. Please find and remove multiple links.',
  47. linkedToThisPlace: 'Already linked to this place',
  48. linkedNearby: 'Already linked to a nearby place',
  49. linkedToXPlaces: 'This is linked to {0} places',
  50. badLink: 'Invalid Google link. Please remove it.',
  51. tooFar: 'The Google linked place is more than {0} meters from the Waze place. Please verify the link is correct.'
  52. };
  53.  
  54. /* eslint-enable no-unused-vars */
  55. constructor() {
  56. const attributionElem = document.createElement('div');
  57. this.#placesService = new google.maps.places.PlacesService(attributionElem);
  58. this.#initLZString();
  59. const STORED_CACHE = localStorage.getItem(this.#LINK_CACHE_NAME);
  60. try {
  61. this.#linkCache = STORED_CACHE ? $.parseJSON(this.#lzString.decompressFromUTF16(STORED_CACHE)) : {};
  62. } catch (ex) {
  63. if (ex.name === 'SyntaxError') {
  64. // In case the cache is corrupted and can't be read.
  65. this.#linkCache = {};
  66. console.warn('GoogleLinkEnhancer:', 'An error occurred while loading the stored cache. A new cache was created.');
  67. } else {
  68. throw ex;
  69. }
  70. }
  71. if (this.#linkCache === null || this.#linkCache.length === 0) this.#linkCache = {};
  72.  
  73. this.#initLayer();
  74.  
  75. // NOTE: Arrow functions are necessary for calling methods on object instances.
  76. // This could be made more efficient by only processing the relevant places.
  77. W.model.events.register('mergeend', null, () => { this.#processPlaces(); });
  78. W.model.venues.on('objectschanged', () => { this.#processPlaces(); });
  79. W.model.venues.on('objectsremoved', () => { this.#processPlaces(); });
  80. W.model.venues.on('objectsadded', () => { this.#processPlaces(); });
  81.  
  82. // Watch for ext provider elements being added to the DOM, and add hover events.
  83. this.#linkObserver = new MutationObserver(mutations => {
  84. mutations.forEach(mutation => {
  85. for (let idx = 0; idx < mutation.addedNodes.length; idx++) {
  86. const nd = mutation.addedNodes[idx];
  87. if (nd.nodeType === Node.ELEMENT_NODE) {
  88. const $el = $(nd);
  89. const $subel = $el.find(this.#EXT_PROV_ELEM_QUERY);
  90. if ($el.is(this.#EXT_PROV_ELEM_QUERY)) {
  91. this.#addHoverEvent($el);
  92. this.#formatLinkElements();
  93. } else if ($subel.length) {
  94. for (let i = 0; i < $subel.length; i++) {
  95. this.#addHoverEvent($($subel[i]));
  96. }
  97. this.#formatLinkElements();
  98. }
  99. if ($el.is(this.#EXT_PROV_ELEM_EDIT_QUERY)) {
  100. this.#searchResultsObserver.observe($el.find('wz-autocomplete[placeholder="Search for a place"]')[0].shadowRoot, { childList: true, subtree: true });
  101. }
  102. }
  103. }
  104. for (let idx = 0; idx < mutation.removedNodes.length; idx++) {
  105. const nd = mutation.removedNodes[idx];
  106. if (nd.nodeType === Node.ELEMENT_NODE) {
  107. const $el = $(nd);
  108. if ($el.is(this.#EXT_PROV_ELEM_EDIT_QUERY)) {
  109. this.#searchResultsObserver.disconnect();
  110. }
  111. }
  112. }
  113. });
  114. });
  115.  
  116. // Watch for Google place search result list items being added to the DOM
  117. const that = this;
  118. this.#searchResultsObserver = new MutationObserver(mutations => {
  119. mutations.forEach(mutation => {
  120. for (let idx = 0; idx < mutation.addedNodes.length; idx++) {
  121. const nd = mutation.addedNodes[idx];
  122. if (nd.nodeType === Node.ELEMENT_NODE && $(nd).is('wz-menu-item.simple-item')) {
  123. $(nd).mouseenter(() => {
  124. // When mousing over a list item, find the Google place ID from the list that was stored previously.
  125. // Then add the point/line to the map.
  126. that.#addPoint($(nd).attr('item-id'));
  127. }).mouseleave(() => {
  128. // When leaving the list item, remove the point.
  129. that.#destroyPoint();
  130. });
  131. }
  132. }
  133. });
  134. });
  135.  
  136. // Watch the side panel for addition of the sidebar-layout div, which indicates a mode change.
  137. this.#modeObserver = new MutationObserver(mutations => {
  138. mutations.forEach(mutation => {
  139. for (let idx = 0; idx < mutation.addedNodes.length; idx++) {
  140. const nd = mutation.addedNodes[idx];
  141. if (nd.nodeType === Node.ELEMENT_NODE && $(nd).is('.sidebar-layout')) {
  142. this.#observeLinks();
  143. break;
  144. }
  145. }
  146. });
  147. });
  148.  
  149. // This is a special event that will be triggered when DOM elements are destroyed.
  150. /* eslint-disable wrap-iife, func-names, object-shorthand */
  151. (function($) {
  152. $.event.special.destroyed = {
  153. remove: function(o) {
  154. if (o.handler && o.type !== 'destroyed') {
  155. o.handler();
  156. }
  157. }
  158. };
  159. })(jQuery);
  160. /* eslint-enable wrap-iife, func-names, object-shorthand */
  161.  
  162. // In case a place is already selected on load.
  163. const selFeatures = W.selectionManager.getSelectedFeatures();
  164. if (selFeatures.length && selFeatures[0].attributes.repositoryObject.type === 'venue') {
  165. this.#formatLinkElements();
  166. }
  167. }
  168.  
  169. #initLayer() {
  170. this.#mapLayer = new OpenLayers.Layer.Vector('Google Link Enhancements.', {
  171. uniqueName: '___GoogleLinkEnhancements',
  172. displayInLayerSwitcher: true,
  173. styleMap: new OpenLayers.StyleMap({
  174. default: {
  175. strokeColor: '${strokeColor}',
  176. strokeWidth: '${strokeWidth}',
  177. strokeDashstyle: '${strokeDashstyle}',
  178. pointRadius: '15',
  179. fillOpacity: '0'
  180. }
  181. })
  182. });
  183.  
  184. this.#mapLayer.setOpacity(0.8);
  185. W.map.addLayer(this.#mapLayer);
  186. }
  187.  
  188. enable() {
  189. if (!this.#enabled) {
  190. this.#modeObserver.observe($('.edit-area #sidebarContent')[0], { childList: true, subtree: false });
  191. this.#observeLinks();
  192. // Watch for JSONP callbacks. JSONP is used for the autocomplete results when searching for Google links.
  193. this.#addJsonpInterceptor();
  194. // Note: Using on() allows passing "this" as a variable, so it can be used in the handler function.
  195. $('#map').on('mouseenter', null, this, GoogleLinkEnhancer.#onMapMouseenter);
  196. $(window).on('unload', null, this, GoogleLinkEnhancer.#onWindowUnload);
  197. W.model.venues.on('objectschanged', this.#formatLinkElements, this);
  198. this.#processPlaces();
  199. this.#cleanAndSaveLinkCache();
  200. this.#cacheCleanIntervalID = setInterval(() => this.#cleanAndSaveLinkCache(), 1000 * 60 * this.#LINK_CACHE_CLEAN_INTERVAL_MIN);
  201. this.#enabled = true;
  202. }
  203. }
  204.  
  205. disable() {
  206. if (this.#enabled) {
  207. this.#modeObserver.disconnect();
  208. this.#linkObserver.disconnect();
  209. this.#searchResultsObserver.disconnect();
  210. this.#removeJsonpInterceptor();
  211. $('#map').off('mouseenter', GoogleLinkEnhancer.#onMapMouseenter);
  212. $(window).off('unload', null, this, GoogleLinkEnhancer.#onWindowUnload);
  213. W.model.venues.off('objectschanged', this.#formatLinkElements, this);
  214. if (this.#cacheCleanIntervalID) clearInterval(this.#cacheCleanIntervalID);
  215. this.#cleanAndSaveLinkCache();
  216. this.#enabled = false;
  217. }
  218. }
  219.  
  220. // The distance (in meters) before flagging a Waze place that is too far from the linked Google place.
  221. // Area places use distanceLimit, plus the distance from the centroid of the AP to its furthest node.
  222. get distanceLimit() {
  223. return this.#distanceLimit;
  224. }
  225.  
  226. set distanceLimit(value) {
  227. this.#distanceLimit = value;
  228. this.#processPlaces();
  229. }
  230.  
  231. get showTempClosedPOIs() {
  232. return this.#showTempClosedPOIs;
  233. }
  234.  
  235. set showTempClosedPOIs(value) {
  236. this.#showTempClosedPOIs = value;
  237. this.#processPlaces();
  238. }
  239.  
  240. static #onWindowUnload(evt) {
  241. evt.data.#cleanAndSaveLinkCache();
  242. }
  243.  
  244. #cleanAndSaveLinkCache() {
  245. if (!this.#linkCache) return;
  246. const now = new Date();
  247. Object.keys(this.#linkCache).forEach(id => {
  248. const link = this.#linkCache[id];
  249. // Bug fix:
  250. if (link.location) {
  251. link.loc = link.location;
  252. delete link.location;
  253. }
  254. // Delete link if older than X hours.
  255. if (!link.ts || (now - new Date(link.ts)) > this.#LINK_CACHE_LIFESPAN_HR * 3600 * 1000) {
  256. delete this.#linkCache[id];
  257. }
  258. });
  259. localStorage.setItem(this.#LINK_CACHE_NAME, this.#lzString.compressToUTF16(JSON.stringify(this.#linkCache)));
  260. // console.log('link cache count: ' + Object.keys(this.#linkCache).length, this.#linkCache);
  261. }
  262.  
  263. // Borrowed from WazeWrap
  264. static #distanceBetweenPoints(point1, point2) {
  265. const line = new OpenLayers.Geometry.LineString([point1, point2]);
  266. const length = line.getGeodesicLength(W.map.getProjectionObject());
  267. return length; // multiply by 3.28084 to convert to feet
  268. }
  269.  
  270. #isLinkTooFar(link, venue) {
  271. if (link.loc) {
  272. const linkPt = new OpenLayers.Geometry.Point(link.loc.lng, link.loc.lat);
  273. linkPt.transform(W.Config.map.projection.remote, W.map.getProjectionObject());
  274. let venuePt;
  275. let distanceLim = this.distanceLimit;
  276. if (venue.isPoint()) {
  277. venuePt = venue.geometry.getCentroid();
  278. } else {
  279. const bounds = venue.geometry.getBounds();
  280. const center = bounds.getCenterLonLat();
  281. venuePt = new OpenLayers.Geometry.Point(center.lon, center.lat);
  282. const topRightPt = new OpenLayers.Geometry.Point(bounds.right, bounds.top);
  283. distanceLim += GoogleLinkEnhancer.#distanceBetweenPoints(venuePt, topRightPt);
  284. }
  285. const distance = GoogleLinkEnhancer.#distanceBetweenPoints(linkPt, venuePt);
  286. return distance > distanceLim;
  287. }
  288. return false;
  289. }
  290.  
  291. #processPlaces() {
  292. return; // Disabled until we can find a fix.
  293. try {
  294. if (this.#enabled) {
  295. const that = this;
  296. // Get a list of already-linked id's
  297. const existingLinks = GoogleLinkEnhancer.#getExistingLinks();
  298. this.#mapLayer.removeAllFeatures();
  299. const drawnLinks = [];
  300. W.model.venues.getObjectArray().forEach(venue => {
  301. const promises = [];
  302. venue.attributes.externalProviderIDs.forEach(provID => {
  303. const id = provID.attributes.uuid;
  304.  
  305. // Check for duplicate links
  306. const linkInfo = existingLinks[id];
  307. if (linkInfo.count > 1) {
  308. const geometry = venue.isPoint() ? venue.geometry.getCentroid() : venue.geometry.clone();
  309. const width = venue.isPoint() ? '4' : '12';
  310. const color = '#fb8d00';
  311. const features = [new OpenLayers.Feature.Vector(geometry, {
  312. strokeWidth: width, strokeColor: color
  313. })];
  314. const lineStart = geometry.getCentroid();
  315. linkInfo.venues.forEach(linkVenue => {
  316. if (linkVenue !== venue
  317. && !drawnLinks.some(dl => (dl[0] === venue && dl[1] === linkVenue) || (dl[0] === linkVenue && dl[1] === venue))) {
  318. features.push(
  319. new OpenLayers.Feature.Vector(
  320. new OpenLayers.Geometry.LineString([lineStart, linkVenue.geometry.getCentroid()]),
  321. {
  322. strokeWidth: 4,
  323. strokeColor: color,
  324. strokeDashstyle: '12 12'
  325. }
  326. )
  327. );
  328. drawnLinks.push([venue, linkVenue]);
  329. }
  330. });
  331. that.#mapLayer.addFeatures(features);
  332. }
  333.  
  334. // Get Google link info, and store results for processing.
  335. promises.push(that.#getLinkInfoAsync(id));
  336. });
  337.  
  338. // Process all results of link lookups and add a highlight feature if needed.
  339. Promise.all(promises).then(results => {
  340. let strokeColor = null;
  341. let strokeDashStyle = 'solid';
  342. if (!that.#DISABLE_CLOSED_PLACES && results.some(res => res.permclosed)) {
  343. if (/^(\[|\()?(permanently )?closed(\]|\)| -)/i.test(venue.attributes.name)
  344. || /(\(|- |\[)(permanently )?closed(\)|\])?$/i.test(venue.attributes.name)) {
  345. strokeDashStyle = venue.isPoint() ? '2 6' : '2 16';
  346. }
  347. strokeColor = '#F00';
  348. } else if (results.some(res => that.#isLinkTooFar(res, venue))) {
  349. strokeColor = '#0FF';
  350. } else if (!that.#DISABLE_CLOSED_PLACES && that.#showTempClosedPOIs && results.some(res => res.tempclosed)) {
  351. if (/^(\[|\()?(temporarily )?closed(\]|\)| -)/i.test(venue.attributes.name)
  352. || /(\(|- |\[)(temporarily )?closed(\)|\])?$/i.test(venue.attributes.name)) {
  353. strokeDashStyle = venue.isPoint() ? '2 6' : '2 16';
  354. }
  355. strokeColor = '#FD3';
  356. } else if (results.some(res => res.notFound)) {
  357. strokeColor = '#F0F';
  358. }
  359. if (strokeColor) {
  360. const style = {
  361. strokeWidth: venue.isPoint() ? '4' : '12',
  362. strokeColor,
  363. strokeDashStyle
  364. };
  365. const geometry = venue.isPoint() ? venue.geometry.getCentroid() : venue.geometry.clone();
  366. that.#mapLayer.addFeatures([new OpenLayers.Feature.Vector(geometry, style)]);
  367. }
  368. });
  369. });
  370. }
  371. } catch (ex) {
  372. console.error('PIE (Google Link Enhancer) error:', ex);
  373. }
  374. }
  375.  
  376. #cacheLink(id, link) {
  377. link.ts = new Date();
  378. this.#linkCache[id] = link;
  379. // console.log('link cache count: ' + Object.keys(this.#linkCache).length, this.#linkCache);
  380. }
  381.  
  382. #getLinkInfoAsync(placeId) {
  383. return new Promise(resolve => {
  384. let link = this.#linkCache[placeId];
  385. if (!link) {
  386. const request = {
  387. placeId,
  388. fields: ['geometry', 'business_status']
  389. };
  390. this.#placesService.getDetails(request, (place, requestStatus) => {
  391. link = {};
  392. if (requestStatus === google.maps.places.PlacesServiceStatus.OK) {
  393. const loc = place.geometry.location;
  394. link.loc = { lng: loc.lng(), lat: loc.lat() };
  395. if (place.business_status === 'CLOSED_PERMANENTLY') {
  396. link.permclosed = true;
  397. } else if (place.business_status === 'CLOSED_TEMPORARILY') {
  398. link.tempclosed = true;
  399. }
  400. this.#cacheLink(placeId, link);
  401. } else if (requestStatus === google.maps.places.PlacesServiceStatus.NOT_FOUND) {
  402. link.notfound = true;
  403. this.#cacheLink(placeId, link);
  404. } else if (this.#disableApiUntil) {
  405. link.apiDisabled = true;
  406. } else {
  407. link.error = requestStatus;
  408. // res.errorMessage = json.error_message;
  409. this.#disableApiUntil = Date.now() + 10 * 1000; // Disable api calls for 10 seconds.
  410. console.error(`${GM_info.script.name}, Google Link Enhancer disabled for 10 seconds due to API error.`, link);
  411. }
  412. resolve(link);
  413. });
  414. } else {
  415. resolve(link);
  416. }
  417. });
  418. }
  419.  
  420. // _getLinkInfoAsync(id) {
  421. // const link = this.#linkCache[id];
  422. // if (link) {
  423. // return Promise.resolve(link);
  424. // }
  425. // if (this.#disableApiUntil) {
  426. // if (Date.now() < this.#disableApiUntil) {
  427. // return Promise.resolve({ apiDisabled: true });
  428. // }
  429. // this.#disableApiUntil = null;
  430. // }
  431. // return new Promise(resolve => {
  432.  
  433. // let fullUrl = this._urlBase;
  434. // if (id.startsWith('q=') || id.startsWith('cid=')) {
  435. // fullUrl += id;
  436. // } else {
  437. // fullUrl += `place_id=${id}`;
  438. // }
  439. // $.getJSON(fullUrl).then(json => {
  440. // const res = {};
  441. // if (json.status === 'OK') {
  442. // res.loc = json.result.geometry.location;
  443. // if (json.result.business_status === 'CLOSED_PERMANENTLY') {
  444. // res.permclosed = true;
  445. // } else if (json.result.business_status === 'CLOSED_TEMPORARILY') {
  446. // res.tempclosed = true;
  447. // }
  448. // this._cacheLink(id, res);
  449. // } else if (json.status === 'NOT_FOUND') {
  450. // res.notfound = true;
  451. // this._cacheLink(id, res);
  452. // } else if (this.#disableApiUntil) {
  453. // res.apiDisabled = true;
  454. // } else {
  455. // res.error = json.status;
  456. // res.errorMessage = json.error_message;
  457. // this.#disableApiUntil = Date.now() + 10 * 1000; // Disable api calls for 10 seconds.
  458. // console.error(`${GM_info.script.name}, Google Link Enhancer disabled for 10 seconds due to API error.`, res);
  459. // }
  460. // resolve(res);
  461. // });
  462. // });
  463. // }
  464.  
  465. static #onMapMouseenter(event) {
  466. // If the point isn't destroyed yet, destroy it when mousing over the map.
  467. event.data.#destroyPoint();
  468. }
  469.  
  470. async #formatLinkElements(callCount = 0) {
  471. const $links = $('#edit-panel').find(this.#EXT_PROV_ELEM_QUERY);
  472. const selFeatures = W.selectionManager.getSelectedFeatures();
  473. if (!$links.length) {
  474. // If links aren't available, continue calling this function for up to 3 seconds unless place has been deselected.
  475. if (callCount < 30 && selFeatures.length && selFeatures[0].attributes.repositoryObject.type === 'venue') {
  476. setTimeout(() => this.#formatLinkElements(++callCount), 100);
  477. }
  478. } else {
  479. const existingLinks = GoogleLinkEnhancer.#getExistingLinks();
  480.  
  481. // fetch all links first
  482. const promises = [];
  483. const extProvElements = [];
  484. $links.each((ix, linkEl) => {
  485. const $linkEl = $(linkEl);
  486. extProvElements.push($linkEl);
  487.  
  488. const id = GoogleLinkEnhancer.#getIdFromElement($linkEl);
  489. if (!id) return;
  490.  
  491. promises.push(this.#getLinkInfoAsync(id));
  492. });
  493. await Promise.all(promises);
  494.  
  495. extProvElements.forEach($extProvElem => {
  496. const id = GoogleLinkEnhancer.#getIdFromElement($extProvElem);
  497.  
  498. if (!id) return;
  499.  
  500. const link = this.#linkCache[id];
  501. if (existingLinks[id] && existingLinks[id].count > 1 && existingLinks[id].isThisVenue) {
  502. setTimeout(() => {
  503. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FFA500' }).attr({
  504. title: this.strings.linkedToXPlaces.replace('{0}', existingLinks[id].count)
  505. });
  506. }, 50);
  507. }
  508. this.#addHoverEvent($extProvElem);
  509. if (link) {
  510. if (link.permclosed && !this.#DISABLE_CLOSED_PLACES) {
  511. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FAA' }).attr('title', this.strings.permClosedPlace);
  512. } else if (link.tempclosed && !this.#DISABLE_CLOSED_PLACES) {
  513. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#FFA' }).attr('title', this.strings.tempClosedPlace);
  514. } else if (link.notFound) {
  515. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#F0F' }).attr('title', this.strings.badLink);
  516. } else {
  517. const venue = W.selectionManager.getSelectedFeatures()[0].attributes.repositoryObject;
  518. if (this.#isLinkTooFar(link, venue)) {
  519. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '#0FF' }).attr('title', this.strings.tooFar.replace('{0}', this.distanceLimit));
  520. } else { // reset in case we just deleted another provider
  521. $extProvElem.find(this.#EXT_PROV_ELEM_CONTENT_QUERY).css({ backgroundColor: '' }).attr('title', '');
  522. }
  523. }
  524. }
  525. });
  526. }
  527. }
  528.  
  529. static #getExistingLinks() {
  530. const existingLinks = {};
  531. let thisVenue;
  532. if (W.selectionManager.getSelectedFeatures().length) {
  533. thisVenue = W.selectionManager.getSelectedFeatures()[0].attributes.repositoryObject;
  534. }
  535. W.model.venues.getObjectArray().forEach(venue => {
  536. const isThisVenue = venue === thisVenue;
  537. const thisPlaceIDs = [];
  538. venue.attributes.externalProviderIDs.forEach(provID => {
  539. const id = provID.attributes.uuid;
  540. if (thisPlaceIDs.indexOf(id) === -1) {
  541. thisPlaceIDs.push(id);
  542. let link = existingLinks[id];
  543. if (link) {
  544. link.count++;
  545. link.venues.push(venue);
  546. } else {
  547. link = { count: 1, venues: [venue] };
  548. existingLinks[id] = link;
  549. if (provID.attributes.url != null) {
  550. const u = provID.attributes.url.replace('https://maps.google.com/?', '');
  551. link.url = u;
  552. }
  553. }
  554. link.isThisVenue = link.isThisVenue || isThisVenue;
  555. }
  556. });
  557. });
  558. return existingLinks;
  559. }
  560.  
  561. // Remove the POI point from the map.
  562. #destroyPoint() {
  563. if (this.#ptFeature) {
  564. this.#ptFeature.destroy();
  565. this.#ptFeature = null;
  566. this.#lineFeature.destroy();
  567. this.#lineFeature = null;
  568. }
  569. }
  570.  
  571. // Add the POI point to the map.
  572. #addPoint(id) {
  573. if (!id) return;
  574. const link = this.#linkCache[id];
  575. if (link) {
  576. if (!link.notFound) {
  577. const coord = link.loc;
  578. const poiPt = new OpenLayers.Geometry.Point(coord.lng, coord.lat);
  579. poiPt.transform(W.Config.map.projection.remote, W.map.getProjectionObject().projCode);
  580. const placeGeom = W.selectionManager.getSelectedFeatures()[0].geometry.getCentroid();
  581. const placePt = new OpenLayers.Geometry.Point(placeGeom.x, placeGeom.y);
  582. const ext = W.map.getExtent();
  583. const lsBounds = new OpenLayers.Geometry.LineString([
  584. new OpenLayers.Geometry.Point(ext.left, ext.bottom),
  585. new OpenLayers.Geometry.Point(ext.left, ext.top),
  586. new OpenLayers.Geometry.Point(ext.right, ext.top),
  587. new OpenLayers.Geometry.Point(ext.right, ext.bottom),
  588. new OpenLayers.Geometry.Point(ext.left, ext.bottom)]);
  589. let lsLine = new OpenLayers.Geometry.LineString([placePt, poiPt]);
  590.  
  591. // If the line extends outside the bounds, split it so we don't draw a line across the world.
  592. const splits = lsLine.splitWith(lsBounds);
  593. let label = '';
  594. if (splits) {
  595. let splitPoints;
  596. splits.forEach(split => {
  597. split.components.forEach(component => {
  598. if (component.x === placePt.x && component.y === placePt.y) splitPoints = split;
  599. });
  600. });
  601. lsLine = new OpenLayers.Geometry.LineString([splitPoints.components[0], splitPoints.components[1]]);
  602. let distance = GoogleLinkEnhancer.#distanceBetweenPoints(poiPt, placePt);
  603. let unitConversion;
  604. let unit1;
  605. let unit2;
  606. if (W.model.isImperial) {
  607. distance *= 3.28084;
  608. unitConversion = 5280;
  609. unit1 = ' ft';
  610. unit2 = ' mi';
  611. } else {
  612. unitConversion = 1000;
  613. unit1 = ' m';
  614. unit2 = ' km';
  615. }
  616. if (distance > unitConversion * 10) {
  617. label = Math.round(distance / unitConversion) + unit2;
  618. } else if (distance > 1000) {
  619. label = (Math.round(distance / (unitConversion / 10)) / 10) + unit2;
  620. } else {
  621. label = Math.round(distance) + unit1;
  622. }
  623. }
  624.  
  625. this.#destroyPoint(); // Just in case it still exists.
  626. this.#ptFeature = new OpenLayers.Feature.Vector(poiPt, { poiCoord: true }, {
  627. pointRadius: 6,
  628. strokeWidth: 30,
  629. strokeColor: '#FF0',
  630. fillColor: '#FF0',
  631. strokeOpacity: 0.5
  632. });
  633. this.#lineFeature = new OpenLayers.Feature.Vector(lsLine, {}, {
  634. strokeWidth: 3,
  635. strokeDashstyle: '12 8',
  636. strokeColor: '#FF0',
  637. label,
  638. labelYOffset: 45,
  639. fontColor: '#FF0',
  640. fontWeight: 'bold',
  641. labelOutlineColor: '#000',
  642. labelOutlineWidth: 4,
  643. fontSize: '18'
  644. });
  645. W.map.getLayerByUniqueName('venues').addFeatures([this.#ptFeature, this.#lineFeature]);
  646. this.#timeoutDestroyPoint();
  647. }
  648. } else {
  649. this.#getLinkInfoAsync(id).then(res => {
  650. if (res.error || res.apiDisabled) {
  651. // API was temporarily disabled. Ignore for now.
  652. } else {
  653. this.#addPoint(id);
  654. }
  655. });
  656. }
  657. }
  658.  
  659. // Destroy the point after some time, if it hasn't been destroyed already.
  660. #timeoutDestroyPoint() {
  661. if (this.#timeoutID) clearTimeout(this.#timeoutID);
  662. this.#timeoutID = setTimeout(() => this.#destroyPoint(), 4000);
  663. }
  664.  
  665. static #getIdFromElement($el) {
  666. const providerIndex = $el.parent().children().toArray().indexOf($el[0]);
  667. return W.selectionManager.getSelectedFeatures()[0].attributes.repositoryObject.getExternalProviderIDs()[providerIndex]?.attributes.uuid;
  668. }
  669.  
  670. #addHoverEvent($el) {
  671. $el.hover(() => this.#addPoint(GoogleLinkEnhancer.#getIdFromElement($el)), () => this.#destroyPoint());
  672. }
  673.  
  674. #observeLinks() {
  675. this.elem = document.querySelector('#edit-panel');
  676. this.#linkObserver.observe(document.querySelector('#edit-panel'), { childList: true, subtree: true });
  677. }
  678.  
  679. // The JSONP interceptor is used to watch the head element for the addition of JSONP functions
  680. // that process Google link search results. Those functions are overridden by our own so we can
  681. // process the results before sending them on to the original function.
  682. #addJsonpInterceptor() {
  683. // The idea for this function was hatched here:
  684. // https://stackoverflow.com/questions/6803521/can-google-maps-places-autocomplete-api-be-used-via-ajax/9856786
  685.  
  686. // The head element, where the Google Autocomplete code will insert a tag
  687. // for a javascript file.
  688. const head = $('head')[0];
  689. // The name of the method the Autocomplete code uses to insert the tag.
  690. const method = 'appendChild';
  691. // The method we will be overriding.
  692. const originalMethod = head[method];
  693. this.#originalHeadAppendChildMethod = originalMethod;
  694. const that = this;
  695. /* eslint-disable func-names, prefer-rest-params */ // Doesn't work as an arrow function (at least not without some modifications)
  696. head[method] = function() {
  697. // Check that the element is a javascript tag being inserted by Google.
  698. if (arguments[0] && arguments[0].src && arguments[0].src.match(/GetPredictions/)) {
  699. // Regex to extract the name of the callback method that the JSONP will call.
  700. const callbackMatchObject = (/callback=([^&]+)&|$/).exec(arguments[0].src);
  701.  
  702. // Regex to extract the search term that was entered by the user.
  703. const searchTermMatchObject = (/\?1s([^&]+)&/).exec(arguments[0].src);
  704.  
  705. // const searchTerm = unescape(searchTermMatchObject[1]);
  706. if (callbackMatchObject && searchTermMatchObject) {
  707. // The JSONP callback method is in the form "abc.def" and each time has a different random name.
  708. const names = callbackMatchObject[1].split('.');
  709. // Store the original callback method.
  710. const originalCallback = names[0] && names[1] && window[names[0]] && window[names[0]][names[1]];
  711.  
  712. if (originalCallback) {
  713. const newCallback = function() { // Define your own JSONP callback
  714. if (arguments[0] && arguments[0].predictions) {
  715. // SUCCESS!
  716.  
  717. // The autocomplete results
  718. const data = arguments[0];
  719.  
  720. // console.log('GLE: ' + JSON.stringify(data));
  721. that._lastSearchResultPlaceIds = data.predictions.map(pred => pred.place_id);
  722.  
  723. // Call the original callback so the WME dropdown can do its thing.
  724. originalCallback(data);
  725. }
  726. };
  727.  
  728. // Add copy of all the attributes of the old callback function to the new callback function.
  729. // This prevents the autocomplete functionality from throwing an error.
  730. Object.keys(originalCallback).forEach(key => {
  731. newCallback[key] = originalCallback[key];
  732. });
  733. window[names[0]][names[1]] = newCallback; // Override the JSONP callback
  734. }
  735. }
  736. }
  737. // Insert the element into the dom, regardless of whether it was being inserted by Google.
  738. return originalMethod.apply(this, arguments);
  739. };
  740. /* eslint-enable func-names, prefer-rest-params */
  741. }
  742.  
  743. #removeJsonpInterceptor() {
  744. $('head')[0].appendChild = this.#originalHeadAppendChildMethod;
  745. }
  746.  
  747. /* eslint-disable */ // Disabling eslint since this is copied code.
  748. #initLZString() {
  749. // LZ Compressor
  750. // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
  751. // This work is free. You can redistribute it and/or modify it
  752. // under the terms of the WTFPL, Version 2
  753. // LZ-based compression algorithm, version 1.4.4
  754. this.#lzString = (function () {
  755. // private property
  756. const f = String.fromCharCode;
  757. const keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  758. const keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
  759. const baseReverseDic = {};
  760.  
  761. function getBaseValue(alphabet, character) {
  762. if (!baseReverseDic[alphabet]) {
  763. baseReverseDic[alphabet] = {};
  764. for (let i = 0; i < alphabet.length; i++) {
  765. baseReverseDic[alphabet][alphabet.charAt(i)] = i;
  766. }
  767. }
  768. return baseReverseDic[alphabet][character];
  769. }
  770. var LZString = {
  771. compressToBase64: function (input) {
  772. if (input === null) return "";
  773. const res = LZString._compress(input, 6, function (a) {
  774. return keyStrBase64.charAt(a);
  775. });
  776. switch (res.length % 4) { // To produce valid Base64
  777. default: // When could this happen ?
  778. case 0:
  779. return res;
  780. case 1:
  781. return res + "===";
  782. case 2:
  783. return res + "==";
  784. case 3:
  785. return res + "=";
  786. }
  787. },
  788. decompressFromBase64: function (input) {
  789. if (input === null) return "";
  790. if (input === "") return null;
  791. return LZString._decompress(input.length, 32, function (index) {
  792. return getBaseValue(keyStrBase64, input.charAt(index));
  793. });
  794. },
  795. compressToUTF16: function (input) {
  796. if (input === null) return "";
  797. return LZString._compress(input, 15, function (a) {
  798. return f(a + 32);
  799. }) + " ";
  800. },
  801. decompressFromUTF16: function (compressed) {
  802. if (compressed === null) return "";
  803. if (compressed === "") return null;
  804. return LZString._decompress(compressed.length, 16384, function (index) {
  805. return compressed.charCodeAt(index) - 32;
  806. });
  807. },
  808.  
  809. compress: function (uncompressed) {
  810. return LZString._compress(uncompressed, 16, function (a) {
  811. return f(a);
  812. });
  813. },
  814. _compress: function (uncompressed, bitsPerChar, getCharFromInt) {
  815. if (uncompressed === null) return "";
  816. let i, value,
  817. context_dictionary = {},
  818. context_dictionaryToCreate = {},
  819. context_c = "",
  820. context_wc = "",
  821. context_w = "",
  822. context_enlargeIn = 2, // Compensate for the first entry which should not count
  823. context_dictSize = 3,
  824. context_numBits = 2,
  825. context_data = [],
  826. context_data_val = 0,
  827. context_data_position = 0,
  828. ii;
  829. for (ii = 0; ii < uncompressed.length; ii += 1) {
  830. context_c = uncompressed.charAt(ii);
  831. if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
  832. context_dictionary[context_c] = context_dictSize++;
  833. context_dictionaryToCreate[context_c] = true;
  834. }
  835. context_wc = context_w + context_c;
  836. if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
  837. context_w = context_wc;
  838. } else {
  839. if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
  840. if (context_w.charCodeAt(0) < 256) {
  841. for (i = 0; i < context_numBits; i++) {
  842. context_data_val = (context_data_val << 1);
  843. if (context_data_position === bitsPerChar - 1) {
  844. context_data_position = 0;
  845. context_data.push(getCharFromInt(context_data_val));
  846. context_data_val = 0;
  847. } else {
  848. context_data_position++;
  849. }
  850. }
  851. value = context_w.charCodeAt(0);
  852. for (i = 0; i < 8; i++) {
  853. context_data_val = (context_data_val << 1) | (value & 1);
  854. if (context_data_position === bitsPerChar - 1) {
  855. context_data_position = 0;
  856. context_data.push(getCharFromInt(context_data_val));
  857. context_data_val = 0;
  858. } else {
  859. context_data_position++;
  860. }
  861. value = value >> 1;
  862. }
  863. } else {
  864. value = 1;
  865. for (i = 0; i < context_numBits; i++) {
  866. context_data_val = (context_data_val << 1) | value;
  867. if (context_data_position === bitsPerChar - 1) {
  868. context_data_position = 0;
  869. context_data.push(getCharFromInt(context_data_val));
  870. context_data_val = 0;
  871. } else {
  872. context_data_position++;
  873. }
  874. value = 0;
  875. }
  876. value = context_w.charCodeAt(0);
  877. for (i = 0; i < 16; i++) {
  878. context_data_val = (context_data_val << 1) | (value & 1);
  879. if (context_data_position === bitsPerChar - 1) {
  880. context_data_position = 0;
  881. context_data.push(getCharFromInt(context_data_val));
  882. context_data_val = 0;
  883. } else {
  884. context_data_position++;
  885. }
  886. value = value >> 1;
  887. }
  888. }
  889. context_enlargeIn--;
  890. if (context_enlargeIn === 0) {
  891. context_enlargeIn = Math.pow(2, context_numBits);
  892. context_numBits++;
  893. }
  894. delete context_dictionaryToCreate[context_w];
  895. } else {
  896. value = context_dictionary[context_w];
  897. for (i = 0; i < context_numBits; i++) {
  898. context_data_val = (context_data_val << 1) | (value & 1);
  899. if (context_data_position === bitsPerChar - 1) {
  900. context_data_position = 0;
  901. context_data.push(getCharFromInt(context_data_val));
  902. context_data_val = 0;
  903. } else {
  904. context_data_position++;
  905. }
  906. value = value >> 1;
  907. }
  908. }
  909. context_enlargeIn--;
  910. if (context_enlargeIn === 0) {
  911. context_enlargeIn = Math.pow(2, context_numBits);
  912. context_numBits++;
  913. }
  914. // Add wc to the dictionary.
  915. context_dictionary[context_wc] = context_dictSize++;
  916. context_w = String(context_c);
  917. }
  918. }
  919. // Output the code for w.
  920. if (context_w !== "") {
  921. if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
  922. if (context_w.charCodeAt(0) < 256) {
  923. for (i = 0; i < context_numBits; i++) {
  924. context_data_val = (context_data_val << 1);
  925. if (context_data_position === bitsPerChar - 1) {
  926. context_data_position = 0;
  927. context_data.push(getCharFromInt(context_data_val));
  928. context_data_val = 0;
  929. } else {
  930. context_data_position++;
  931. }
  932. }
  933. value = context_w.charCodeAt(0);
  934. for (i = 0; i < 8; i++) {
  935. context_data_val = (context_data_val << 1) | (value & 1);
  936. if (context_data_position === bitsPerChar - 1) {
  937. context_data_position = 0;
  938. context_data.push(getCharFromInt(context_data_val));
  939. context_data_val = 0;
  940. } else {
  941. context_data_position++;
  942. }
  943. value = value >> 1;
  944. }
  945. } else {
  946. value = 1;
  947. for (i = 0; i < context_numBits; i++) {
  948. context_data_val = (context_data_val << 1) | value;
  949. if (context_data_position === bitsPerChar - 1) {
  950. context_data_position = 0;
  951. context_data.push(getCharFromInt(context_data_val));
  952. context_data_val = 0;
  953. } else {
  954. context_data_position++;
  955. }
  956. value = 0;
  957. }
  958. value = context_w.charCodeAt(0);
  959. for (i = 0; i < 16; i++) {
  960. context_data_val = (context_data_val << 1) | (value & 1);
  961. if (context_data_position === bitsPerChar - 1) {
  962. context_data_position = 0;
  963. context_data.push(getCharFromInt(context_data_val));
  964. context_data_val = 0;
  965. } else {
  966. context_data_position++;
  967. }
  968. value = value >> 1;
  969. }
  970. }
  971. context_enlargeIn--;
  972. if (context_enlargeIn === 0) {
  973. context_enlargeIn = Math.pow(2, context_numBits);
  974. context_numBits++;
  975. }
  976. delete context_dictionaryToCreate[context_w];
  977. } else {
  978. value = context_dictionary[context_w];
  979. for (i = 0; i < context_numBits; i++) {
  980. context_data_val = (context_data_val << 1) | (value & 1);
  981. if (context_data_position === bitsPerChar - 1) {
  982. context_data_position = 0;
  983. context_data.push(getCharFromInt(context_data_val));
  984. context_data_val = 0;
  985. } else {
  986. context_data_position++;
  987. }
  988. value = value >> 1;
  989. }
  990. }
  991. context_enlargeIn--;
  992. if (context_enlargeIn === 0) {
  993. context_enlargeIn = Math.pow(2, context_numBits);
  994. context_numBits++;
  995. }
  996. }
  997. // Mark the end of the stream
  998. value = 2;
  999. for (i = 0; i < context_numBits; i++) {
  1000. context_data_val = (context_data_val << 1) | (value & 1);
  1001. if (context_data_position === bitsPerChar - 1) {
  1002. context_data_position = 0;
  1003. context_data.push(getCharFromInt(context_data_val));
  1004. context_data_val = 0;
  1005. } else {
  1006. context_data_position++;
  1007. }
  1008. value = value >> 1;
  1009. }
  1010. // Flush the last char
  1011. while (true) {
  1012. context_data_val = (context_data_val << 1);
  1013. if (context_data_position === bitsPerChar - 1) {
  1014. context_data.push(getCharFromInt(context_data_val));
  1015. break;
  1016. } else context_data_position++;
  1017. }
  1018. return context_data.join('');
  1019. },
  1020. decompress: function (compressed) {
  1021. if (compressed === null) return "";
  1022. if (compressed === "") return null;
  1023. return LZString._decompress(compressed.length, 32768, function (index) {
  1024. return compressed.charCodeAt(index);
  1025. });
  1026. },
  1027. _decompress: function (length, resetValue, getNextValue) {
  1028. let dictionary = [],
  1029. next,
  1030. enlargeIn = 4,
  1031. dictSize = 4,
  1032. numBits = 3,
  1033. entry = "",
  1034. result = [],
  1035. i,
  1036. w,
  1037. bits, resb, maxpower, power,
  1038. c,
  1039. data = {
  1040. val: getNextValue(0),
  1041. position: resetValue,
  1042. index: 1
  1043. };
  1044. for (i = 0; i < 3; i += 1) {
  1045. dictionary[i] = i;
  1046. }
  1047. bits = 0;
  1048. maxpower = Math.pow(2, 2);
  1049. power = 1;
  1050. while (power !== maxpower) {
  1051. resb = data.val & data.position;
  1052. data.position >>= 1;
  1053. if (data.position === 0) {
  1054. data.position = resetValue;
  1055. data.val = getNextValue(data.index++);
  1056. }
  1057. bits |= (resb > 0 ? 1 : 0) * power;
  1058. power <<= 1;
  1059. }
  1060. switch (next = bits) {
  1061. case 0:
  1062. bits = 0;
  1063. maxpower = Math.pow(2, 8);
  1064. power = 1;
  1065. while (power !== maxpower) {
  1066. resb = data.val & data.position;
  1067. data.position >>= 1;
  1068. if (data.position === 0) {
  1069. data.position = resetValue;
  1070. data.val = getNextValue(data.index++);
  1071. }
  1072. bits |= (resb > 0 ? 1 : 0) * power;
  1073. power <<= 1;
  1074. }
  1075. c = f(bits);
  1076. break;
  1077. case 1:
  1078. bits = 0;
  1079. maxpower = Math.pow(2, 16);
  1080. power = 1;
  1081. while (power !== maxpower) {
  1082. resb = data.val & data.position;
  1083. data.position >>= 1;
  1084. if (data.position === 0) {
  1085. data.position = resetValue;
  1086. data.val = getNextValue(data.index++);
  1087. }
  1088. bits |= (resb > 0 ? 1 : 0) * power;
  1089. power <<= 1;
  1090. }
  1091. c = f(bits);
  1092. break;
  1093. case 2:
  1094. return "";
  1095. }
  1096. dictionary[3] = c;
  1097. w = c;
  1098. result.push(c);
  1099. while (true) {
  1100. if (data.index > length) {
  1101. return "";
  1102. }
  1103. bits = 0;
  1104. maxpower = Math.pow(2, numBits);
  1105. power = 1;
  1106. while (power !== maxpower) {
  1107. resb = data.val & data.position;
  1108. data.position >>= 1;
  1109. if (data.position === 0) {
  1110. data.position = resetValue;
  1111. data.val = getNextValue(data.index++);
  1112. }
  1113. bits |= (resb > 0 ? 1 : 0) * power;
  1114. power <<= 1;
  1115. }
  1116. switch (c = bits) {
  1117. case 0:
  1118. bits = 0;
  1119. maxpower = Math.pow(2, 8);
  1120. power = 1;
  1121. while (power !== maxpower) {
  1122. resb = data.val & data.position;
  1123. data.position >>= 1;
  1124. if (data.position === 0) {
  1125. data.position = resetValue;
  1126. data.val = getNextValue(data.index++);
  1127. }
  1128. bits |= (resb > 0 ? 1 : 0) * power;
  1129. power <<= 1;
  1130. }
  1131. dictionary[dictSize++] = f(bits);
  1132. c = dictSize - 1;
  1133. enlargeIn--;
  1134. break;
  1135. case 1:
  1136. bits = 0;
  1137. maxpower = Math.pow(2, 16);
  1138. power = 1;
  1139. while (power !== maxpower) {
  1140. resb = data.val & data.position;
  1141. data.position >>= 1;
  1142. if (data.position === 0) {
  1143. data.position = resetValue;
  1144. data.val = getNextValue(data.index++);
  1145. }
  1146. bits |= (resb > 0 ? 1 : 0) * power;
  1147. power <<= 1;
  1148. }
  1149. dictionary[dictSize++] = f(bits);
  1150. c = dictSize - 1;
  1151. enlargeIn--;
  1152. break;
  1153. case 2:
  1154. return result.join('');
  1155. }
  1156. if (enlargeIn === 0) {
  1157. enlargeIn = Math.pow(2, numBits);
  1158. numBits++;
  1159. }
  1160. if (dictionary[c]) {
  1161. entry = dictionary[c];
  1162. } else {
  1163. if (c === dictSize) {
  1164. entry = w + w.charAt(0);
  1165. } else {
  1166. return null;
  1167. }
  1168. }
  1169. result.push(entry);
  1170. // Add w+entry[0] to the dictionary.
  1171. dictionary[dictSize++] = w + entry.charAt(0);
  1172. enlargeIn--;
  1173. w = entry;
  1174. if (enlargeIn === 0) {
  1175. enlargeIn = Math.pow(2, numBits);
  1176. numBits++;
  1177. }
  1178. }
  1179. }
  1180. };
  1181. return LZString;
  1182. })();
  1183. }
  1184. /* eslint-enable */
  1185. }