// ==UserScript== // @name 谷歌街景助手 - 全景下载 // @description 获取精确拍摄时间 | 下载街景全景图 | 导入位置至 Map Making App | 复制短链接 // @namespace https://greasyfork.org/users/1179204 // @version 2.7.9.8 // @author KaKa // @license MIT // @tag 街景, 地图, 下载, 截图, 全景, 谷歌街景, 谷歌地图 // @include *://maps.google.com/* // @include *://*.google.*/maps/* // @exclude https://ogs.google.com // @exclude https://accounts.google.com // @exclude https://clients5.google.com // @icon https://www.svgrepo.com/show/485785/magnifier.svg // @require https://cdn.jsdelivr.net/npm/sweetalert2@11 // @require https://cdn.jsdelivr.net/npm/chinese-lunar@0.1.4/lib/chinese-lunar.min.js // @require https://cdn.jsdelivr.net/npm/browser-geo-tz@0.1.0/dist/geotz.min.js // @grant GM_xmlhttpRequest // @grant GM_setClipboard // @grant GM_addStyle // @grant GM_download // @grant GM_setValue // @grant GM_getValue // @connect vs-update-map.netlify.app // @connect cdn.jsdelivr.net // @connect google.com // ==/UserScript== (function() { const DEFAULT_CONFIG={ DATE_FORMAT: 0, TIME_FORMAT: 1, ACCURACY: 2, SEARCH_RADIUS: 30, LENGTH_UNITS: 'METERS', MAP_MAKING_API_KEY: 'PASTE_YOUR_KEY_HERE', NUMBER_OF_RECENT_MAPS: 3, NEARBY_CHECK:0, FULL_CHECK:true, UNOFFICIAL_COVERAGE: true, ROAD_NAME_LABELS_VISIBILITY: true, COVERAGE_PREFERENCE: 0, OSM_ADDRESS:false, }; let CONFIG= window.JSON.parse(GM_getValue("PANO_DETECTIVE_CONFIG", JSON.stringify(DEFAULT_CONFIG))); let pageLoaded = false; let sceneFooterObserver = null; let panoType = 2; let onFocus; let detectButton, downloadButton; let previousListener, zoomLevel; let formattedTime, capturePano; let isHidden, cleanStyle; let currentPano, LOCATION; let MAP_LIST; let previousMapId= window.JSON.parse(GM_getValue('previousMapId', null)); let previousTags = window.JSON.parse(GM_getValue('previousTags', '[]')); let preferTagKeys = window.JSON.parse(GM_getValue('preferTagKeys', '{}')); const metadataCache = new Map(); const locationQueryCache = new Map(); const typeQueryCache = new Map(); const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const full_months=['January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December'] let dateSvg=` ` let date_Svg=` ` let iconSvg=` ` let icon_Svg=` ` let saveSvg=` ` let noteSvg=` ` let settingSvg=`` const iconUrl=svgToUrl(iconSvg) const icon_Url=svgToUrl(icon_Svg) const svgUrl=svgToUrl(dateSvg) const svg_Url=svgToUrl(date_Svg) const saveUrl=svgToUrl(saveSvg) const noteUrl=svgToUrl(noteSvg) const settingUrl=svgToUrl(settingSvg) const gen2Countries = new Set(['AU', 'BR', 'CA', 'CL', 'JP', 'GB', 'IE', 'NZ', 'MX', 'RU', 'US', 'IT', 'DK', 'GR', 'RO', 'PL', 'CZ', 'CH', 'SE', 'FI', 'BE', 'LU', 'NL', 'ZA', 'SG', 'TW', 'HK', 'MO', 'MC', 'NO', 'SM', 'AD', 'IM', 'JE', 'FR', 'DE', 'ES', 'PT', 'SJ']); const gen3Dates = { 'BD': '2021-04', 'FI': '2020-09', 'IN': '2021-10', 'LK': '2021-02', 'LB': '2021-05', 'NG': '2021-06', 'US': '2019-01', 'VN':'2021-01', }; const moon_phase=['🌑','🌒','🌓','🌔','🌕','🌖','🌗','🌘'] function svgToUrl(svgText) { const svgBlob = new Blob([svgText], {type: 'image/svg+xml'}); const svgUrl = URL.createObjectURL(svgBlob); return svgUrl; } async function showSettingsPopup(){ await Swal.fire({ title: '⚙️ Config Settings', html: `
`, confirmButtonText: '💾 Save Settings', denyButtonText: '🗑️ Clear Config', showDenyButton: true, focusConfirm: false, showCloseButton:true, allowOutsideClick: true, allowEscapeKey: true, didOpen: () => { document.getElementById('swal-date').value = CONFIG.DATE_FORMAT; document.getElementById('swal-time').value = CONFIG.TIME_FORMAT; document.getElementById('swal-accuracy').value = CONFIG.ACCURACY; document.getElementById('swal-search-radius').value = CONFIG.SEARCH_RADIUS; document.getElementById('swal-units').value = CONFIG.LENGTH_UNITS; document.getElementById('swal-api').value = CONFIG.MAP_MAKING_API_KEY; document.getElementById('swal-recent').value = CONFIG.NUMBER_OF_RECENT_MAPS; document.getElementById('swal-fullcheck').value = CONFIG.FULL_CHECK?.toString(); document.getElementById('swal-nearbycheck').value = String(CONFIG.NEARBY_CHECK); document.getElementById('swal-hide-labels').value = String(CONFIG.ROAD_NAME_LABELS_VISIBILITY); document.getElementById('swal-ari').value = String(CONFIG.UNOFFICIAL_COVERAGE); document.getElementById('swal-coverage').value = CONFIG.COVERAGE_PREFERENCE; document.getElementById('swal-osm-address').value = CONFIG.OSM_ADDRESS; }, preConfirm: () => { const accuracy = parseInt(document.getElementById('swal-accuracy').value); const radius = parseInt(document.getElementById('swal-search-radius').value); const recentMaps = parseInt(document.getElementById('swal-recent').value); if (isNaN(accuracy) || accuracy <= 0 || !Number.isInteger(accuracy)) { Swal.showValidationMessage("Accuracy must be a positive integer."); return false; } if (isNaN(recentMaps) || recentMaps <= 0 || recentMaps > 10 || !Number.isInteger(recentMaps)) { Swal.showValidationMessage("Recent Maps to Show must be an integer between 1 and 10."); return false; } return { DATE_FORMAT: parseInt(document.getElementById('swal-date').value), TIME_FORMAT: parseInt(document.getElementById('swal-time').value), ACCURACY: accuracy, SEARCH_RADIUS: radius, LENGTH_UNITS: document.getElementById('swal-units').value, MAP_MAKING_API_KEY: document.getElementById('swal-api').value.trim(), NUMBER_OF_RECENT_MAPS: recentMaps, FULL_CHECK: document.getElementById('swal-fullcheck').value === 'true', NEARBY_CHECK: Number(document.getElementById('swal-nearbycheck').value), ROAD_NAME_LABELS_VISIBILITY: document.getElementById('swal-hide-labels').value === 'true', UNOFFICIAL_COVERAGE: document.getElementById('swal-ari').value === 'true', COVERAGE_PREFERENCE: Number(document.getElementById('swal-coverage').value), OSM_ADDRESS:document.getElementById('swal-osm-address').value === 'true' }; } }).then(async (result) => { if (result.isConfirmed && result.value) { GM_setValue("PANO_DETECTIVE_CONFIG", JSON.stringify(result.value)); CONFIG=result.value await Swal.fire({ title: ' ✔️ Settings saved successfully.', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" } }); } else if (result.isDenied) { GM_setValue("PANO_DETECTIVE_CONFIG", JSON.stringify(DEFAULT_CONFIG)); CONFIG = DEFAULT_CONFIG await Swal.fire({ title: '🗑️ Configuration cleared.', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" } }); } }); } function defaultState() { return { recentMaps: [] } } function loadState() { const data = GM_getValue('mwstmm_state', null) if(!data) return; const dataJson = window.JSON.parse(data); if(!data) return; Object.assign(MWSTMM_STATE, defaultState(), dataJson); saveState(); } function saveState() { GM_setValue('mwstmm_state', JSON.stringify(MWSTMM_STATE)); } const MWSTMM_STATE = defaultState(); loadState(); async function mmaFetch(url, options = {}) { const response = await fetch(new URL(url, 'https://map-making.app'), { ...options, headers: { accept: 'application/json', authorization: `API ${CONFIG.MAP_MAKING_API_KEY.trim()}`, ...options.headers } }); if (!response.ok) { let message = 'Unknown error'; try { const res = await response.json(); if (res.message) { message = res.message; } } catch { //empty } alert(`An error occurred while trying to connect to Map Making App. ${message}`); throw Object.assign(new Error(message), { response }); } return response; } async function getMaps() { const response = await mmaFetch(`/api/maps`); const maps = await response.json(); return maps; } async function importLocations(mapId, locations) { const response = await mmaFetch(`/api/maps/${mapId}/locations`, { method: 'post', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ edits: [{ action: { type: 4 }, create: locations, remove: [] }] }) }); await response.json(); } function extractParams(link) { const regex = /@(-?\d+\.\d+),(-?\d+\.\d+),.*?\/data=!3m\d+!1e\d+!3m\d+!1s([^!]+)!/; const urlObj = new URL(link); const path = urlObj.pathname; const pathRegex = /@([^,]+),([^,]+),(\d+)a,([^y]+)y,([^h]+)h,([^t]+)t/; const pathMatch = path.match(pathRegex); const match = link.match(regex); let lat, lng, panoId, a, y, h, t; if (match) { panoId = match[3]; } if (pathMatch) { lat = parseFloat(pathMatch[1]); lng = parseFloat(pathMatch[2]); a = parseFloat(pathMatch[3]); y = parseFloat(pathMatch[4]); h = parseFloat(pathMatch[5]); t = parseFloat(pathMatch[6]); } return { lat, lng, panoId, a, y, h, t }; } function buildMapHTML(m) { return `
${m.name} ADD ADDED
`; } function showLoader() { if(document.getElementById('mwstmm-loader')) return; const element = document.createElement('div'); element.id = 'mwstmm-loader'; element.className = 'mwstmm-modal'; element.innerHTML = `
LOADING...
`; document.body.appendChild(element); } function hideLoader() { const element = document.getElementById('mwstmm-loader'); if(element) element.remove(); } async function clickedMapButton() { if (CONFIG.MAP_MAKING_API_KEY === 'PASTE_YOUR_KEY_HERE') { await Swal.fire({ icon: 'warning', title: 'API Key Required', html: `To save locations to Map Making App, you must first configure your API key.

