GeoGuessr Path Logger

Adds a trace of where you have been to GeoGuessr's results screen

目前為 2023-03-01 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name GeoGuessr Path Logger
  3. // @version 0.4.1
  4. // @description Adds a trace of where you have been to GeoGuessr's results screen
  5. // @match https://www.geoguessr.com/*
  6. // @author victheturtle#5159
  7. // @license MIT
  8. // @run-at document-start
  9. // @require https://openuserjs.org/src/libs/xsanda/Run_code_as_client.js
  10. // @require https://openuserjs.org/src/libs/xsanda/Google_Maps_Promise.js
  11. // @namespace https://gf.qytechs.cn/users/967692-victheturtle
  12. // ==/UserScript==
  13. // credits to xsanda (https://openuserjs.org/users/xsanda) for the original GeoGuessr Path Logger script
  14.  
  15. /*jshint esversion: 6 */
  16.  
  17. googleMapsPromise.then(() => runAsClient(() => {
  18. const google = window.google;
  19.  
  20. const KEEP_FOR = 1000 * 60 * 60 * 24 * 7; // 1 week
  21.  
  22. // Keep a track of the lines drawn on the map, so they can be removed
  23. let markers = [];
  24.  
  25. const isGamePage = () => location.pathname.startsWith("/challenge/") || location.pathname.startsWith("/results/") || location.pathname.startsWith("/game/") ||
  26. location.pathname.startsWith("/duels/") || location.pathname.startsWith("/team-duels/");
  27.  
  28. // Detect if only a single result is shown
  29. const singleResult = () => !!document.querySelector('div[class^="round-result_distanceIndicatorWrapper__"]') ||
  30. (!!document.querySelector('[class^="overlay_backdrop__"], [class^="overlay_overlay__"]') && !document.querySelector('[class^=new-round_roundNumber__]') &&
  31. !document.querySelector('[class^=new-game_container__]'));
  32.  
  33. // Detect if a results screen is visible, so the traces should be shown
  34. const resultShown = () => singleResult() || !!document.querySelector('div[class^="result-overlay_overlayTotalScore__"]') || location.href.includes('results') ||
  35. !!document.querySelector('[class^="game-summary_container__"]') || location.href.includes('summary');
  36.  
  37. // Keep a track of whether we are in a round already
  38. let inGame = false;
  39.  
  40. // Get the game ID, for storing the trace against
  41. const id = () => {
  42. const split = location.href.split("/")
  43. if (split[split.length-1] == "summary") return split[split.length-2]
  44. else return split[split.length-1]
  45. }
  46. const roundNumber = () => {
  47. const el = document.querySelector('[data-qa=round-number] :nth-child(2)');
  48. const el2 = document.querySelector('[class^=round-score_roundNumber__]');
  49. return el ? parseInt(el.innerHTML) : (el2 ? parseInt(el2.innerHTML.split(" ")[1]) : 0);
  50. };
  51. const roundID = (n, gameID) => (gameID || id()) + '-' + (n || roundNumber());
  52.  
  53. // Get the location of the street view
  54. const getPosition = sv => ({
  55. lat: sv.position.lat(),
  56. lng: sv.position.lng(),
  57. });
  58.  
  59. // Record the time a game was played
  60. const updateTimestamp = () => {
  61. const timestamps = JSON.parse(localStorage.timestamps || "{}");
  62. timestamps[id()] = Date.now();
  63. localStorage.timestamps = JSON.stringify(timestamps);
  64. };
  65.  
  66. // Remove all games older than a week
  67. const clearOldGames = () => {
  68. const timestamps = JSON.parse(localStorage.timestamps || "{}");
  69. // Delete all games older than a week
  70. const cutoff = Date.now() - KEEP_FOR;
  71. for (const [gameID, gameTime] of Object.entries(timestamps)) {
  72. if (gameTime < cutoff) {
  73. delete timestamps[gameID];
  74. Object.keys(localStorage).filter(key => key.startsWith(gameID)).forEach(key => delete localStorage[key]);
  75. }
  76. }
  77. localStorage.timestamps = JSON.stringify(timestamps);
  78. };
  79.  
  80. const R = 6371.071; // radius of the Earth
  81. const distance = (mk1lat, mk1lng, mk2lat, mk2lng) => {
  82. const rlat1 = mk1lat * (Math.PI / 180)
  83. const rlat2 = mk2lat * (Math.PI / 180)
  84. const difflat = rlat2 - rlat1
  85. const difflon = (mk2lng - mk1lng) * (Math.PI / 180);
  86. const km = 2*R * Math.asin(Math.sqrt(
  87. Math.sin(difflat/2) * Math.sin(difflat/2) +
  88. Math.cos(rlat1) * Math.cos(rlat2) * Math.sin(difflon/2) * Math.sin(difflon/2)
  89. ))
  90. return km;
  91. }
  92.  
  93. clearOldGames();
  94.  
  95. // Keep a track of the current round’s route
  96. let route;
  97.  
  98. let currentRound = undefined;
  99.  
  100. // Keep a track of the start location for the current round, for detecting the return to start button
  101. let start;
  102. let lastPosition = undefined;
  103.  
  104. // Handle the street view being navigated
  105. const onMove = (sv) => {
  106. try {
  107. if (!isGamePage()) return;
  108.  
  109. const position = getPosition(sv);
  110.  
  111. if (!inGame) {
  112. // Do nothing if the map is being updated in the background, e.g. on page load while the results are still shown
  113. if (resultShown()) return;
  114. // otherwise start the round
  115. inGame = true;
  116. start = position;
  117. route = [];
  118. } else if (currentRound !== roundID()) {
  119. currentRound = roundID();
  120. start = position;
  121. route = [];
  122. }
  123.  
  124. // If we’re at the start or moving too far in one click, assume the flag or checkpoint feature were used and begin a new trace
  125. if (position.lat == start.lat && position.lng == start.lng ||
  126. lastPosition != undefined && distance(lastPosition.lat, lastPosition.lng, position.lat, position.lng) > 0.2) {
  127. start = position;
  128. route.push([]);
  129. }
  130.  
  131. lastPosition = position;
  132.  
  133. // Add the location to the trace
  134. route[route.length - 1].push(position);
  135. }
  136. catch (e) {
  137. console.error("GeoGuessr Path Logger Error:", e);
  138. }
  139. };
  140.  
  141. let mapState = 0;
  142.  
  143. // The geometry API isn’t loaded unless a Street View has been displayed since the last load.
  144. const loadGeometry = () => new Promise((resolve, reject) => {
  145. const existingScript = document.querySelector("script[src^='https://maps.googleapis.com/maps-api-v3/api/js/']")
  146. if (!existingScript) reject("No Google Maps loaded yet");
  147. const libraryURL = existingScript.src.replace(/(.+\/)(.+?)(\.js)/, '$1geometry$3');
  148. document.head.appendChild(Object.assign(document.createElement("script"), {
  149. onload: resolve,
  150. type: "text/javascript",
  151. src: libraryURL,
  152. }));
  153. });
  154.  
  155. const onMapUpdate = (map) => {
  156. try {
  157. if (!isGamePage()) return;
  158.  
  159. if (!google.maps.geometry) {
  160. loadGeometry().then(() => onMapUpdate(map));
  161. return;
  162. }
  163.  
  164. // create a checksum of the game state, only updating the map when this changes, to save on computation
  165. const newMapState = (inGame ? 50 : 0) + (resultShown() ? 100 : 0) + (singleResult() ? 200 : 0) + roundNumber();
  166. if (newMapState == mapState) return;
  167. mapState = newMapState;
  168.  
  169. // Hide all traces
  170. markers.forEach(m => m.setMap(null));
  171. // If we’re looking at the results, draw the traces again
  172. if (resultShown()) {
  173. // If we were in a round the last time we checked, then we need to save the route
  174. if (inGame) {
  175. // encode the route to reduce the storage required.
  176. const encodedRoutes = route.map(path => google.maps.geometry.encoding.encodePath(path.map(point => new google.maps.LatLng(point))));
  177. localStorage[roundID()] = JSON.stringify(encodedRoutes);
  178. updateTimestamp();
  179. }
  180. inGame = false;
  181. // Show all rounds for the current game when viewing the full results
  182. const roundsToShow = singleResult() ? [roundID()] : Object.keys(localStorage).filter(map => map.startsWith(id()));
  183. markers = roundsToShow
  184. .map(key => localStorage[key]) // Get the map for this round
  185. .filter(r => r) // Ignore missing rounds
  186. .flatMap(r =>
  187. // Render each trace within each round as a red line
  188. JSON.parse(r).map(polyline =>
  189. new google.maps.Polyline({
  190. path: google.maps.geometry.encoding.decodePath(polyline),
  191. geodesic: true,
  192. strokeColor: '#FF0000',
  193. strokeOpacity: 1.0,
  194. strokeWeight: 2,
  195. })
  196. )
  197. );
  198.  
  199. // Add all traces to the map
  200. markers.forEach(m => m.setMap(map));
  201.  
  202. }
  203. }
  204. catch (e) {
  205. console.error("GeoGuessr Path Logger Error:", e);
  206. }
  207. };
  208.  
  209. // When a StreetViewPanorama is constructed, add a listener for moving
  210. const oldSV = google.maps.StreetViewPanorama;
  211. google.maps.StreetViewPanorama = Object.assign(function (...args) {
  212. const res = oldSV.apply(this, args);
  213. this.addListener('position_changed', () => onMove(this));
  214. return res;
  215. }, {
  216. prototype: Object.create(oldSV.prototype)
  217. });
  218.  
  219. // When a Map is constructed, add a listener for updating
  220. const oldMap = google.maps.Map;
  221. google.maps.Map = Object.assign(function (...args) {
  222. const res = oldMap.apply(this, args);
  223. this.addListener('idle', () => onMapUpdate(this));
  224. return res;
  225. }, {
  226. prototype: Object.create(oldMap.prototype)
  227. });
  228. }));

QingJ © 2025

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