Geoguessr 5k radius displayer

Adds the 5k radius to community maps pages

目前為 2025-08-05 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Geoguessr 5k radius displayer
// @description  Adds the 5k radius to community maps pages
// @version      0.1.3
// @license      MIT
// @author       irrational
// @match        https://www.geoguessr.com/*
// @require      https://greasyfork.org/scripts/460322-geoguessr-styles-scan/code/Geoguessr%20Styles%20Scan.js?version=1151668
// @namespace    https://greasyfork.org/users/1501600
// ==/UserScript==


const USERSCRIPT_RADIUS_BLOCK_CLASS = "___userscript-radius-block";

const TRANSLATIONS = {
  "en": "5k radius",
  "de": "5k-Radius",
  "es": "radio de 5k",
  "fr": "rayon de 5k",
  "it": "raggio di 5k",
  "nl": "5k straal",
  "pt": "raio de 5k",
  "sv": "5k radie",
  "tr": "5k yarıçap",
  "ja": "5k半径",
  "pl": "promień 5k",
  "ko": "5k 반경"
}


/* Run only on maps pages. Because the Geoguessr frontend is a React application, URL updates are not
   always registered (by Tampermonkey on Firefox at least) for the purpose of finding out whether
   the script should be loaded at all. So unfortunately, we must @match on the entire website.

   Also, run only on community maps. Official map IDs are retrievable via the /api/maps/explorer
   endpoint, but these IDs 404 on /api/maps/<id>. */
const checkURL = () => location.pathname.match(/^\/([a-z]{2}\/)?maps\/[0-9a-fA-F]{24}$/);


const fetchMap = async (mapId) => {
    return fetch("https://www.geoguessr.com/api/maps/" + mapId)
        .then(out => out.json())
        .catch(err => { console.log("5k radius displayer in fetchMap():", err); return null; });
}


const getLanguage = () => {
    if (location.pathname.startsWith('/maps/')) return 'en';
    return location.pathname.substring(1, 3);
}


const fetchDistanceUnit = async () => {
    return fetch("https://www.geoguessr.com/api/v3/profiles")
        .then(out => out.json())
        .then(profile => profile.distanceUnit == 1 ? 'yd' : 'm')
        .catch(err => { console.log("5k radius displayer in fetchDistanceUnit():", err); return null; });
}


const createRadiusBlock = () => {
    let radiusBlock = document.createElement('div');
    radiusBlock.className = cn("community-map-stat_mapStat__") + " " + USERSCRIPT_RADIUS_BLOCK_CLASS;
    let statIcon = document.createElement('div');
    statIcon.className = cn("community-map-stat_icon__");
    let statContent = document.createElement('div');
    statContent.className = cn("community-map-stat_content__");
    let statValue = document.createElement('div');
    statValue.className = cn("community-map-stat_value__");
    let statTitle = document.createElement('div');
    statTitle.className = cn("community-map-stat_title__");
    statContent.appendChild(statValue);
    statContent.appendChild(statTitle);
    radiusBlock.appendChild(statIcon);
    radiusBlock.appendChild(statContent);
    statIcon.innerHTML = String.fromCodePoint(0x1F4CD); // round pushpin emoji
    statTitle.innerHTML = TRANSLATIONS[getLanguage()] || TRANSLATIONS.en;
    return radiusBlock;
}


const fillRadiusBlock = (radiusBlock, content, fontStyle = null) => {
    let statValue = radiusBlock.querySelector("." + cn("community-map-stat_value__"));
    statValue.innerHTML = content;
    if (fontStyle) statValue.style.fontStyle = fontStyle;
}


var lastMapId = null;
var lastLanguage = null;

const run = async () => {
    scanStyles().then(_ => {
        let statsContainer = document.querySelector("." + cn("community-map-block_mapStatsContainer__"));
        /* Before there is a stats container in the DOM, there is nothing to do. */
        if (! statsContainer) return;

        /* Multiple mutations may occur and trigger this function before we have created
           the radius block, so acquire a lock and release it once we've created and filled
           the block in order to avoid adding multiple. */
        navigator.locks.request("radius_block", async (lock) => {
            let mapId = location.pathname.split('/').pop();
            let radiusBlock = document.querySelector("." + USERSCRIPT_RADIUS_BLOCK_CLASS);

            // If we have a radius block, and the language setting changes, we need to recreate it.
            let language = getLanguage();
            if (radiusBlock && language != lastLanguage) radiusBlock.remove();
            lastLanguage = language;

            /* We don't want API requests on every mutation. However, React reuses document
               elements, e.g. when a new map is selected from search results when a map page is
               already open. So, upon mutation, check if the map ID has changed to see if new
               API requests are worth it. */
            if (radiusBlock && mapId == lastMapId) return;
            lastMapId = mapId;

            if (! radiusBlock) {
                radiusBlock = createRadiusBlock();
                statsContainer.appendChild(radiusBlock);
                let mapInfoContainer = document.querySelector("." + cn("community-map-block_mapInfo__"));
                mapInfoContainer.style.height = "18.125rem"; // current height + block height + gap = 14.625 + 3 + 0.5
            }
            fillRadiusBlock(radiusBlock, "\u2026"); // ellipsis

            Promise.all([fetchDistanceUnit(), fetchMap(mapId)]).then(([distanceUnit, map]) => {
                if (! (distanceUnit && map)) { // We probably were rate-limited.
                    fillRadiusBlock(radiusBlock, "\u274C", "normal"); // cross mark emoji
                    return;
                }

                /* It doesn't sound like it, but maxErrorDistance is in effect faked by maps that set the 5k
                   radius manually. Thus, we can always use it to determine the 5k radius. */
                let radius = Math.log(5000/4999.5) * map.maxErrorDistance / 10; // in m
                radius = radius < 25 ? 25 : radius;

                if (distanceUnit == 'yd') {
                    radius = Math.round(radius / 0.0254); // in inches, rounded to inches
                    const yd = Math.trunc(radius / 36);
                    const ft = Math.trunc((radius - 36 * yd) / 12);
                    const in_ = radius - 36 * yd - 12 * ft;
                    fillRadiusBlock(radiusBlock, in_ > 0 ? `${yd} yd ${ft}′ ${in_}″` :
                                                  ft > 0 ? `${yd} yd ${ft}′` :
                                                           `${yd} yd`);
                } else {
                    radius = Math.round(radius * 100) / 100; // in m, rounded to cm
                    fillRadiusBlock(radiusBlock, new Intl.NumberFormat(language).format(radius) + " m");
                }
            });
        });
    });
}

new MutationObserver((mutations) => {
    if (! checkURL()) return;
    run();
}).observe(document.body, { subtree: true, childList: true });