Please click the ⚙️ icon and enter your API key in the popup.

You can get your API key by creating one here.`, confirmButtonText: 'Got it!', }); return; } if(!MAP_LIST) { showLoader(); try { MAP_LIST = await getMaps(); }catch{ //empty } hideLoader(); } if(MAP_LIST) { showMapList() } } function showMapList() { if(document.getElementById('mwstmm-map-list')) return; const element = document.createElement('div'); element.id = 'mwstmm-map-list'; element.className = 'mwstmm-modal'; let recentMapsSection = ``; if(CONFIG.NUMBER_OF_RECENT_MAPS > 0 && MWSTMM_STATE.recentMaps.length > 0) { let recentMapsHTML = ''; for(const m of MWSTMM_STATE.recentMaps) { if(m.archivedAt) continue; recentMapsHTML += `
${m.name} ADD ADDED
`; } recentMapsSection = `

Recent Maps

${recentMapsHTML}

`; } const tagButtonsArr = []; const defaultTags = LOCATION.tagKeys.map((key, i) => preferTagKeys[key] ? LOCATION.tagFields[i] : null).filter(Boolean); if (LOCATION) { for (let i = 0; i < LOCATION.tagFields.length; i++) { tagButtonsArr.push(` `); } } if (previousTags.length > 0) { for (const tag of previousTags) { if (LOCATION.tagFields.includes(tag)) continue; tagButtonsArr.push(``); } } const mapsArr = MAP_LIST.filter(m => !m.archivedAt).map(buildMapHTML); element.innerHTML = `

Tags (comma separated)

${tagButtonsArr.join('')}


${recentMapsSection}

All Maps

${mapsArr.join('')}
`; const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement; const targetContainer = fullscreenElement || document.body; targetContainer.appendChild(element); element.querySelector('.dim').addEventListener('click', closeMapList); const tagInput = document.getElementById('mwstmm-map-tags'); for (const btn of element.querySelectorAll('.tag-button')) { if (preferTagKeys[btn.dataset.key]) { btn.classList.add('active'); } } const stopPropagation = e => e.stopPropagation(); tagInput.addEventListener('keyup', stopPropagation); tagInput.addEventListener('keydown', stopPropagation); tagInput.addEventListener('keypress', stopPropagation); tagInput.focus(); for(const map of element.querySelectorAll('.maps .map-add')) { map.addEventListener('click', addLocationToMap); } for (const btn of element.querySelectorAll('.tag-button')) { btn.addEventListener('click', function () { const tag = this.dataset.tag; const input = document.getElementById('mwstmm-map-tags'); let currentTags = input.value.split(',') .map(t => t.trim()) .filter(t => t.length > 0); if (this.classList.contains('active')) { currentTags = currentTags.filter(t => t !== tag); this.classList.remove('active'); } else { if (!currentTags.includes(tag)) { currentTags.push(tag); } this.classList.add('active'); } input.value = currentTags.join(', '); }); } } function closeMapList() { const element = document.getElementById('mwstmm-map-list'); if(element) element.remove(); } function addLocationToMap(e) { e.target.parentNode.classList.add('is-added'); const id = parseInt(e.target.dataset.id); previousMapId=id GM_setValue('previousMapId', JSON.stringify(previousMapId)); if(CONFIG.NUMBER_OF_RECENT_MAPS > 0) { MWSTMM_STATE.recentMaps = MWSTMM_STATE.recentMaps.filter(e => e.id !== id).slice(0, CONFIG.NUMBER_OF_RECENT_MAPS-1); for(const map of MAP_LIST) { if(map.id === id) { MWSTMM_STATE.recentMaps.unshift(map); break; } } } saveState(); const tagList = document.getElementById('mwstmm-map-tags').value.split(',').map(t => t.trim()).filter(t => t.length > 0); // Use Set for efficient deduplication const tagFieldsSet = new Set(LOCATION.tagFields); const customTags = tagList.filter(tag => !tagFieldsSet.has(tag)); const mergedSet = new Set([...customTags, ...previousTags]); const limited = [...mergedSet].slice(0, 5); GM_setValue('previousTags', JSON.stringify(limited)); for (const btn of document.querySelectorAll('#mwstmm-map-list .tag-button.active')) { if (btn.dataset.key) { preferTagKeys[btn.dataset.key] = true; } } GM_setValue('preferTagKeys', JSON.stringify(preferTagKeys)); importLocations(id, [{ id: -1, location: {lat: LOCATION.lat, lng: LOCATION.lng}, panoId: LOCATION.panoId ?? null, heading: LOCATION.heading ?? 90, pitch: LOCATION.pitch ?? 0, zoom: 0, //LOCATION.zoom ?? 0, tags: document.getElementById('mwstmm-map-tags').value.split(',').map(t => t.trim()).filter(t => t.length > 0), flags: LOCATION.panoId ? 1 : 0 }]); } function addSettingsButtonToPage() { const container = document.querySelector('.UL7Qtf'); if(!container || document.getElementById('settings-btn')) return; const element = document.createElement('div'); element.id = 'settings-btn'; element.style.backgroundImage=`url(${settingUrl})` element.setAttribute('data-text',"Settings") container.appendChild(element); element.addEventListener('click', async () => { await showSettingsPopup() }); setTimeout(() => { if(document.querySelector('.S9kvJb ')){ element.style.right='7.2rem' element.style.top='4rem' }}, 100) } function parseMeta(data) { const tags=[] const panoId = data?.[1]?.[0]?.[1]?.[1]; const lat = data?.[1]?.[0]?.[5]?.[0]?.[1]?.[0]?.[2]; const lng = data?.[1]?.[0]?.[5]?.[0]?.[1]?.[0]?.[3]; const year = data?.[1]?.[0]?.[6]?.[7]?.[0]; const month = data?.[1]?.[0]?.[6]?.[7]?.[1]; const worldsize = data?.[1]?.[0]?.[2]?.[2]; const history = data?.[1]?.[0]?.[5]?.[0]?.[8]; const links = data?.[1]?.[0]?.[5]?.[0]?.[3]?.[0] || []; const date = new Date(year, month - 1); const formattedDate = date.toLocaleString('default', { month: 'short', year: 'numeric' }); let originHeading, region, locality, road, country, altitude; try{ originHeading=data[1][0][5][0][1][2][0]; }catch(e){ originHeading=0 } try { country = data[1][0][5][0][1][4]; if (['TW', 'HK', 'MO'].includes(country)) { country = 'CN'; } } catch (e) { country = null; } try { const address = data[1][0][3][2][1][0]; const parts = address.split(',') if(parts.length > 1){ region = parts[parts.length-1].trim(); locality=parts[0].trim(); } else { region = address; locality = data[1][0][3][2][0][0]; } } catch (e) { try{ const address=data[1][0][3][2][0][0]; const parts = address.split(','); if(parts.length > 1){ region = parts[parts.length-1].trim(); locality=parts[0].trim(); } else region = address; } catch(e){ locality = null; region = null; } } try { road = data[1][0][5][0][12][0][0][0][2][0]; } catch (e) { road = null; } try{ altitude=data[1][0][5][0][1][1][0] } catch(e){ altitude=null; } const generation = String(data[1][0][4]).includes('Google')?getGeneration(worldsize[0], country, lat, date):'ari'; let camera; if (generation=='Gen4'){ if(['IN','PR', 'CY', 'MK', 'XK', 'ME', 'AL'].includes(country))camera='smallcam' else if (['NA', 'PA' , 'OM', 'QA', 'EC', 'IS', 'FO', 'CR', 'KE', 'SN', 'NG'].includes(country))camera='gen4trekker' } let isNewRoad= !history ? 'newroad' : false const tagEntries = [ ["formattedDate", formattedDate], ["yearMonth", `${year}-${month}`], ["yearMonthShort", `${String(year).slice(2,4)}-${month}`], ["year", year], ["monthShort", months[month-1]], ["monthFull", full_months[month-1]], ["country", country], ["region", region], ["locality", locality], ["road", road], ["generation", generation], ["camera", camera], ["altitude", altitude ? altitude.toFixed(2)+"m" : null], ["isNewRoad", isNewRoad] ]; const tagFields = []; const tagKeys = []; for (const [key, value] of tagEntries) { if (value) { tagFields.push(value); tagKeys.push(key); } } return { lat, lng, altitude, panoId, year, month, country, region, locality, road, worldsize, generation, links, history, originHeading, pitch: 0, zoom: 0, tags, tagKeys, tagFields } } function getGeneration(height, country, lat, date, format) { if (height === 8192) return format ? 4 : 'Gen4'; else if (height === 6656) { const dateStr = date.toISOString().slice(0, 7); if(dateStr >= '2022-01') return format ? 5 : 'BadCam' if (dateStr >= gen3Dates[country]) { if(country!='US') return format ? 5 : 'BadCam' if(country === 'US' && lat > 52) return format ? 5 : 'BadCam' } if (gen2Countries.has(country) && dateStr <= '2011-11') { return dateStr >= '2010-09' ? (format ? 25 :'Gen2/3') : (format ? 2 : 'Gen2'); } return format ? 3: 'Gen3'; } else if (height === 1664) return format ? 1 : 'Gen1'; return 'ari'; } function getGenerationIcon(gen){ switch(gen){ case 'Gen4': if(['IN','PR', 'CY'].includes(LOCATION.country)) return 'https://cdn.discordapp.com/emojis/1191152665154039928.webp?size=100'; else if (['NA', 'PA' , 'OM', 'QA', 'EC', 'IS', 'FO', 'CR', 'KE', 'SN', 'NG'].includes(LOCATION.country)) return 'https://cdn.discordapp.com/emojis/1245723839380455545.webp?size=100'; return 'https://cdn.discordapp.com/emojis/776224006256197632.webp?size=100'; case 'BadCam': return 'https://cdn.discordapp.com/emojis/1143737630178160660.webp?size=100' case 'Gen2': return 'https://cdn.discordapp.com/emojis/776223985796775986.webp?size=100'; case 'Gen1': return 'https://cdn.discordapp.com/emojis/776223975096451102.webp?size=100'; default: return 'https://cdn.discordapp.com/emojis/776223996224077844.webp?size=100'; } } function haversine(lat1, lng1, lat2, lng2) { const R = 6371; const toRad = Math.PI / 180; const φ1 = lat1 * toRad; const φ2 = lat2 * toRad; const Δφ = (lat2 - lat1) * toRad; const Δλ = (lng2 - lng1) * toRad; const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; } async function getLOCATION(result){ if(!result || !result.panoId) return; const metaData = await fetchGooglePanorama('GetMetadata', result.panoId); console.log(metaData) if(metaData && metaData[1]?.[0]?.length == 22 || metaData[1]?.[0]?.length == 20) { LOCATION = parseMeta(metaData); return metaData; } } async function fetchGooglePanorama(mode, key, range, radius) { if (metadataCache.has(key)) { return metadataCache.get(key); } try { const url = `https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/${mode}`; let payload = createPayload(mode, key,range, radius); const response = await fetch(url, { method: "POST", headers: { "accept": "application/json", "content-type": "application/json+protobuf", "x-user-agent": "grpc-web-javascript/0.1", "x-client-data": "CKmdygEIlKHLAQiFoM0BCOXHlDAYvanKARicwc8B", }, body: payload, mode: "cors", credentials: "omit" }); if (!response.ok) { console.error(`HTTP error! status: ${response.status}`); return response } else { const data = await response.json(); if (mode === 'GetMetadata') { metadataCache.set(key, data); } return data; } } catch (error) { console.error(`Error fetching google panorama: ${error.message}`); } } function fetchGooglePanoramaSync(mode, key, range, radius) { try { const url =`https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/${mode}`; const payload = createPayload(mode, key, range, radius); const xhr = new XMLHttpRequest(); xhr.open("POST", url, false); xhr.setRequestHeader("accept", "application/json"); xhr.setRequestHeader("content-type", "application/json+protobuf"); xhr.setRequestHeader("x-user-agent", "grpc-web-javascript/0.1"); xhr.setRequestHeader("x-client-data", "CKmdygEIlKHLAQiFoM0BCOXHlDAYvanKARicwc8B"); xhr.send(payload); if (xhr.status !== 200) { console.error("HTTP error! status:", xhr.status); return null; } return xhr.responseText; } catch (error) { console.error("Error fetching google panorama:", error); return null; } } function createPayload(mode,key,range,radius) { var payload; if (mode.startsWith('G')) { const panoField = Array.isArray(key) ? key.map(id => [[panoType, id]]) : [[[panoType, key]]]; payload = [ ["apiv3", null, null, null, "US", null, null, null, null, null, [[0]]], ["en", "US"], panoField, [[1, 2, 3, 4, 8, 6]] ]; } else { payload=[ ["apiv3"], [[null,null,key.lat,key.lng],radius],[[null,null,null,null,null,null,null,null,null,null,range],null,null,null,null,null,null,null,[2],null,[[[panoType,true,2]]]], [[1,2,3,4,8,6],[],null,null,[],[]] ]; } return JSON.stringify(payload); } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function requestWithRetry(fn) { while (true) { try { const response = await fn(); if (response?.status === 501) { await sleep( 200 + Math.random() * 200 ); continue; } return response; } catch (error) { if (error?.status === 501) { await sleep( 200 + Math.random() * 200 ); continue; } throw error; } } } async function binarySearch( c, start, end, accuracy = CONFIG.ACCURACY, radius = CONFIG.SEARCH_RADIUS ) { let response; while ((end - start) > accuracy) { const mid = Math.round((start + end) / 2); response = await fetchGooglePanorama("SingleImageSearch", c, [start, mid], radius); if (response && response.length > 1) { end = mid; } else { start = mid; } } return Math.round((start + end) / 2); } async function downloadPanoramaImage(panoId, fileName,w,h) { return new Promise(async (resolve, reject) => { try { const imageUrl= `https://streetviewpixels-pa.googleapis.com/v1/tile?cb_client=apiv3&panoid=${panoId}&output=tile&zoom=${zoomLevel}&nbt=0&fover=2`; const tileWidth = 512; const tileHeight = 512; const zoomTiles=[2,4,8,16,32] let tilesPerRow,tilesPerColumn if(panoType==2){ tilesPerRow = Math.min(Math.ceil(w / tileWidth),zoomTiles[zoomLevel-1]); tilesPerColumn = Math.min(Math.ceil(h / tileHeight),zoomTiles[zoomLevel-1]/2);} else{ tilesPerRow=Math.ceil(w / tileWidth) tilesPerColumn = Math.ceil(h/ tileHeight); } const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width =tilesPerRow * tileWidth; canvas.height = tilesPerColumn * tileHeight; if (w === 13312) { const sizeMap = { 4: [6656, 3328], 3: [3328, 1664], 2: [1664, 832], 1: [832, 416] }; if (sizeMap[zoomLevel]) { [canvas.width, canvas.height] = sizeMap[zoomLevel]; } } const loadTile = (x, y) => { return new Promise(async (resolveTile) => { let tile; let tileUrl = `${imageUrl}&x=${x}&y=${y}`; if(panoType==10)tileUrl=`https://lh3.ggpht.com/jsapi2/a/b/c/x${x}-y${y}-z${zoomLevel}/${panoId}` try { tile = await loadImage(tileUrl); ctx.drawImage(tile, x * tileWidth, y * tileHeight, tileWidth, tileHeight); resolveTile(); } catch (error) { console.error(`Error loading tile at ${x},${y}:`, error); resolveTile(); } }); }; let tilePromises = []; for (let y = 0; y < tilesPerColumn; y++) { for (let x = 0; x < tilesPerRow; x++) { tilePromises.push(loadTile(x, y)); } } await Promise.all(tilePromises); canvas.toBlob(blob => { const url = URL.createObjectURL(blob); GM_download({ url, name: fileName, saveAs: true, onload: () => URL.revokeObjectURL(url) }); }, 'image/jpeg'); Swal.fire({ title: 'Download Completed ✔️', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" }}); } catch (error) { Swal.fire({ title: 'Error Downloading ❌', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" }}) reject(error); } }); } async function getElevation(lat, lng) { const url = `https://api.open-meteo.com/v1/elevation?latitude=${lat}&longitude=${lng}`; try { const response = await fetch(url); if (!response.ok) { console.error(`HTTP error! Status: ${response.status}`); return null } const data = await response.json(); const altitude = data.elevation; if(altitude) return altitude[0] else return null } catch (error) { console.error('Error fetching elevation data:', error); return null } } async function loadImage(url) { return new Promise((resolve, reject) => { const img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = () => resolve(img); img.onerror = () => reject(new Error(`Failed to load image from ${url}`)); img.src = url; }); } function monthToTimestamp(m) { const [year, month] = m const startDate =Math.round( new Date(year, month-1,0).getTime()/1000); const endDate =Math.round(new Date(year, month, 2).getTime()/1000) return { startDate, endDate }; } async function getLocal(coord, timestamp) { const systemTimezoneOffset = -new Date().getTimezoneOffset() * 60; try { var offset_hours, offset const timezone=await GeoTZ.find(coord[0],coord[1]) try{ offset = await GeoTZ.toOffset(timezone);} catch(error){ offset = await GeoTZ.toOffset(timezone[0]);} if(offset){ offset_hours=parseInt(offset/60) } else if (offset===0) offset_hours=0 const offsetDiff = systemTimezoneOffset -offset_hours*3600; const convertedTimestamp = timestamp -offsetDiff; return convertedTimestamp; } catch (e) { try { const [lat, lng] = coord; const url = `https://api.wheretheiss.at/v1/coordinates/${lat},${lng}`; const response = await fetch(url); if (!response.ok) { throw new Error("Request failed: " + response.statusText); } const data = await response.json(); const targetTimezoneOffset = data.offset * 3600; const offsetDiff = systemTimezoneOffset - targetTimezoneOffset; const convertedTimestamp = Math.round(timestamp - offsetDiff); return convertedTimestamp; } catch (e){ console.error('Failed to get timezone data'+e) } } } function getMoonPhaseIcon(dayOfMonth) { const cycleDays = 29.53; const phaseIndex = Math.floor((dayOfMonth % cycleDays) / (cycleDays / moon_phase.length)); return moon_phase[phaseIndex]; } function formatTimestamp(timestamp) { var date_text,time_text const date = new Date(timestamp * 1000); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); if (CONFIG.DATE_FORMAT===2) date_text=`${year}/${month}/${day}` else if (CONFIG.DATE_FORMAT===3) date_text=`${day}/${month}/${year}` else if (CONFIG.DATE_FORMAT===4) date_text=`${month}/${day}/${year}` else if (CONFIG.DATE_FORMAT===5) date_text=`${months[parseInt(month-1)]} ${parseInt(day)}, ${year}` else if (CONFIG.DATE_FORMAT===6) date_text=`${parseInt(day)} ${months[parseInt(month-1)]}, ${year}` else if (CONFIG.DATE_FORMAT===7) { const lunarDate=chineseLunar.solarToLunar(date) date_text = `${year}-${month}-${day} ${chineseLunar.format(lunarDate, 'MD')} ${getMoonPhaseIcon(lunarDate.day)}`;} else date_text=`${year}-${month}-${day}` ; if(CONFIG.TIME_FORMAT===1) time_text=`${hours}:${minutes}:${seconds}` else{ const period = parseInt(hours) >= 12 ? 'pm' : 'am'; var _hours = parseInt(hours) % 12 || 12; _hours = String(_hours).padStart(2, '0'); time_text= `${_hours}:${minutes}:${seconds} ${period}`; } if(!CONFIG.DATE_FORMAT)return date.toLocaleString().replace('T', ' '); else return `${date_text} ${time_text}`; } function formatLatLng(lat, lng) { const latDirection = lat >= 0 ? 'N' : 'S'; const latAbs = Math.abs(lat).toFixed(4); const latStr = `${latAbs}°${latDirection}`; const lngDirection = lng >= 0 ? 'E' : 'W'; const lngAbs = Math.abs(lng).toFixed(4); const lngStr = `${lngAbs}°${lngDirection}`; return `${latStr}, ${lngStr}`; } function formatDistance(meters) { if (CONFIG.LENGTH_UNITS === 'Imperial') { const miles = meters * 0.000621371; return `${Math.round(miles)} miles`; } else { return `${Math.round(meters*0.001)} km`; } } function getButtonPosition(symbol, spotlight) { if (!symbol || !spotlight) return null; const rectSymbol = symbol.getBoundingClientRect(); const rectSpotlight = spotlight.getBoundingClientRect(); return rectSpotlight.top ? { top: rectSymbol.top, left: rectSymbol.left } : null; } function createButton(id) { const button = document.createElement("button"); button.id = id; return button; } function setupButton(button, backgroundUrl, position) { Object.assign(button.style, { backgroundImage: `url(${backgroundUrl})`, backgroundSize: "cover", backgroundPosition: "center", display: "block", width: "24px", height: "24px", fontSize: "12px", borderRadius: "10px", cursor: "pointer", backgroundColor: "transparent", ...(position && { position: "fixed", top: `${position.top + 40}px`, left: `${position.left - 25}px` }), }); } function addButtons(symbol, position) { if (!detectButton) { detectButton = createButton("detect-button"); addButtonHoverEffect(detectButton, svg_Url, svgUrl); detectButton.addEventListener("click",async function() { const date_selectors = [ 'span.lchoPb', 'span.mqX5ad', 'div.mqX5ad', 'div.lchoPb', 'div.W0fu2b' ]; const dateSpan = date_selectors .map(selector => document.querySelector(selector)) .find(el => el !== null); if (dateSpan){ dateSpan.innerHTML='loading...' } try { if (!LOCATION.year || !LOCATION.month) { console.error('Failed to get metadata'); return; } capturePano=LOCATION.panoId; const timeRange = monthToTimestamp([LOCATION.year, LOCATION.month]); if (!timeRange) { console.error('Failed to convert panoDate to timestamp'); return; } const captureTime = await binarySearch({lat: LOCATION.lat, lng: LOCATION.lng}, timeRange.startDate, timeRange.endDate); if (!captureTime) { console.error('Failed to get capture time'); return; } const localTime=await getLocal([LOCATION.lat,LOCATION.lng],captureTime) if(!localTime){ console.error('Failed to get exact time'); } formattedTime=formatTimestamp(localTime) if(dateSpan){ dateSpan.textContent = formattedTime; } } catch (error) { console.error(error); } }) } if (!downloadButton){ downloadButton = createButton("download-button"); addButtonHoverEffect(downloadButton, icon_Url, iconUrl); downloadButton.addEventListener("click",async function(){ const { value: zoom, dismiss: inputDismiss } = await Swal.fire({ title: 'Image Quality', html: '', icon: 'question', showCancelButton: true, showCloseButton: true, allowOutsideClick: false, backdrop:null, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes', cancelButtonText: 'Cancel', preConfirm: () => { return document.getElementById('zoom-select').value; } }); if (zoom){ zoomLevel=parseInt(zoom) if(LOCATION && LOCATION.worldsize){ const gpsTag=formatLatLng(LOCATION.lat,LOCATION.lng) var timeTag='' if(LOCATION.panoId===capturePano&&formattedTime) timeTag=formattedTime else{ if(LOCATION.year) timeTag=`${LOCATION.year}-${LOCATION.month}`} const fileName = `${gpsTag}(${timeTag}).jpg`; Swal.fire({ title: 'Downloading...', showConfirmButton: false, allowOutsideClick:true, backdrop:null, allowEscapeKey: false, didOpen: () => { Swal.showLoading(); }, customClass: { popup: "swal-small-popup" } }); await downloadPanoramaImage( LOCATION.panoId, fileName, LOCATION.worldsize[1], LOCATION.worldsize[0] ); } } }) } if (symbol&&symbol.parentNode&&!symbol.parentNode.contains(detectButton))symbol.parentNode.appendChild(detectButton); if (symbol&&symbol.parentNode&&!symbol.parentNode.contains(downloadButton))symbol.parentNode.appendChild(downloadButton); } function checkPosition() { const symbol = document.querySelector("[jsaction='titlecard.settings']"); const spotlight = document.querySelector("[jsaction='titlecard.spotlight']"); const position = getButtonPosition(symbol, spotlight); if(symbol){ if(!position){ detectButton.style=null downloadButton.style=null } else{ detectButton.style.marginTop = '1px'; if(position.left&&position.top) downloadButton.style.marginLeft = '26px'; else downloadButton.style.marginLeft='1px' } } if (!document.getElementById("detect-button") && !document.getElementById("download-button")) { addButtons(symbol, position); } setupButton(detectButton, svgUrl, position); setupButton(downloadButton, iconUrl, position); } function observePositionChanges() { const observer = new MutationObserver(() => checkPosition()); observer.observe(document.body, { childList: true, subtree: true }); } async function updateAltitudeNGeneration(){ const logo = document.querySelector('.hz7Obe'); const logoSpan = document.querySelector('span.OVC7id'); if(LOCATION.generation && logo && LOCATION.generation != 'ari') logo.style.backgroundImage=`url(${getGenerationIcon(LOCATION.generation)})`; if(!LOCATION.altitude) LOCATION.altitude = await getElevation(LOCATION.lat,LOCATION.lng); if (LOCATION.altitude != null && logoSpan) { let displayAltitude = LOCATION.altitude; let altUnit = 'm'; if (CONFIG.LENGTH_UNITS === 'Imperial') { displayAltitude = LOCATION.altitude * 3.28084; altUnit = 'ft'; } const altIcon = displayAltitude > 50 ? "⛰️" : "🌊"; const text = ` ${altIcon} ${Math.round(displayAltitude * 100) / 100}${altUnit}`; logoSpan.textContent = text; } } async function addCustomButton() { const symbol = document.querySelector("[jsaction='titlecard.settings']"); const spotlight = document.querySelector("[jsaction='titlecard.spotlight']"); const position = getButtonPosition(symbol, spotlight); if (!symbol || !spotlight) return; addButtons(symbol, position); observePositionChanges(); } function drawSegmentedLine(ctx, x1, y1, x2, y2, alpha) { ctx.setLineDash([10, 5]); const midX1 = x1 + (x2 - x1) * 0.49; const midY1 = y1 + (y2 - y1) * 0.49; const midX2 = x1 + (x2 - x1) * 0.51; const midY2 = y1 + (y2 - y1) * 0.51; ctx.lineWidth = 1.5; ctx.setLineDash([10, 5]); ctx.globalAlpha = alpha; ctx.strokeStyle = "black"; ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(midX1, midY1); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1.0; ctx.strokeStyle = "red"; ctx.lineWidth = 2.5; ctx.beginPath(); ctx.moveTo(midX1, midY1); ctx.lineTo(midX2, midY2); ctx.stroke(); ctx.lineWidth = 1.5; ctx.setLineDash([10, 5]); ctx.globalAlpha = alpha; ctx.strokeStyle = "black"; ctx.beginPath(); ctx.moveTo(midX2, midY2); ctx.lineTo(x2, y2); ctx.stroke(); ctx.globalAlpha = 1.0; } async function getShortUrl() { const url = 'https://www.google.com/maps/rpc/shorturl'; const result=extractParams(window.location.href) if(!result||!result.panoId){ Swal.fire({ title: 'Error Generating ❌', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" }}) return } const pb = `!1shttps://www.google.com/maps/@${result.lat},${result.lng},${result.a}a,${result.y}y,${result.h}h,${result.t}t/data=*213m5*211e1*213m3*211s${result.panoId}*212e0*216shttps%3A%2F%2Fstreetviewpixels-pa.googleapis.com%2Fv1%2Fthumbnail%3Fpanoid%3D${result.panoId}%26cb_client%3Dmaps_sv.share%26w%3D900%26h%3D600%26yaw%3D${result.h}%26pitch%3D${(result.t)-90}%26thumbfov%3D100*217i16384*218i8192?coh=205410&entry=tts!2m1!7e81!6b1`; const params = new URLSearchParams({ authuser: '0', hl: 'en', gl: 'us', pb: pb }).toString(); return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url: `${url}?${params}`, onload: function (response) { if (response.status >= 200 && response.status < 300) { try { const text = response.responseText; const match = text.match(/"([^"]+)"/); if (match && match[1]) { resolve(match[1]); } else { reject('No URL found.'); } } catch (error) { reject('Failed to parse response: ' + error); } } else { reject('Request failed with status: ' + response.status); } }, onerror: function (error) { reject('Request error: ' + error); } }); }); } function addButtonHoverEffect(button, hoverImageUrl, defaultImageUrl) { button.addEventListener("mouseenter", function(event) { button.style.backgroundImage = `url(${hoverImageUrl})`; }); button.addEventListener("mouseleave", function(event) { button.style.backgroundImage = `url(${defaultImageUrl})`; }); } async function getCountryName(code) { return new Promise((resolve) => { GM_xmlhttpRequest({ method: "GET", url: "https://cdn.jsdelivr.net/gh/umpirsky/country-list/data/en_US/country.json", onload: function (res) { try { const data = window.JSON.parse(res.responseText); resolve(data[code.toUpperCase()] || "Unknown"); } catch (e) { resolve("Unknown"); } }, onerror: function () { resolve("Unknown"); } }); }); } async function getAddressFromOSM(lat, lng) { try { const url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=en`; const response = await fetch(url); if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`); const data = await response.json(); return data.address; } catch (error) { console.error("Error fetching address from OSM:", error); return "Unknown"; } } function getLocationKey({ lat, lng, year, month }, radius) { return `${lat}_${lng}_${radius}_${year}_${month}`; } function getTypeKey({ country, region, year, month }) { return `${country}_${region}_${year}_${month}`; } async function queryByLocation() { const { lat, lng, year, month } = LOCATION; let radius = CONFIG.NEARBY_CHECK ? Number(CONFIG.NEARBY_CHECK) * 1000 : 10000; const queryKey = getLocationKey(LOCATION, radius); if (locationQueryCache.has(queryKey)) { return locationQueryCache.get(queryKey); } const params = new URLSearchParams({ lat, lng, radius, year, month, count:1 }).toString(); const url = `https://vs-update-map.netlify.app/.netlify/functions/queryByLocation?${params}`; const response = await new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: "GET", url, responseType: "json", onload: res => { try { const json = typeof res.response === "object" ? res.response : window.JSON.parse(res.response); if (json.error) { reject(new Error("Query failed: API returned error")); } else { locationQueryCache.set(queryKey, json.data); // 可以是 null resolve(json.data); } } catch (e) { reject(new Error("Failed to parse response JSON")); } }, onerror: err => reject(new Error("Network error or CORS issue")) }); }); return response; } async function checkUpdateTypes() { const { country, region, year, month, generation } = LOCATION; const channel_id=generation==='BadCam'?'1231106542351421495':'905824309963014195' const queryKey = `${country}_${region}_${year}_${month}`; if (typeQueryCache.has(queryKey)) { return typeQueryCache.get(queryKey); } const params = new URLSearchParams({ country, region, year, month, channel_id }).toString(); const url = `https://vs-update-map.netlify.app/.netlify/functions/checkUpdateType?${params}`; const response = await new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: "GET", url, responseType: "json", onload: res => { try { const data = typeof res.response === 'object' ? res.response : window.JSON.parse(res.response); typeQueryCache.set(queryKey, data); resolve(data); const json = typeof res.response === 'object' ? res.response : window.JSON.parse(res.response); } catch (e) { reject(new Error("Failed to parse response JSON")); } }, onerror: err => reject(new Error("Network error or CORS issue")) }); }); return response; } async function generateUpdateReportText() { let genupdate; let countryName; if(!LOCATION) return; try{ if (LOCATION.generation === 'ari'||!LOCATION.country||!LOCATION.region) { try { const address = await getAddressFromOSM(LOCATION.lat, LOCATION.lng); if (address) { LOCATION.country = address.country_code || LOCATION.country; LOCATION.countryName = address.country || LOCATION.countryName; LOCATION.region = LOCATION.region||address.state || address.region || address.province || address.county; LOCATION.locality = LOCATION.locality || address.city || address.city_district || address.town; LOCATION.road = address.road || LOCATION.road; countryName = LOCATION.countryName; } } catch (error) { console.error("Error fetching address:", error); } } if (LOCATION.history && LOCATION.links) { try { const dates = LOCATION.history.map(pano => [pano[1][0], pano[0]]).sort((a, b) => b[0] - a[0]); if (dates.length > 0) { const metaData = await fetchGooglePanorama('GetMetadata', LOCATION.links[dates[0][1]][0][1]); var generation = parseMeta(metaData).generation; if(generation=='BadCam')generation='ari' genupdate = generation === 'Gen4' ? null : `:${generation.toLowerCase()}update:`; } } catch (error) { console.error("Error fetching metadata:", error); } } const [currentLink, typeupdate, nearbyUpdate,fetchedCountryName, osm_address] = await Promise.all([ getShortUrl(), CONFIG.FULL_CHECK?checkUpdateTypes():null, CONFIG.NEARBY_CHECK?queryByLocation():null, LOCATION.generation !== 'ari' ? getCountryName(LOCATION.country || 'Unknown') : Promise.resolve(countryName), CONFIG.OSM_ADDRESS ?getAddressFromOSM(LOCATION.lat, LOCATION.lng) : null, ]); if( CONFIG.OSM_ADDRESS && osm_address) { if(!LOCATION.region) LOCATION.region = osm_address.state || osm_address.region || osm_address.province || osm_address.territory || osm_address.county; if(!LOCATION.locality) LOCATION.locality = osm_address.city || osm_address.city_district || osm_address.town; if(!LOCATION.road) LOCATION.road = osm_address.road || osm_address.street; } let position_word if(LOCATION.locality){ if(LOCATION.road){ if(LOCATION.road==LOCATION.locality) position_word='on' else position_word='in' } else position_word='in' } else{ if(LOCATION.road){ position_word='on' } else position_word='in' } const activeTypes = [ typeupdate?.newyear && ':newyear:', typeupdate?.newcountry && ':newcountry:', typeupdate?.newregion && ':newregion:' ].filter(Boolean) const emojiMap = { ':newyear:': 'https://cdn.discordapp.com/emojis/1270086438054002699.webp', ':newcountry:': 'https://cdn.discordapp.com/emojis/972878615408676946.webp', ':newregion:': 'https://cdn.discordapp.com/emojis/972878598073634816.webp' }; const reportParts = [ `:flag_${LOCATION.country ? LOCATION.country.toLowerCase() : ''}:`, ...activeTypes, !LOCATION.history ? ':newroad:' : '', genupdate || '', (LOCATION.generation=='Gen4' && (['IN','PR', 'CY', 'MK', 'XK', 'ME', 'AL'].includes(LOCATION.country)))? ':smallcam:': '', `${full_months[LOCATION.month - 1]} ${LOCATION.year}`, `${position_word} ${LOCATION.locality || LOCATION.road || ''}${(LOCATION.locality || LOCATION.road) ? ', ' : ''}${LOCATION.region}, ${fetchedCountryName}`, currentLink || `https://www.google.com/maps/@?api=1&map_action=pano&pano=${LOCATION.panoId}` ].filter(Boolean); const reportText = reportParts.join(' '); GM_setClipboard(reportText, 'text'); const emojiHtml = activeTypes.map(type => `` ).join(''); const discordLink =nearbyUpdate?`https://discord.com/channels/747030604897452130/${nearbyUpdate.channel_id}/${nearbyUpdate.message_id}`:null const mapsLink =nearbyUpdate?`https://www.google.com/maps/@?api=1&map_action=pano&pano=${nearbyUpdate.panoId}`:null Swal.fire({ title: `Copy Succeeded${nearbyUpdate?` (Nearby update report found ${formatDistance(nearbyUpdate.distance)} away) `:' '}✔️`, html:nearbyUpdate?`
${discordLink ? `✉️ Discord Message` : ''} ${mapsLink ? ` 📍 Location` : ''}
` :(activeTypes.length>0?`
${emojiHtml}
`:null), timer: nearbyUpdate?10000:5000, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: nearbyUpdate?"swal-info-popup":"swal-small-popup" } }); } catch(e){ console.error('Error generating update report text: '+e) Swal.fire({ title: 'Error Generating ❌', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" }}) } } function addUploadButtonToPage() { const container = document.querySelector('.UL7Qtf'); if(!container || document.getElementById('mwstmm-main')) return; const element = document.createElement('div'); element.id = 'mwstmm-main'; element.style.backgroundImage=`url(${saveUrl})` element.setAttribute('data-text',"Save to MapMaking") element.innerHTML = `
`; container.appendChild(element); setTimeout(() => { if(document.querySelector('.S9kvJb ')){ element.style.right='0.85rem' element.style.top='4rem' }}, 100) element.addEventListener('click', async () => { clickedMapButton(); }); } function addNoteButtonToPage() { const container = document.querySelector('.UL7Qtf'); if(!container || document.getElementById('note-btn')) return; const element = document.createElement('div'); element.id = 'note-btn'; element.style.backgroundImage=`url(${noteUrl})` element.setAttribute('data-text',"Generate update report") container.appendChild(element); element.addEventListener('click', async () => { await generateUpdateReportText() }); setTimeout(() => { if(document.querySelector('.S9kvJb ')){ element.style.right='4rem' element.style.top='4rem' }}, 100) } function toggleElementHidden() { if (!isHidden) { cleanStyle = GM_addStyle(` #omnibox-container, #settings-btn, #note-btn, #watermark, #image-header, #mwstmm-main, .Hk4XGb, .AbwhFc, .tGgADf, .e9Chtd, .widget-image-header-close, .widget-image-header-scrim, .app-viewcard-strip, .scene-footer, .content-container, #titlecard, #pane { display: none !important; } `); isHidden = true; } else { cleanStyle.remove(); isHidden = false; } } function waitForElement(selector, callback) { const el = document.querySelector(selector); if (el) { callback(el); return; } const observer = new MutationObserver(() => { const el = document.querySelector(selector); if (el) { observer.disconnect(); callback(el); } }); observer.observe(document.documentElement, { childList: true, subtree: true, }); } const matchGen = (gen, pref) => { if (pref === 25) return gen === 2 || gen === 3 || gen === 25; if (pref === 6) return gen !== 1 && gen !== 5; return gen === pref; }; const origParse = unsafeWindow.JSON.parse; unsafeWindow.JSON.parse = function(text, reviver) { const obj = origParse(text, reviver); try { if (Array.isArray(obj) && obj.length==2 && obj[1]?.[0]?.length == 20 &&(isHidden || !CONFIG.ROAD_NAME_LABELS_VISIBILITY)) { //obj[1][0][3][2][0] = null; let roadLabel = obj[1][0][5][0][12]; if(roadLabel){ roadLabel.forEach(el => { el[0][0][2] = null; }); } /*if (CONFIG.COVERAGE_PREFERENCE != 0 ){ const panoEntries = obj[1][0][5][0][8]; const panoMap = obj[1][0][5][0][3][0]; const panoIds = panoEntries.map(e => panoMap?.[e[0]]?.[0]?.[0] != 10 && panoMap?.[e[0]]?.[0]?.[1]); if(panoIds.includes(LOCATION.panoId)) return obj; if(panoIds.length < 1) return obj; const year = obj[1][0][6][7][0]; const month = obj[1][0][6][7][1]; const date = new Date(year, month - 1); const rootGen = getGeneration(obj[1][0][2][2][0], obj[1][0][5][0][1][4], obj[1][0][5][0][1][0][2], date, true) if (CONFIG.COVERAGE_PREFERENCE != 6 && rootGen === CONFIG.COVERAGE_PREFERENCE) return obj; else if(CONFIG.COVERAGE_PREFERENCE == 6 && rootGen!= 5 && rootGen!= 1) return obj; const metas = origParse(fetchGooglePanoramaSync('GetMetadata', panoIds)); for (const meta of metas[1]) { const year = meta?.[6]?.[7]?.[0]; const month = meta?.[6]?.[7]?.[1]; const date = new Date(year, month - 1); const gen = getGeneration( meta?.[2]?.[2]?.[0], meta?.[5]?.[0]?.[1]?.[4], meta?.[5]?.[0]?.[1]?.[0]?.[2], date, true ); if (matchGen(gen, CONFIG.COVERAGE_PREFERENCE)) { obj[1][0][1][1] = meta[1][1]; obj[1][0][2][2] = meta[2][2]; break; } } }*/ } else if (Array.isArray(obj) && obj.length === 11 && obj[0]?.length > 1 && CONFIG.COVERAGE_PREFERENCE!= 0) { const rootPanoId = obj[0][0][0]; if (!rootPanoId || rootPanoId?.startsWith('CIHM0')) return obj; const metadata = origParse(fetchGooglePanoramaSync('GetMetadata', rootPanoId)); if (!metadata || metadata.length < 2) return obj; const year = metadata[1][0][6][7][0]; const month = metadata[1][0][6][7][1]; const date = new Date(year, month - 1); const rootGen = getGeneration(metadata[1][0][2][2][0], metadata[1][0][5][0][1][4], metadata[1][0][5][0][1][0][2], date, true) if (CONFIG.COVERAGE_PREFERENCE != 6 && rootGen === CONFIG.COVERAGE_PREFERENCE) return obj; else if(CONFIG.COVERAGE_PREFERENCE == 6 && rootGen!= 5 && rootGen!= 1) return obj; const panoEntries = metadata[1][0][5][0][8]; const panoMap = metadata[1][0][5][0][3][0]; const panoIds = panoEntries.map(e => panoMap?.[e[0]]?.[0]?.[0] != 10 && panoMap?.[e[0]]?.[0]?.[1]); if(panoIds.length < 1) return obj; const metas = origParse(fetchGooglePanoramaSync('GetMetadata', panoIds)); for (const meta of metas[1]) { const year = meta?.[6]?.[7]?.[0]; const month = meta?.[6]?.[7]?.[1]; const date = new Date(year, month - 1); const gen = getGeneration(meta?.[2]?.[2]?.[0], meta?.[5]?.[0]?.[1]?.[4], meta?.[5]?.[0]?.[1]?.[0]?.[2], date, true); if (matchGen(gen, CONFIG.COVERAGE_PREFERENCE)) { const panoId = meta?.[1]?.[1]; obj[0][0][0] = panoId; obj[0][0][21][1] = panoId; break; } } } } catch(e) { } finally{ return obj; } }; const origOpen = XMLHttpRequest.prototype.open; const origSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.open = function(method, url, async, user, pass) { this._url = url; return origOpen.apply(this, arguments); }; XMLHttpRequest.prototype.send = function(body) { if (this._url && this._url.includes("batchexecute?rpcids=hspqX") && !CONFIG.UNOFFICIAL_COVERAGE) { if (typeof body === "string" && body.includes("f.req")) { let params = body.split("&").map(kv => kv.split("=")); for (let i = 0; i < params.length; i++) { if (params[i][0] === "f.req") { let raw = decodeURIComponent(params[i][1]); let outer = window.JSON.parse(raw); let inner = window.JSON.parse(outer[0][0][1]); inner[4][6][0][4] = [2, 0, 3]; inner[4][6][0][5] = [2, 1, 2]; inner[4][6][0][6] = [2, 0, 4]; outer[0][0][1] = JSON.stringify(inner); params[i][1] = encodeURIComponent(JSON.stringify(outer)); } } let newBody = params.map(kv => kv.join("=")).join("&"); return origSend.call(this, newBody); } } return origSend.apply(this, arguments); }; function onPageLoad() { if (pageLoaded) return; pageLoaded = true; waitForElement("[role='contentinfo']", (sceneFooter) => { document.addEventListener("keydown", onKeyDown, true); if (sceneFooterObserver) { sceneFooterObserver.disconnect(); } sceneFooterObserver = new MutationObserver(() => { const navigationDiv = document.querySelector("[role='navigation']"); if (navigationDiv) { addCustomButton(); addUploadButtonToPage(); addNoteButtonToPage(); addSettingsButtonToPage(); } else { document.getElementById('mwstmm-main')?.remove(); document.getElementById('note-btn')?.remove(); document.getElementById('settings-btn')?.remove(); } }); sceneFooterObserver.observe(sceneFooter, { childList: true, subtree: true, attributes: true, }); }); } if (!pageLoaded) { window.addEventListener('load', onPageLoad); setInterval(async () => { const result = extractParams(window.location.href); if (result && result.panoId) { if(!document.getElementById('note-btn')) return; if( currentPano !== result.panoId){ const provider = document.querySelector('[jsaction^="titlecard.attributionClick"]')?.href; panoType = provider.slice(29).startsWith('v') ? 2: 10; currentPano = result.panoId; await getLOCATION(result); if(LOCATION && LOCATION)updateAltitudeNGeneration(); } else { if(currentPano && LOCATION){ if(result.h)LOCATION.heading=result.h; if(result.t)LOCATION.pitch=parseInt(result.t)-90; if(result.y)LOCATION.zoom = Math.log2(180 / result.y); } } } }, 200); } const focus_canvas = document.createElement("canvas"); focus_canvas.style.zIndex=0 focus_canvas.style.position = "fixed"; focus_canvas.style.top = "0"; focus_canvas.style.left = "0"; focus_canvas.style.width = "100vw"; focus_canvas.style.height = "100vh"; focus_canvas.style.pointerEvents = "none"; focus_canvas.width = window.innerWidth; focus_canvas.height = window.innerHeight; const ctx = focus_canvas.getContext("2d"); drawSegmentedLine(ctx, 0, 0, focus_canvas.width, focus_canvas.height,0.8); drawSegmentedLine(ctx, focus_canvas.width, 0, 0, focus_canvas.height,0.8); let onKeyDown = async (e) => { if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA' || event.target.isContentEditable) { return; } if ((e.metaKey || e.shiftKey)&&(e.key === 'z' || e.key === 'Z')) { if(!previousMapId) return e.stopImmediatePropagation(); importLocations(previousMapId, [{ id: -1, location: {lat: LOCATION.lat, lng: LOCATION.lng}, panoId: LOCATION.panoId ?? null, heading: LOCATION.heading ?? 0, pitch: LOCATION.pitch ?? 0, zoom: 0, //LOCATION.zoom ?? 0, tags: LOCATION.tags, flags: LOCATION.panoId ? 1 : 0 }]); Swal.fire({ title: 'Import Succeeded ✔️', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" } }); } if (!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&(e.key === 'x' || e.key === 'X')){ if (!onFocus){ onFocus=true document.body.appendChild(focus_canvas) } else{ onFocus=false document.body.removeChild(focus_canvas) } } if (!e.ctrlKey&&!e.metaKey&&!e.shiftKey && e.key.toLowerCase() === 'h') { e.stopImmediatePropagation(); toggleElementHidden() } if (!e.ctrlKey&&!e.metaKey&&!e.shiftKey && e.key.toLowerCase() === 'c') { e.stopImmediatePropagation(); const currentLink=await getShortUrl() if(!currentLink) return GM_setClipboard(currentLink, 'text'); Swal.fire({ title: 'Copy Succeeded ✔️', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" } }); } if (!e.ctrlKey&&!e.metaKey && e.key.toLowerCase() === 'v') { e.stopImmediatePropagation(); await generateUpdateReportText() } if (!e.ctrlKey&&!e.metaKey && e.key.toLowerCase() === 'j') { e.stopImmediatePropagation(); if (LOCATION) { GM_setClipboard(LOCATION.panoId) Swal.fire({ title: 'Copy Succeeded ✔️', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" } }); } } if (!e.ctrlKey&&!e.metaKey && e.key.toLowerCase() === 'k') { e.stopImmediatePropagation(); if (LOCATION) { GM_setClipboard(`POINT(${LOCATION.lng.toFixed(6)} ${LOCATION.lat.toFixed(6)})`) Swal.fire({ title: 'Copy Succeeded ✔️', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" } }); } } if (!e.ctrlKey&&!e.metaKey && e.key.toLowerCase() === 'l') { e.stopImmediatePropagation(); if (LOCATION) { GM_setClipboard(LOCATION.altitude) Swal.fire({ title: 'Copy Succeeded ✔️', timer: 1500, showConfirmButton: false, allowOutsideClick:true, backdrop:null, customClass: { popup: "swal-small-popup" } }); } } } GM_addStyle(` .mwstmm-modal { position: fixed; inset: 0; z-index: 99999; display: flex; align-items: center; justify-content: center; flex-direction: column; } .mwstmm-modal .dim { position: fixed; inset: 0; z-index: 0; background: rgba(0,0,0,0.75); } .mwstmm-modal .text { position: relative; z-index: 1; } .mwstmm-modal .inner { box-sizing: border-box; position: relative; z-index: 1; background: #fff; padding: 20px; margin: 20px; width: calc(100% - 40px); max-width: 500px; overflow: auto; color: #000; flex: 0 1 auto; } #mwstmm-loader { color: #fff; font-weight: bold; } .mwstmm-settings { position: absolute; top: 1rem; left: 1rem; z-index: 9; display: flex; flex-direction: column; gap: 5px; align-items: flex-start; } #note-btn { position: absolute; width:40px; height:40px; top: 0.85rem; right: 7.2rem; z-index: 9; display: flex; border: none; border-radius: 50%; background: #00000099; background-repeat: no-repeat; background-position:50%; flex-direction: column; gap: 5px; align-items: flex-start; } #note-btn:hover{ cursor: pointer; opacity:0.8; } #note-btn::after{ display:none; content: attr(data-text); position:absolute; top:120%; left:50%; transform: translateX(-50%); background-color: rgba(0, 0, 0, 1); color: #fff; padding: 5px; border-radius: 5px; font-weight:normal; font-size: 11px; line-height: 1; height: auto; white-space: nowrap; transition: opacity 0.5s ease; } #note-btn:hover::after { opacity: 1; display: block; } #settings-btn { position: absolute; width:40px; height:40px; top: 0.85rem; right: 7.2rem; z-index: 9; display: flex; border: none; border-radius: 50%; background: #00000099; background-repeat: no-repeat; background-position:50%; flex-direction: column; gap: 5px; align-items: flex-start; } #settings-btn:hover{ cursor: pointer; opacity:0.8; } #settings-btn::after{ display:none; content: attr(data-text); position:absolute; top:120%; left:50%; transform: translateX(-50%); background-color: rgba(0, 0, 0, 1); color: #fff; padding: 5px; border-radius: 5px; font-weight:normal; font-size: 11px; line-height: 1; height: auto; white-space: nowrap; transition: opacity 0.5s ease; } #settings-btn:hover::after { opacity: 1; display: block; } #coordinate-altitude-control { display: flex; left: 300px; align-items: flex-end; text-align: left; padding: 0 0.3rem; gap:0.15rem; color: #fff !important; font-size: 10px; margin-bottom: 0; background: #1f1f1f; opacity:0.8; box-shadow: 0 1px 4px -1px #0000004d; } #mwstmm-main { position: absolute; width:40px; height:40px; top: 0.85rem; right: 4rem; z-index: 9; display: flex; border: none; border-radius: 50%; background: #00000099; background-repeat: no-repeat; background-position:50%; flex-direction: column; gap: 5px; align-items: flex-start; } #mwstmm-main:hover{ cursor: pointer; opacity:0.8; } #mwstmm-main::after{ display:none; content: attr(data-text); position:absolute; top:120%; transform: translateX(-50%); background-color: rgba(0, 0, 0, 1); color: #fff; padding: 5px; border-radius: 5px; font-weight:normal; font-size: 11px; line-height: 1; height: auto; white-space: nowrap; transition: opacity 0.5s ease; } #mwstmm-main:hover::after { opacity: 1; display: block; } .mwstmm-settings.extra-pad { top: 2.5rem; } .mwstmm-title { font-size: 15px; font-weight: bold; text-shadow: rgb(204, 48, 46) 2px 0px 0px, rgb(204, 48, 46) 1.75517px 0.958851px 0px, rgb(204, 48, 46) 1.0806px 1.68294px 0px, rgb(204, 48, 46) 0.141474px 1.99499px 0px, rgb(204, 48, 46) -0.832294px 1.81859px 0px, rgb(204, 48, 46) -1.60229px 1.19694px 0px, rgb(204, 48, 46) -1.97998px 0.28224px 0px, rgb(204, 48, 46) -1.87291px -0.701566px 0px, rgb(204, 48, 46) -1.30729px -1.5136px 0px, rgb(204, 48, 46) -0.421592px -1.95506px 0px, rgb(204, 48, 46) 0.567324px -1.91785px 0px, rgb(204, 48, 46) 1.41734px -1.41108px 0px, rgb(204, 48, 46) 1.92034px -0.558831px 0px; position: relative; z-index: 1; } .mwstmm-subtitle { font-size: 12px; background: rgba(204, 48, 46, 0.4); padding: 3px 5px; border-radius: 5px; position: relative; z-index: 0; top: -8px; text-shadow: 0 1px 2px rgba(0,0,0,0.5); } .mwstmm-subtitle a:hover { text-decoration: underline; } .mwstmm-settings-option { background: var(--ds-color-purple-100); padding: 6px 10px; border-radius: 5px; font-size: 12px; cursor: pointer; opacity: 0.75; transition: opacity 0.2s; pointer-events: auto; } .mwstmm-settings-option:hover { opacity: 1; } #mwstmm-map-list h3 { margin-bottom: 10px; } #mwstmm-map-list .tag-input { display: block; width: 100%; font: inherit; border:1px solid #ccc; } #mwstmm-map-list .maps { max-height: 200px; overflow-x: hidden; overflow-y: auto; font-size: 15px; } #mwstmm-map-list .map { display: flex; justify-content: space-between; align-items: center; gap: 20px; padding: 8px; transition: background 0.2s; } #mwstmm-map-list .map:nth-child(2n) { background: #f0f0f0; } #mwstmm-map-list .map-buttons:not(.is-added) .map-added { display: none !important; } #mwstmm-map-list .map-buttons.is-added .map-add { display: none !important; } #mwstmm-map-list .map-add { background: green; color: #fff; padding: 3px 6px; border-radius: 5px; font-size: 13px; font-weight: bold; cursor: pointer; } #mwstmm-map-list .map-added { background: #000; color: #fff; padding: 3px 6px; border-radius: 5px; font-size: 13px; font-weight: bold; } div[class^="result-list_listItemWrapper__"] { position: relative; } div[class^="result-list_listItemWrapper__"] .mwstmm-settings-option { margin-left: auto; line-height: 1; align-self: center; } .swal-small-popup { position: absolute; width: auto !important; height: auto !important; top: -250px !important; font-weight: bold !important; font-size: 8px !important; text-align: center !important; display: flex !important; justify-content: center !important; align-items: center !important; } .swal-info-popup { position: absolute; width: auto !important; height: auto !important; top: -250px !important; font-weight: bold !important; font-size: 8px !important; text-align: center !important; display: block !important; justify-content: center !important; align-items: center !important; } .tag-buttons { margin-top: 10px; } .tag-button { margin: 5px 5px 0 0; padding: 4px 10px; border: 1px solid #ccc; background: #f0f0f0; border-radius: 4px; cursor: pointer; transition: 0.2s; font-size: 16px; font-weight: bold; } .tag-button:hover { background: #e0e0e0; } .tag-button.active { background-color: green; color: white; border-color: green; } .swal2-title { font-size: 18px !important; } .swal2-input { font-size: 13px !important; } .swal2-select { font-size: 13px !important; } .swal2-confirm, .swal2-deny { font-size: 16px !important; padding: 0.4rem 0.8rem !important; } `); })();