// ==UserScript==
// @name 谷歌街景助手 - 全景下载
// @description 获取精确拍摄时间 | 下载全景图片 | 对比历史街景 | 导入位置至 Map Making App | 复制短链接 | 解除小地图缩放限制
// @namespace https://greasyfork.org/users/1179204
// @version 2.9.4
// @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:
`
Date Format:
Default (locale)
yyyy-mm-dd
yyyy/mm/dd
dd/mm/yyyy
mm/dd/yyyy
Month dd, yyyy
dd Month, yyyy
Lunar
Time Format:
24-hour (hh:mm:ss)
12-hour (hh:mm:ss AM/PM)
Accuracy (seconds):
Search Radius (meters):
Length Units:
Meters
Imperial
MapMaking API Key:
Recent Maps to Show:
Full Update Types Check:
Enabled
Disabled
Nearby Update Check:
Disabled
≤5km
≤10km
≤15km
≤20km
≤40km
≤50km
≤100km
Fallback to OSM Address:
Enabled
Disabled
Road Name Labels:
Visible
Hidden
Unofficial Coverage:
Enabled
Disabled
Coverage Preference:
Default
Gen 1
Gen 2
Gen 2/3
Gen 3
Gen 4
BadCam
Exclude BadCam & Gen 1
`,
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 ``;
}
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 += ``;
}
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(`
${LOCATION.tagFields[i]}
`);
}
}
if (previousTags.length > 0) {
for (const tag of previousTags) {
if (LOCATION.tagFields.includes(tag)) continue;
tagButtonsArr.push(`${tag} `);
}
}
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);
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:
'' +
'1 (100KB~500KB) ' +
'2 (500KB~1MB) ' +
'3 (1MB~4MB) ' +
'4 (4MB~8MB) ' +
'5 (8MB~15MB) ' +
' ',
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?``
:(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,
.svt-top,
.svt-dates,
.svt-status,
#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 MINIMAP_MIN_ZOOM = 0;
function patchMinimapZoomSource(code) {
const zoomOutRe = /([A-Za-z$_][\w$]*)!==void 0&&\1-1>=10&&/g;
if (!zoomOutRe.test(code)) return null;
const patched = code.replace(zoomOutRe, (match) => match.replace('-1>=10&&', `-1>=${MINIMAP_MIN_ZOOM}&&`));
return patched.replace(/([A-Za-z$_][\w$]*)!==void 0&&\1>10,/g, (match) => match.replace('>10,', `>${MINIMAP_MIN_ZOOM},`));
}
function installMinimapMinZoomBypass() {
const page = unsafeWindow;
const proto = page.HTMLScriptElement.prototype;
const srcDesc = Object.getOwnPropertyDescriptor(proto, 'src');
if (!srcDesc || typeof srcDesc.set !== 'function' || !srcDesc.configurable) return;
const nativeSet = srcDesc.set;
const nativeGet = srcDesc.get;
const nativeAppend = page.Node.prototype.appendChild;
const nativeInsert = page.Node.prototype.insertBefore;
const waiting = new WeakMap();
function urlOf(value) {
if (typeof value === 'string') return value;
if (value == null) return '';
try {
const text = String(value);
return text === '[object Object]' ? '' : text;
} catch (e) {
return '';
}
}
function shouldIntercept(url) {
return url.includes('/maps/_/js/') && url.includes('ed=1') && !url.startsWith('blob:');
}
function finish(el, assigned) {
const job = waiting.get(el);
try {
nativeSet.call(el, assigned);
} catch (e) {
try { nativeSet.call(el, job ? job.url : assigned); } catch (err) {}
}
if (job) job.ready = true;
}
function rewrite(el, url) {
const job = waiting.get(el);
page.fetch(url, {credentials: 'same-origin'}).then((res) => {
if (!res.ok) throw new Error(String(res.status));
return res.text();
}).then((code) => {
const patched = patchMinimapZoomSource(code);
if (!patched) {
finish(el, url);
return;
}
const blob = new page.Blob([patched], {type: 'text/javascript'});
const blobUrl = page.URL.createObjectURL(blob);
el.addEventListener('load', () => page.URL.revokeObjectURL(blobUrl), {once: true});
finish(el, blobUrl);
}).catch(() => {
finish(el, url);
}).finally(() => {
if (job) job.ready = true;
if (job && job.resolve) job.resolve();
});
}
function delayInsertion(parent, node, original, args) {
const job = node && node.tagName === 'SCRIPT' ? waiting.get(node) : null;
if (!job || job.ready) return original.apply(parent, args);
job.promise.then(() => {
if (!node.isConnected) original.apply(parent, args);
});
return node;
}
Object.defineProperty(proto, 'src', {
configurable: true,
enumerable: srcDesc.enumerable,
get() {
const job = waiting.get(this);
if (job && !job.ready) return job.url;
return nativeGet.call(this);
},
set(value) {
const url = urlOf(value);
if (!shouldIntercept(url) || waiting.has(this)) {
if (!shouldIntercept(url)) waiting.delete(this);
return nativeSet.call(this, value);
}
let resolve;
const promise = new page.Promise((r) => { resolve = r; });
waiting.set(this, {url, ready: false, promise, resolve});
rewrite(this, url);
},
});
page.Node.prototype.appendChild = function(node) {
return delayInsertion(this, node, nativeAppend, arguments);
};
page.Node.prototype.insertBefore = function(node) {
return delayInsertion(this, node, nativeInsert, arguments);
};
}
installMinimapMinZoomBypass();
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 origFetch = unsafeWindow.fetch;
unsafeWindow.fetch = async function(input, init) {
const request = input instanceof Request ? input : null;
const url = request ? request.url : String(input);
if (url.includes("batchexecute?rpcids=hspqX") && !CONFIG.UNOFFICIAL_COVERAGE) {
let body = init?.body;
if (body === undefined && request) body = await request.clone().text();
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 = JSON.parse(raw);
let inner = 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));
}
}
const newBody = params.map(kv => kv.join("=")).join("&");
if (request) {
const newRequest = new Request(request, {body: newBody});
return origFetch.call(this, newRequest, init);
}
return origFetch.call(this, input, {...init, body: newBody});
}
}
return origFetch.call(this, input, init);
};
let compareOn = false;
let compareChromeStyle = null;
let compareMode = 'overlap';
let compareRatio = 0.5;
// The street view Google is showing is always one side of the comparison; the other
// side is the date the user picked in the timeline (or the closest date at a new spot).
let compareCur = null;
let compareOther = null;
let compareTarget = null;
let compareResolving = '';
let compareFailed = {id: '', at: 0};
let compareNoOther = false;
let compareFollowAt = 0;
let compareUrlId = '';
let compareShown = false;
let comparePoseKey = '';
let compareDateMenu = '';
let compareHoldId = '';
let compareSideRev = 0;
let compareLeft = null;
let compareRight = null;
let comparePickAt = 0;
let compareRev = 0;
let compareRaf = 0;
let compareGL = null;
let compareProgram = null;
let compareUniforms = null;
let compareUiAt = 0;
let compareCanvas = null;
let compareHud = null;
let compareCam = null;
let compareHudKey = '';
let compareOffset = 12;
let compareOffsetAt = 0;
const compareTex = new Map();
const compareIcon = ` `;
function compareAddress() {
if (!LOCATION) return 'Street View compare';
const parts = [LOCATION.road, LOCATION.locality, LOCATION.region].filter(Boolean);
return (parts.join(' ') || 'Street View compare').replace(/[&<>"']/g, (ch) => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[ch]));
}
function compareMonthKey(date) {
if (!date || !date.year) return 0;
return date.year * 12 + ((date.month || 1) - 1);
}
function compareLabel(date) {
if (!date || !date.year) return 'Unknown date';
const names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${names[Math.max(0, Math.min(11, (date.month || 1) - 1))]} ${date.year}`;
}
// Everything the compare view needs to know about one panorama: where it is, how big
// it is, which other dates exist at the same spot and which panoramas are next to it.
async function describeComparePano(panoId) {
if (!panoId) return null;
let meta;
try {
meta = await fetchGooglePanorama('GetMetadata', panoId);
} catch (e) {
return null;
}
const block = meta?.[1]?.[0];
if (!Array.isArray(block)) return null;
const node = block[5]?.[0];
const id = block[1]?.[1] || panoId;
const place = node?.[1];
const stamp = block[6]?.[7];
const links = node?.[3]?.[0] || [];
const history = node?.[8] || [];
const dateLinks = new Set();
const dates = [];
const self = {
panoId: id,
type: block[1]?.[0] === 10 ? 10 : 2,
year: stamp?.[0] || 0,
month: stamp?.[1] || 1,
};
dates.push(self);
for (const entry of history) {
const link = links[entry?.[0]];
const ym = entry?.[1];
const otherId = link?.[0]?.[1];
if (!otherId || !Array.isArray(ym)) continue;
dateLinks.add(entry[0]);
if (dates.some((d) => d.panoId === otherId)) continue;
dates.push({panoId: otherId, type: link?.[0]?.[0] === 10 ? 10 : 2, year: ym[0], month: ym[1]});
}
const neighbors = [];
links.forEach((link, index) => {
const otherId = link?.[0]?.[1];
const lat = link?.[2]?.[0]?.[2];
const lng = link?.[2]?.[0]?.[3];
if (!otherId || otherId === id || dateLinks.has(index) || typeof lat !== 'number' || typeof lng !== 'number') return;
if (neighbors.some((n) => n.panoId === otherId)) return;
neighbors.push({panoId: otherId, lat, lng});
});
const info = {
panoId: id,
type: self.type,
year: self.year,
month: self.month,
heading: place?.[2]?.[0] || 0,
lat: place?.[0]?.[2],
lng: place?.[0]?.[3],
world: panoWorldSize(meta),
dates,
neighbors,
raw: {
name: block[3]?.[2]?.[0],
place,
stamp,
},
};
info.label = compareLabel(info);
return info;
}
let compareSheetCollapsed = false;
const sheetHideIcon = ` `;
const sheetShowIcon = ` `;
function tabButtonStyle() {
return {
width: '28px',
height: '27px',
minWidth: '28px',
maxWidth: '28px',
margin: '0',
padding: '0',
border: '0',
borderRadius: '8px 8px 0 0',
background: '#000',
color: '#fff',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'fixed',
right: 'auto',
bottom: 'auto',
zIndex: '5',
cursor: 'pointer',
pointerEvents: 'auto',
overflow: 'hidden',
boxSizing: 'border-box',
};
}
// These buttons must not be children of .cE0Abd. That bar is a flex row packed to
// the right, so an absolute child with an auto offset is given the same static
// position as the native close button and paints over it. Google also rewrites
// styles inside the bar, which drops any offset we set. Keep the buttons on
// document.body and place them from the close button's viewport box.
function layoutCompareTabs() {
const compare = document.getElementById('svt-compare-btn');
const sheet = document.getElementById('svt-sheet-btn');
const closeBtn = document.querySelector('.cE0Abd button.zmX2Df');
const closeRect = closeBtn ? closeBtn.getBoundingClientRect() : null;
const visible = closeRect && closeRect.width > 0 && closeRect.height > 0;
const place = (el, left) => {
if (!visible) {
el.style.visibility = 'hidden';
el.style.pointerEvents = 'none';
return;
}
const size = 28;
let x = Math.floor(left);
if (x + size > closeRect.left - 8) x = Math.floor(closeRect.left - 8 - size);
const y = Math.floor(closeRect.top);
el.style.visibility = 'visible';
el.style.pointerEvents = 'auto';
if (el.style.left !== x + 'px') el.style.left = x + 'px';
if (el.style.top !== y + 'px') el.style.top = y + 'px';
};
const gap = 28;
if (sheet) place(sheet, visible ? closeRect.left - gap - 28 : 0);
if (compare) place(compare, visible ? closeRect.left - gap - 28 - (sheet ? 16 + 28 : 0) : 0);
}
function keepTabClick(e) {
e.stopPropagation();
}
function syncCompareButton() {
const btn = document.getElementById('svt-compare-btn');
if (!btn) return;
btn.setAttribute('aria-pressed', compareOn ? 'true' : 'false');
btn.style.background = compareOn ? '#fff' : '#000';
btn.style.color = compareOn ? '#202124' : '#fff';
}
function syncTimelineSheet() {
const sheet = document.querySelector('.wzj68e');
if (!sheet) return;
const collapsed = compareOn && compareSheetCollapsed;
sheet.style.overflow = collapsed ? 'hidden' : '';
sheet.style.maxHeight = collapsed ? '0px' : '';
sheet.style.opacity = collapsed ? '0' : '';
sheet.style.pointerEvents = collapsed ? 'none' : '';
sheet.style.transition = 'max-height .18s ease, opacity .18s ease';
const btn = document.getElementById('svt-sheet-btn');
if (!btn) return;
const label = collapsed ? 'Show timeline' : 'Hide timeline';
btn.title = label;
btn.setAttribute('aria-label', label);
btn.setAttribute('aria-pressed', collapsed ? 'true' : 'false');
btn.innerHTML = collapsed ? sheetShowIcon : sheetHideIcon;
btn.style.background = collapsed ? '#fff' : '#000';
btn.style.color = collapsed ? '#202124' : '#fff';
}
function mountSheetButton() {
const existing = document.getElementById('svt-sheet-btn');
if (!compareOn) {
existing?.remove();
return;
}
if (existing) {
syncTimelineSheet();
return;
}
const btn = document.createElement('button');
btn.id = 'svt-sheet-btn';
btn.type = 'button';
Object.assign(btn.style, tabButtonStyle());
btn.addEventListener('pointerdown', keepTabClick);
btn.addEventListener('pointerup', keepTabClick);
btn.addEventListener('click', (e) => {
keepTabClick(e);
compareSheetCollapsed = !compareSheetCollapsed;
syncTimelineSheet();
});
document.body.appendChild(btn);
syncTimelineSheet();
}
function mountCompareButton() {
const bar = document.querySelector('.cE0Abd');
const closeBtn = bar && bar.querySelector('button.zmX2Df');
if (!bar || !closeBtn) {
document.getElementById('svt-compare-btn')?.remove();
document.getElementById('svt-sheet-btn')?.remove();
return;
}
if (!document.getElementById('svt-compare-btn')) {
const btn = document.createElement('button');
btn.id = 'svt-compare-btn';
btn.type = 'button';
btn.setAttribute('aria-label', 'Compare Street View dates');
btn.title = 'Compare Street View dates';
btn.innerHTML = compareIcon;
Object.assign(btn.style, tabButtonStyle());
btn.addEventListener('pointerdown', keepTabClick);
btn.addEventListener('pointerup', keepTabClick);
btn.addEventListener('click', (e) => {
keepTabClick(e);
toggleCompare();
});
document.body.appendChild(btn);
}
syncCompareButton();
mountSheetButton();
layoutCompareTabs();
syncTimelineSheet();
}
// ---- Compare renderer: tiled panorama engine (modelled on Kakao panorama.js) ----
// Each panorama keeps a pyramid of 512px tiles. Only tiles inside the current view are
// fetched (fetch + createImageBitmap, decoded off the main thread), uploaded once as
// GPU textures and drawn as sphere patches. Coarse tiles stay resident as a fallback so
// there are never holes while sharper tiles stream in.
const COMPARE_TILE = 512;
const COMPARE_MAX_TILES = 96;
const COMPARE_MAX_FETCH = 8;
const COMPARE_UPLOADS_PER_FRAME = 3;
let compareQueue = [];
let compareInflight = 0;
let compareUploads = [];
let compareDrawNo = 0;
let compareDirty = true;
let compareMeshes = null;
let compareObserver = null;
function compareTileUrl(date, zoom, x, y) {
if (date.type === 10) {
return `https://lh3.ggpht.com/jsapi2/a/b/c/x${x}-y${y}-z${zoom}/${encodeURIComponent(date.panoId)}`;
}
return `https://streetviewpixels-pa.googleapis.com/v1/tile?cb_client=apiv3&panoid=${encodeURIComponent(date.panoId)}&output=tile&zoom=${zoom}&nbt=0&fover=2&x=${x}&y=${y}`;
}
function panoWorldSize(meta) {
const world = meta?.[1]?.[0]?.[2]?.[2];
let height = world?.[0];
let width = world?.[1];
if (!width || !height) return {width: 16384, height: 8192};
if (width < height) {
const swap = width;
width = height;
height = swap;
}
return {width, height};
}
// Google's pyramid: the top zoom holds the full-resolution panorama and every lower
// zoom halves it, so a panorama of any size maps onto 2^(zoom - zmax).
function compareZoomMax(world) {
return Math.max(1, Math.min(5, Math.ceil(Math.log2(Math.max(world.width, COMPARE_TILE) / COMPARE_TILE))));
}
function compareGrid(entry, zoom) {
let grid = entry.grids[zoom];
if (grid) return grid;
const scale = 2 ** (zoom - entry.zmax);
const width = Math.max(1, Math.round(entry.world.width * scale));
const height = Math.max(1, Math.round(entry.world.height * scale));
grid = {
zoom,
width,
height,
cols: Math.ceil(width / COMPARE_TILE),
rows: Math.ceil(height / COMPARE_TILE),
};
entry.grids[zoom] = grid;
return grid;
}
function compareTile(entry, zoom, x, y) {
const key = (zoom << 16) | (y << 8) | x;
let tile = entry.tiles.get(key);
if (!tile) {
tile = {
entry,
zoom,
x,
y,
key,
state: 'idle',
tex: null,
bitmap: null,
want: 0,
used: 0,
pri: 0,
retryAt: 0,
pinned: zoom <= 2,
};
entry.tiles.set(key, tile);
}
return tile;
}
function wantCompareTile(tile, pri) {
tile.want = compareDrawNo;
if (tile.state === 'error' && performance.now() > tile.retryAt) tile.state = 'idle';
if (tile.state === 'queued') {
if (pri < tile.pri) tile.pri = pri;
return;
}
if (tile.state !== 'idle') return;
tile.state = 'queued';
tile.pri = pri;
compareQueue.push(tile);
}
async function fetchCompareTile(tile) {
const entry = tile.entry;
const rev = compareRev;
tile.state = 'loading';
compareInflight++;
try {
const res = await fetch(compareTileUrl(entry.date, tile.zoom, tile.x, tile.y), {credentials: 'omit'});
if (!res.ok) throw new Error('tile ' + res.status);
const bitmap = await createImageBitmap(await res.blob());
if (rev !== compareRev || entry.dead || tile.state !== 'loading') {
bitmap.close?.();
if (tile.state === 'loading') tile.state = 'idle';
return;
}
tile.bitmap = bitmap;
tile.state = 'bitmap';
compareUploads.push(tile);
} catch (e) {
if (tile.state === 'loading') {
tile.state = 'error';
tile.retryAt = performance.now() + 5000;
}
} finally {
compareInflight--;
compareDirty = true;
}
}
function pumpCompareQueue() {
if (!compareQueue.length) return;
compareQueue = compareQueue.filter((tile) => {
if (tile.state !== 'queued') return false;
if (!tile.pinned && tile.want < compareDrawNo - 3) {
tile.state = 'idle';
return false;
}
return true;
});
if (!compareQueue.length || compareInflight >= COMPARE_MAX_FETCH) return;
compareQueue.sort((a, b) => a.pri - b.pri);
while (compareInflight < COMPARE_MAX_FETCH && compareQueue.length) {
fetchCompareTile(compareQueue.shift());
}
}
function evictCompareTiles(entry) {
const gl = compareGL;
if (!gl) return;
const resident = [];
entry.tiles.forEach((tile) => {
if (tile.tex) resident.push(tile);
});
let extra = resident.length - COMPARE_MAX_TILES;
if (extra <= 0) return;
resident
.filter((tile) => !tile.pinned && tile.used < compareDrawNo - 1)
.sort((a, b) => a.used - b.used)
.some((tile) => {
gl.deleteTexture(tile.tex);
tile.tex = null;
tile.state = 'idle';
extra--;
return extra <= 0;
});
}
function uploadCompareTiles() {
const gl = compareGL;
if (!gl || !compareUploads.length) return false;
const isPot = (n) => n > 0 && (n & (n - 1)) === 0;
let count = 0;
let changed = false;
while (compareUploads.length && count < COMPARE_UPLOADS_PER_FRAME) {
const tile = compareUploads.shift();
const bitmap = tile.bitmap;
tile.bitmap = null;
if (!bitmap) continue;
if (tile.entry.dead || tile.state !== 'bitmap') {
bitmap.close?.();
continue;
}
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, bitmap);
const mips = isPot(bitmap.width) && isPot(bitmap.height);
if (mips) gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, mips ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
bitmap.close?.();
tile.tex = tex;
tile.state = 'ready';
tile.used = compareDrawNo;
count++;
changed = true;
evictCompareTiles(tile.entry);
}
return changed;
}
function refreshCompareEntry(entry) {
if (entry.status === 'ready') return;
let ready = 0;
let failed = false;
entry.base.forEach((tile) => {
if (tile.state === 'ready') {
ready++;
return;
}
if (tile.state === 'error') failed = true;
wantCompareTile(tile, -1);
});
const status = ready === entry.base.length ? 'ready' : failed ? 'error' : 'loading';
if (status !== entry.status) {
entry.status = status;
compareDirty = true;
}
}
function resetCompareEntryTextures(entry) {
entry.tiles.forEach((tile) => {
tile.tex = null;
if (tile.bitmap) {
tile.bitmap.close?.();
tile.bitmap = null;
}
if (tile.state === 'ready' || tile.state === 'bitmap' || tile.state === 'queued') tile.state = 'idle';
});
entry.status = 'loading';
}
function disposeCompareEntry(entry) {
entry.dead = true;
entry.tiles.forEach((tile) => {
if (tile.tex && compareGL && !compareGL.isContextLost()) compareGL.deleteTexture(tile.tex);
tile.tex = null;
if (tile.bitmap) {
tile.bitmap.close?.();
tile.bitmap = null;
}
tile.state = 'dead';
});
entry.tiles.clear();
}
function pruneCompareEntries() {
const keep = new Set([compareLeft?.panoId, compareRight?.panoId, compareHoldId].filter(Boolean));
compareTex.forEach((entry, id) => {
if (keep.has(id)) return;
disposeCompareEntry(entry);
compareTex.delete(id);
});
}
function disposeAllCompareEntries() {
compareTex.forEach(disposeCompareEntry);
compareTex.clear();
compareQueue = [];
compareUploads = [];
}
function loadCompareTexture(date) {
const current = compareTex.get(date.panoId);
if (current && !current.dead) return current;
const world = date.world || {width: 16384, height: 8192};
const entry = {
panoId: date.panoId,
date,
world,
zmax: compareZoomMax(world),
grids: [],
tiles: new Map(),
base: [],
status: 'loading',
dead: false,
};
compareTex.set(date.panoId, entry);
const low = compareGrid(entry, 1);
for (let y = 0; y < low.rows; y++) {
for (let x = 0; x < low.cols; x++) {
const tile = compareTile(entry, 1, x, y);
entry.base.push(tile);
wantCompareTile(tile, -1);
}
}
if (entry.zmax >= 2) {
const mid = compareGrid(entry, 2);
for (let y = 0; y < mid.rows; y++) {
for (let x = 0; x < mid.cols; x++) wantCompareTile(compareTile(entry, 2, x, y), -0.5);
}
}
compareDirty = true;
return entry;
}
function createCompareMesh(gl, n) {
const verts = new Float32Array((n + 1) * (n + 1) * 2);
let k = 0;
for (let j = 0; j <= n; j++) {
for (let i = 0; i <= n; i++) {
verts[k++] = i / n;
verts[k++] = j / n;
}
}
const idx = new Uint16Array(n * n * 6);
k = 0;
for (let j = 0; j < n; j++) {
for (let i = 0; i < n; i++) {
const a = j * (n + 1) + i;
const b = a + 1;
const c = a + n + 1;
const d = c + 1;
idx[k++] = a;
idx[k++] = b;
idx[k++] = c;
idx[k++] = b;
idx[k++] = d;
idx[k++] = c;
}
}
const vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, verts, gl.STATIC_DRAW);
const ibo = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW);
return {vbo, ibo, count: idx.length};
}
function initCompareGL(canvas) {
const gl = canvas.getContext('webgl', {
alpha: true,
premultipliedAlpha: true,
antialias: false,
depth: false,
stencil: false,
powerPreference: 'high-performance',
});
if (!gl) return null;
// Tile patch on the unit sphere: the grid (g) is placed by direction, rotated into
// camera space and perspective-projected in the vertex shader. The texture only
// needs plain per-tile coordinates, so panning/zooming never touches texture data.
const vs = [
'attribute vec2 g;',
'uniform vec4 uRect;',
'uniform vec4 uRot;',
'uniform vec2 uTan;',
'uniform vec2 uFill;',
'uniform float uH0;',
'varying vec2 vUv;',
'void main(){',
'float u=mix(uRect.x,uRect.y,g.x);',
'float t=mix(uRect.z,uRect.w,g.y);',
'float az=(u-0.5)*6.2831853+uH0;',
'float lat=(t-0.5)*3.14159265;',
'float cl=cos(lat);',
'vec3 w=vec3(cl*sin(az),sin(lat),cl*cos(az));',
'float x=w.x*uRot.x-w.z*uRot.y;',
'float dz2=w.x*uRot.y+w.z*uRot.x;',
// Tilt below 90 looks down, so a positive pitch (90-tilt) drops the view.
'float y=w.y*uRot.z+dz2*uRot.w;',
'float z=-w.y*uRot.w+dz2*uRot.z;',
'gl_Position=vec4(x/uTan.x,y/uTan.y,z-0.02,z);',
'vUv=vec2(g.x*uFill.x,(1.0-g.y)*uFill.y);',
'}',
].join('');
const fs = [
'precision mediump float;',
'uniform sampler2D uTex;',
'varying vec2 vUv;',
'void main(){gl_FragColor=vec4(texture2D(uTex,vUv).rgb,1.0);}',
].join('');
const compile = (type, source) => {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return gl.getShaderParameter(shader, gl.COMPILE_STATUS) ? shader : null;
};
const vertex = compile(gl.VERTEX_SHADER, vs);
const fragment = compile(gl.FRAGMENT_SHADER, fs);
if (!vertex || !fragment) return null;
const program = gl.createProgram();
gl.attachShader(program, vertex);
gl.attachShader(program, fragment);
gl.bindAttribLocation(program, 0, 'g');
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return null;
gl.useProgram(program);
gl.enableVertexAttribArray(0);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE);
gl.disable(gl.BLEND);
gl.uniform1i(gl.getUniformLocation(program, 'uTex'), 0);
compareProgram = program;
compareMeshes = {fine: createCompareMesh(gl, 12), coarse: createCompareMesh(gl, 32)};
compareUniforms = {
rect: gl.getUniformLocation(program, 'uRect'),
rot: gl.getUniformLocation(program, 'uRot'),
tan: gl.getUniformLocation(program, 'uTan'),
fill: gl.getUniformLocation(program, 'uFill'),
h0: gl.getUniformLocation(program, 'uH0'),
};
return gl;
}
function sizeCompareCanvas() {
if (!compareCanvas) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const w = Math.max(1, Math.round(compareCanvas.clientWidth * dpr));
const h = Math.max(1, Math.round(compareCanvas.clientHeight * dpr));
if (compareCanvas.width !== w || compareCanvas.height !== h) {
compareCanvas.width = w;
compareCanvas.height = h;
}
compareDirty = true;
}
// The compare view never owns a camera. Every frame it reads the pose of the camera
// Google's own viewer is using, so dragging, inertia, wheel zoom and the compass all keep
// working natively and the two views can never drift apart.
function readStreetViewPose() {
const root = pageRoot();
const view = findStreetView();
if (view && root && typeof root.tx === 'function' && typeof root.lm === 'function') {
try {
const cam = view.camera.get();
const pov = root.im(cam);
const heading = root.tx(pov);
const tilt = typeof pov.od === 'function' ? pov.od() : NaN;
const fov = root.lm(cam);
if (Number.isFinite(heading) && Number.isFinite(tilt) && Number.isFinite(fov) && fov > 1 && fov < 179) {
return {
yaw: heading * Math.PI / 180,
pitch: (90 - tilt) * Math.PI / 180,
fov: fov * Math.PI / 180,
heading,
tilt,
fovDeg: fov,
};
}
} catch (e) {
streetViewCtl = null;
}
}
const params = extractParams(location.href);
if (!params || params.y == null || params.h == null || params.t == null) return null;
return {
yaw: params.h * Math.PI / 180,
pitch: (90 - params.t) * Math.PI / 180,
fov: (params.y || 75) * Math.PI / 180,
heading: Number(params.h),
tilt: Number(params.t),
fovDeg: Number(params.y || 75),
};
}
function ensureCompareLayers(force) {
if (!force && compareCanvas && compareCanvas.isConnected && compareGL && !compareGL.isContextLost()) return true;
const host = document.querySelector('.D21QYe') || document.querySelector('.UL7Qtf');
if (!host) return false;
if (compareCanvas && compareCanvas.isConnected && compareGL && !compareGL.isContextLost() && compareCanvas.parentElement === host) {
return true;
}
compareObserver?.disconnect();
compareCanvas?.remove();
compareHud?.remove();
compareShown = false;
compareQueue = [];
compareUploads = [];
compareTex.forEach(resetCompareEntryTextures);
compareCanvas = document.createElement('canvas');
compareCanvas.id = 'svt-compare-view';
compareHud = document.createElement('div');
compareHud.id = 'svt-compare-hud';
host.appendChild(compareCanvas);
document.body.appendChild(compareHud);
compareCanvas.style.visibility = 'visible';
compareGL = initCompareGL(compareCanvas);
compareCanvas.addEventListener('webglcontextlost', (e) => e.preventDefault());
if (typeof ResizeObserver === 'function') {
compareObserver = new ResizeObserver(sizeCompareCanvas);
compareObserver.observe(compareCanvas);
}
sizeCompareCanvas();
compareHudKey = '';
compareHud.addEventListener('click', onCompareHudClick);
compareHud.addEventListener('pointerdown', onCompareSliderDown);
if (compareLeft) loadCompareTexture(compareLeft);
if (compareRight) loadCompareTexture(compareRight);
return !!compareGL;
}
function timelineButtons() {
return [...document.querySelectorAll('button.aLPB6c')];
}
function panoidOf(btn) {
const style = btn.getAttribute('style') || '';
const match = style.match(/[?&]panoid=([^&]+)/);
return match ? decodeURIComponent(match[1]) : '';
}
function markTimelinePicks() {
for (const btn of timelineButtons()) {
const id = panoidOf(btn);
btn.classList.toggle('svt-pick-left', !!(compareLeft && id && id === compareLeft.panoId));
btn.classList.toggle('svt-pick-right', !!(compareRight && id && id === compareRight.panoId));
}
}
function scrollTimelinePano(panoId) {
const btn = timelineButtons().find((el) => panoidOf(el) === panoId);
btn?.scrollIntoView({block: 'nearest', inline: 'center', behavior: 'smooth'});
}
function sideIsLive(side) {
const date = side === 'left' ? compareLeft : compareRight;
if (date) return !!(compareCur && date.panoId === compareCur.panoId);
return side === 'right' && !!compareCur;
}
function noteCompareHold() {
for (const date of [compareLeft, compareRight]) {
if (!date || (compareCur && date.panoId === compareCur.panoId)) continue;
const entry = compareTex.get(date.panoId);
if (entry && entry.status === 'ready' && !entry.dead) compareHoldId = date.panoId;
}
}
function compareDateChoices() {
const map = new Map();
for (const date of [...(compareCur?.dates || []), ...(compareOther?.dates || []), ...(compareLeft?.dates || []), ...(compareRight?.dates || [])]) {
if (!date || !date.panoId) continue;
const prev = map.get(date.panoId);
if (!prev || compareMonthKey(date) > compareMonthKey(prev)) map.set(date.panoId, date);
}
return [...map.values()].sort((a, b) => compareMonthKey(b) - compareMonthKey(a));
}
// Left is the older picture when the timeline chooses the pair. A date menu
// or a walk keeps whichever side the user already put each picture on.
function setCompareSides() {
noteCompareHold();
const cur = compareCur;
const other = compareOther;
let left = null;
let right = null;
if (cur && other) {
if (compareMonthKey(other) <= compareMonthKey(cur)) {
left = other;
right = cur;
} else {
left = cur;
right = other;
}
}
compareLeft = left;
compareRight = right;
if (left) loadCompareTexture(left);
if (right) loadCompareTexture(right);
pruneCompareEntries();
compareHudKey = '';
compareDirty = true;
markTimelinePicks();
}
function writeOtherSide(info) {
const live = compareCur && compareCur.panoId;
compareOther = info || null;
compareNoOther = !info;
if (compareLeft && compareLeft.panoId !== live) compareLeft = info;
else if (compareRight && compareRight.panoId !== live) compareRight = info;
else if (!compareLeft) compareLeft = info;
else compareRight = info;
if (info) loadCompareTexture(info);
pruneCompareEntries();
compareHudKey = '';
compareDirty = true;
markTimelinePicks();
}
function adoptLivePano(info) {
const prev = compareCur && compareCur.panoId;
if (compareLeft && (compareLeft.panoId === info.panoId || compareLeft.panoId === prev)) compareLeft = info;
else if (compareRight && (compareRight.panoId === info.panoId || compareRight.panoId === prev)) compareRight = info;
compareCur = info;
compareHudKey = '';
compareDirty = true;
if (compareLeft && compareLeft.panoId === info.panoId) loadCompareTexture(info);
if (compareRight && compareRight.panoId === info.panoId) loadCompareTexture(info);
markTimelinePicks();
}
// The other side at the current spot: the picked date, or the closest one that exists
// here when the user has walked somewhere that was not photographed on that date.
async function refreshCompareOther(rev) {
const cur = compareCur;
const sideRev = compareSideRev;
if (!cur) return;
if (!compareTarget) {
compareOther = null;
compareNoOther = false;
setCompareSides();
return;
}
const goal = compareMonthKey(compareTarget);
let best = null;
let bestDist = Infinity;
for (const date of cur.dates) {
if (date.panoId === cur.panoId) continue;
const dist = Math.abs(compareMonthKey(date) - goal);
if (dist < bestDist) {
best = date;
bestDist = dist;
}
}
if (!best) {
if (rev !== compareRev || compareCur !== cur || sideRev !== compareSideRev) return;
compareHoldId = '';
writeOtherSide(null);
return;
}
noteCompareHold();
let info = compareOther && compareOther.panoId === best.panoId ? compareOther : null;
if (!info && compareLeft && compareLeft.panoId === best.panoId) info = compareLeft;
if (!info && compareRight && compareRight.panoId === best.panoId) info = compareRight;
if (!info) info = await describeComparePano(best.panoId);
if (rev !== compareRev || compareCur !== cur || sideRev !== compareSideRev) return;
writeOtherSide(info);
}
async function resolveCompareCurrent(id) {
const rev = compareRev;
compareResolving = id;
const info = await describeComparePano(id);
if (rev !== compareRev || compareResolving !== id) return;
compareResolving = '';
if (!info) {
compareFailed = {id, at: performance.now()};
return;
}
compareFailed = {id: '', at: 0};
adoptLivePano(info);
await refreshCompareOther(rev);
}
// Follow whatever panorama Google is showing, so walking around keeps the comparison.
function followCompareCurrent(now) {
if (now - compareFollowAt < 80) return;
compareFollowAt = now;
const params = extractParams(location.href);
const id = (params && params.panoId) || '';
compareUrlId = id;
if (!id || (compareCur && compareCur.panoId === id) || compareResolving === id) return;
if (compareFailed.id === id && now - compareFailed.at < 3000) return;
resolveCompareCurrent(id);
}
async function assignTimelinePano(panoId) {
if (!compareOn || !panoId) return;
if (compareCur && compareCur.panoId === panoId) return;
const rev = compareRev;
compareSideRev++;
const info = compareOther && compareOther.panoId === panoId ? compareOther : await describeComparePano(panoId);
if (!info || !compareOn || rev !== compareRev) return;
compareTarget = {year: info.year, month: info.month};
compareOther = info;
compareNoOther = false;
setCompareSides();
scrollTimelinePano(info.panoId);
scrollTimelinePano(compareCur && compareCur.panoId);
}
async function pickCompareDate(side, panoId) {
if (!compareOn || !panoId || (side !== 'left' && side !== 'right')) return;
const current = side === 'left' ? compareLeft : compareRight;
const other = side === 'left' ? compareRight : compareLeft;
if (current && current.panoId === panoId) {
compareDateMenu = '';
compareHudKey = '';
return;
}
if (other && other.panoId === panoId) return;
const rev = compareRev;
compareSideRev++;
compareDateMenu = '';
compareHudKey = '';
const wasLive = sideIsLive(side);
const info = await describeComparePano(panoId);
if (!info || !compareOn || rev !== compareRev) return;
noteCompareHold();
if (side === 'left') compareLeft = info;
else compareRight = info;
loadCompareTexture(info);
if (wasLive && (!compareCur || info.panoId !== compareCur.panoId)) {
if (other) compareTarget = {year: other.year, month: other.month};
compareOther = other || null;
streetViewMoveTo(info);
} else if (!wasLive) {
compareOther = info;
compareTarget = {year: info.year, month: info.month};
compareNoOther = false;
if (side === 'left' && !compareRight && compareCur) {
compareRight = compareCur;
loadCompareTexture(compareCur);
}
if (side === 'right' && !compareLeft && compareCur && compareCur.panoId !== info.panoId) {
compareLeft = compareCur;
loadCompareTexture(compareCur);
}
}
pruneCompareEntries();
compareDirty = true;
compareHudKey = '';
markTimelinePicks();
scrollTimelinePano(info.panoId);
renderCompareHud();
}
function onTimelinePointer(e) {
if (!compareOn) return;
const inDate = e.target.closest && e.target.closest('.svt-side');
if (compareDateMenu && !inDate && (e.type === 'pointerdown' || e.type === 'click')) {
compareDateMenu = '';
compareHudKey = '';
renderCompareHud();
}
const btn = e.target.closest && e.target.closest('button.aLPB6c');
if (!btn) return;
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
if (e.type !== 'pointerdown') return;
const now = Date.now();
if (now - comparePickAt < 350) return;
comparePickAt = now;
assignTimelinePano(panoidOf(btn));
}
function compareSideText(side) {
const date = side === 'left' ? compareLeft : compareRight;
if (date) return date.label;
if (side === 'right') return compareCur ? compareCur.label : '';
return compareNoOther ? 'No other date here' : 'Pick a date below';
}
function compareSideHtml(name) {
const date = name === 'left' ? compareLeft : compareRight;
const text = compareSideText(name);
const choices = compareDateChoices();
const open = compareDateMenu === name;
const latest = choices[0];
const selectedId = date ? date.panoId : (name === 'right' && compareCur ? compareCur.panoId : '');
const items = choices.map((choice) => {
const on = choice.panoId === selectedId;
const tag = latest && choice.panoId === latest.panoId ? 'Latest ' : '';
return `${compareLabel(choice)}${tag} `;
}).join('');
const canOpen = choices.length > 1;
return `
${text}
${canOpen ? ' ' : ''}
${open && canOpen ? `` : ''}
`;
}
function renderCompareHud() {
if (!compareHud) return;
const choices = compareDateChoices().map((date) => date.panoId).join(',');
const key = [
compareMode,
compareLeft ? compareLeft.panoId : '',
compareRight ? compareRight.panoId : '',
compareSideText('left'),
compareSideText('right'),
compareDateMenu,
choices,
].join('|');
if (key === compareHudKey) {
placeCompareChrome();
return;
}
compareHudKey = key;
compareDirty = true;
const modeBtn = (mode, label) => `${label} `;
compareHud.innerHTML = `
${compareAddress()}
${modeBtn('overlap', 'Overlap')}
${modeBtn('split', 'Split')}
×
${compareSideHtml('left')}
${compareSideHtml('right')}
`;
placeCompareChrome();
}
function compareChromeOffset() {
const now = performance.now();
if (now - compareOffsetAt < 400) return compareOffset;
compareOffsetAt = now;
const host = compareHud?.getBoundingClientRect();
const input = document.querySelector('#searchboxinput, input[name="q"]');
if (!host || !input) {
compareOffset = 16;
return compareOffset;
}
const below = input.getBoundingClientRect().bottom - host.top + 12;
compareOffset = Math.max(12, Math.min(110, Math.round(below)));
return compareOffset;
}
function placeCompareHudBox() {
if (!compareHud || !compareCanvas || !compareCanvas.parentElement) return;
const host = compareCanvas.parentElement.getBoundingClientRect();
compareHud.style.left = host.left + 'px';
compareHud.style.top = host.top + 'px';
compareHud.style.width = host.width + 'px';
compareHud.style.height = host.height + 'px';
}
function placeCompareChrome() {
if (!compareHud) return;
const offset = compareChromeOffset();
const topBar = compareHud.querySelector('.svt-top');
if (topBar) topBar.style.top = offset + 'px';
const dates = compareHud.querySelector('.svt-dates');
if (dates) dates.style.top = (offset + 46) + 'px';
const slider = compareHud.querySelector('#svt-slider');
const divider = compareHud.querySelector('#svt-divider');
const left = compareHud.querySelector('.svt-side.left');
const right = compareHud.querySelector('.svt-side.right');
if (!slider || !left || !right) return;
const both = !!(compareLeft && compareRight);
const leftPct = compareMode === 'overlap' && both ? compareRatio * 100 : 50;
left.style.width = leftPct + '%';
right.style.width = (100 - leftPct) + '%';
if (compareMode === 'overlap' && both) {
slider.style.display = 'block';
divider.style.display = 'none';
slider.style.left = `${compareRatio * 100}%`;
} else {
slider.style.display = 'none';
divider.style.display = both && compareMode === 'split' ? 'block' : 'none';
}
const picked = [compareLeft, compareRight].filter(Boolean);
const failed = picked.filter((d) => compareTex.get(d.panoId)?.status === 'error').map((d) => d.label);
const status = compareHud.querySelector('.svt-status');
if (status) {
let text = '';
if (failed.length) text = `Could not load ${failed.join(', ')}`;
else if (compareNoOther) text = 'No other imagery at this spot';
else if (!compareTarget) text = 'Pick a date from the timeline below';
else if (compareOther && compareTex.get(compareOther.panoId)?.status !== 'ready' && !(compareHoldId && compareTex.get(compareHoldId)?.status === 'ready')) text = 'Loading';
status.style.top = (offset + 90) + 'px';
status.textContent = text;
}
}
function onCompareHudClick(e) {
const pick = e.target.closest('[data-date]');
if (pick) {
e.preventDefault();
e.stopPropagation();
pickCompareDate(pick.dataset.side, pick.dataset.date);
return;
}
const dateBtn = e.target.closest('.svt-date');
if (dateBtn && !dateBtn.disabled) {
e.preventDefault();
e.stopPropagation();
const side = dateBtn.dataset.side;
compareDateMenu = compareDateMenu === side ? '' : side;
compareHudKey = '';
renderCompareHud();
return;
}
const mode = e.target.closest('[data-mode]');
if (mode) {
e.preventDefault();
e.stopPropagation();
compareMode = mode.dataset.mode;
compareDateMenu = '';
compareDirty = true;
compareHudKey = '';
renderCompareHud();
return;
}
if (e.target.closest('[data-close]')) {
e.preventDefault();
e.stopPropagation();
stopCompare();
return;
}
}
function onCompareSliderDown(e) {
const slider = e.target.closest('#svt-slider');
if (!slider || compareMode !== 'overlap' || !compareCanvas) return;
e.preventDefault();
e.stopPropagation();
slider.setPointerCapture(e.pointerId);
const move = (ev) => {
const rect = compareCanvas.getBoundingClientRect();
if (!rect.width) return;
compareRatio = Math.min(0.9, Math.max(0.1, (ev.clientX - rect.left) / rect.width));
compareDirty = true;
placeCompareChrome();
};
const up = () => {
slider.removeEventListener('pointermove', move);
slider.removeEventListener('pointerup', up);
slider.removeEventListener('pointercancel', up);
};
slider.addEventListener('pointermove', move);
slider.addEventListener('pointerup', up);
slider.addEventListener('pointercancel', up);
move(e);
}
// Tiles of `zoom` that intersect the (slightly enlarged) view frustum.
function compareViewTiles(entry, zoom, cam, tanH, tanV) {
const grid = compareGrid(entry, zoom);
const cy = Math.cos(cam.yaw);
const sy = Math.sin(cam.yaw);
const cp = Math.cos(cam.pitch);
const sp = Math.sin(cam.pitch);
const h0 = (entry.date.heading || 0) * Math.PI / 180;
const found = new Map();
const steps = 20;
const reach = 1.25;
for (let j = 0; j <= steps; j++) {
const ny = (j / steps * 2 - 1) * reach;
const y = ny * tanV;
const dy2 = y * cp - sp;
const dz2 = y * sp + cp;
for (let i = 0; i <= steps; i++) {
const nx = (i / steps * 2 - 1) * reach;
const x = nx * tanH;
const dx3 = x * cy + dz2 * sy;
const dz3 = -x * sy + dz2 * cy;
const az = Math.atan2(dx3, dz3);
const lat = Math.atan2(dy2, Math.hypot(dx3, dz3));
let u = (az - h0) / (Math.PI * 2) + 0.5;
u -= Math.floor(u);
const t = 0.5 + lat / Math.PI;
const col = Math.min(grid.cols - 1, Math.max(0, Math.floor(u * grid.width / COMPARE_TILE)));
const row = Math.min(grid.rows - 1, Math.max(0, Math.floor((1 - t) * grid.height / COMPARE_TILE)));
const key = row * 64 + col;
const r = nx * nx + ny * ny;
const prev = found.get(key);
if (!prev) found.set(key, {x: col, y: row, r});
else if (r < prev.r) prev.r = r;
}
}
return found;
}
function drawComparePano(entry, cam, tanH, tanV, viewH) {
const gl = compareGL;
if (!gl || !entry || entry.dead || entry.status !== 'ready') return;
const uniforms = compareUniforms;
// Pick the pyramid level whose texel density matches the screen (1 texel : 1 pixel).
const needTexels = (viewH / 2 / tanV) * Math.PI * 2;
let zoom = entry.zmax;
for (let k = 1; k <= entry.zmax; k++) {
if (entry.world.width * 2 ** (k - entry.zmax) >= needTexels) {
zoom = k;
break;
}
}
const visible = compareViewTiles(entry, zoom, cam, tanH, tanV);
const drawSet = new Map();
visible.forEach((v) => {
for (let z = zoom; z >= 1; z--) {
const shift = zoom - z;
const tile = compareTile(entry, z, v.x >> shift, v.y >> shift);
if (tile.state === 'ready') {
tile.used = compareDrawNo;
drawSet.set(tile.key, tile);
break;
}
if (shift <= 1) wantCompareTile(tile, v.r + shift * 0.3);
}
});
if (!drawSet.size) return;
const list = [...drawSet.values()].sort((a, b) => a.zoom - b.zoom);
gl.uniform2f(uniforms.tan, tanH, tanV);
gl.uniform1f(uniforms.h0, (entry.date.heading || 0) * Math.PI / 180);
let mesh = null;
for (const tile of list) {
const grid = compareGrid(entry, tile.zoom);
const want = tile.zoom >= 4 ? compareMeshes.fine : compareMeshes.coarse;
if (want !== mesh) {
mesh = want;
gl.bindBuffer(gl.ARRAY_BUFFER, mesh.vbo);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, mesh.ibo);
}
const u0 = tile.x * COMPARE_TILE / grid.width;
const u1 = Math.min(1, (tile.x + 1) * COMPARE_TILE / grid.width);
const t1 = 1 - tile.y * COMPARE_TILE / grid.height;
const t0 = 1 - Math.min(1, (tile.y + 1) * COMPARE_TILE / grid.height);
gl.uniform4f(uniforms.rect, u0, u1, t0, t1);
gl.uniform2f(uniforms.fill, (u1 - u0) * grid.width / COMPARE_TILE, (t1 - t0) * grid.height / COMPARE_TILE);
gl.bindTexture(gl.TEXTURE_2D, tile.tex);
gl.drawElements(gl.TRIANGLES, mesh.count, gl.UNSIGNED_SHORT, 0);
}
}
function drawCompare() {
const gl = compareGL;
const cam = compareCam;
if (!gl || !cam || !compareCanvas || gl.isContextLost()) return;
compareDrawNo++;
const w = compareCanvas.width;
const h = compareCanvas.height;
gl.useProgram(compareProgram);
gl.disable(gl.SCISSOR_TEST);
gl.viewport(0, 0, w, h);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.uniform4f(compareUniforms.rot, Math.cos(cam.yaw), Math.sin(cam.yaw), Math.cos(cam.pitch), Math.sin(cam.pitch));
const aspect = w / h;
// Google's fov (URL y, _.lm) is the vertical field of view. Horizontal extent is
// tan(fov/2) times the canvas aspect, which is also how far the view opens at min zoom.
const tanV = Math.tan(cam.fov / 2);
const tanHFull = tanV * aspect;
const liveId = compareCur && compareCur.panoId;
const paint = (entry, x, sw, tanH) => {
if (!entry || entry.dead || entry.status !== 'ready' || sw <= 0) return;
gl.enable(gl.SCISSOR_TEST);
gl.scissor(x, 0, sw, h);
if (compareMode === 'split') gl.viewport(x, 0, sw, h);
else gl.viewport(0, 0, w, h);
drawComparePano(entry, cam, tanH, tanV, h);
};
for (const side of ['left', 'right']) {
const date = side === 'left' ? compareLeft : compareRight;
const leftW = compareMode === 'split' ? Math.round(w / 2) : Math.round(w * compareRatio);
const x = side === 'left' ? 0 : leftW;
const sw = side === 'left' ? leftW : w - leftW;
const native = compareMode !== 'split' && date && liveId && date.panoId === liveId;
if (native) continue;
let entry = date && compareTex.get(date.panoId);
if (entry && entry.status === 'ready' && !entry.dead) {
if (!liveId || date.panoId !== liveId) compareHoldId = date.panoId;
} else if (compareHoldId) {
entry = compareTex.get(compareHoldId);
} else {
entry = null;
}
const tanH = compareMode === 'split' ? tanV * sw / h : tanHFull;
paint(entry, x, sw, tanH);
}
gl.disable(gl.SCISSOR_TEST);
gl.viewport(0, 0, w, h);
}
function compareSidesReady() {
const cur = compareCur;
if (!cur || !compareLeft || !compareRight || compareUrlId !== cur.panoId) return false;
if (compareLeft.panoId !== cur.panoId && compareRight.panoId !== cur.panoId) return false;
return [compareLeft, compareRight].every((date) => compareTex.get(date.panoId)?.status === 'ready');
}
function stepCompare(now) {
compareTex.forEach(refreshCompareEntry);
followCompareCurrent(now);
const ready = compareSidesReady();
if (ready !== compareShown) {
compareShown = ready;
compareDirty = true;
compareHudKey = '';
}
if (compareCanvas && compareCanvas.style.visibility !== 'visible') compareCanvas.style.visibility = 'visible';
const pose = readStreetViewPose();
if (pose) {
const key = pose.heading.toFixed(4) + '|' + pose.tilt.toFixed(4) + '|' + pose.fovDeg.toFixed(4);
if (key !== comparePoseKey) {
comparePoseKey = key;
compareDirty = true;
}
compareCam = pose;
}
if (uploadCompareTiles()) compareDirty = true;
pumpCompareQueue();
if (compareDirty && compareCam) {
compareDirty = false;
drawCompare();
}
}
function compareFrame(now) {
compareRaf = 0;
if (!compareOn) return;
if (ensureCompareLayers(false)) {
now = now || performance.now();
stepCompare(now);
if (now - compareUiAt > 200) {
compareUiAt = now;
ensureCompareLayers(true);
placeCompareHudBox();
syncTimelineSheet();
markTimelinePicks();
renderCompareHud();
}
}
compareRaf = requestAnimationFrame(compareFrame);
}
function hideComparePageChrome() {
if (compareChromeStyle) return;
compareChromeStyle = GM_addStyle(`
.tGgADf,
.C5SiJf,
.Owrmqf,
#omnibox-container {
display: none !important;
}
`);
}
function showComparePageChrome() {
if (!compareChromeStyle) return;
compareChromeStyle.remove();
compareChromeStyle = null;
}
let streetViewCtl = null;
let streetViewHooked = false;
let streetViewMissAt = 0;
let streetViewFlowClass = null;
let streetViewFlowMgr = null;
let streetViewFlowMgrView = null;
function pageWindow() {
return typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
}
function pageRoot() {
const root = pageWindow()._;
return root && typeof root === 'object' ? root : null;
}
function acceptStreetView(view) {
const root = pageRoot();
if (!view || !view.camera || typeof view.camera.get !== 'function' || !root || typeof root.im !== 'function') return false;
try {
const cam = view.camera.get();
const pov = cam && root.im(cam);
if (!pov || typeof pov.od !== 'function') return false;
} catch (e) {
return false;
}
streetViewCtl = view;
return true;
}
// The viewer already exists by the time this script can see window._. io() will not
// run again, so walk the objects the page already holds and keep the one whose camera
// matches the live panorama.
function findStreetView() {
if (streetViewCtl && acceptStreetView(streetViewCtl)) return streetViewCtl;
streetViewCtl = null;
if (performance.now() - streetViewMissAt < 400) return null;
const page = pageWindow();
const seen = new Set();
const queue = [];
if (page._) queue.push(page._);
queue.push(page);
let scanned = 0;
while (queue.length && scanned < 8000) {
const obj = queue.pop();
if (!obj || typeof obj !== 'object' || seen.has(obj) || obj.nodeType) continue;
seen.add(obj);
scanned++;
if (acceptStreetView(obj)) return streetViewCtl;
let keys;
try { keys = Object.keys(obj); } catch (e) { continue; }
const limit = Math.min(keys.length, 300);
for (let i = 0; i < limit; i++) {
let value;
try { value = obj[keys[i]]; } catch (e) { continue; }
if (!value || typeof value !== 'object' || value.nodeType || seen.has(value)) continue;
queue.push(value);
}
}
streetViewMissAt = performance.now();
return null;
}
function hookStreetView() {
if (streetViewHooked) return true;
const root = pageRoot();
if (!root) return false;
for (const key of Object.keys(root)) {
const Ctor = root[key];
const io = Ctor && Ctor.prototype && Ctor.prototype.io;
if (typeof io !== 'function') continue;
if (io.__svt) {
streetViewHooked = true;
return true;
}
const src = Function.prototype.toString.call(io);
if (!src.includes('this.camera') || !src.includes('.notify')) continue;
const wrapped = function (cam, flow) {
acceptStreetView(this);
return io.apply(this, arguments);
};
wrapped.__svt = true;
Ctor.prototype.io = wrapped;
streetViewHooked = true;
return true;
}
return false;
}
// moveTo() wants a real "flow" (Google's telemetry/lifecycle object). Its class is the
// one whose source mentions "beforedone"; its manager is the object with start(a, b, flow).
function findStreetViewFlowClass() {
if (streetViewFlowClass) return streetViewFlowClass;
const root = pageRoot();
if (!root) return null;
for (const key of Object.keys(root)) {
let fn;
try { fn = root[key]; } catch (e) { continue; }
if (typeof fn !== 'function' || !fn.prototype) continue;
const proto = fn.prototype;
if (typeof proto.isActive !== 'function' || typeof proto.tick !== 'function' || typeof proto.H !== 'function') continue;
try {
if (!/beforedone/.test(Function.prototype.toString.call(fn))) continue;
} catch (e) {
continue;
}
streetViewFlowClass = fn;
return fn;
}
return null;
}
function findStreetViewFlowManager(view) {
if (streetViewFlowMgr && streetViewFlowMgrView === view) return streetViewFlowMgr;
const seen = new Set();
const queue = [view];
let scanned = 0;
while (queue.length && scanned < 6000) {
const obj = queue.shift();
if (!obj || typeof obj !== 'object' || seen.has(obj) || obj.nodeType) continue;
seen.add(obj);
scanned++;
try {
if (obj !== view && typeof obj.start === 'function' && typeof obj.isActive === 'function' && obj.isActive.length >= 1 && !('tick' in obj)) {
streetViewFlowMgr = obj;
streetViewFlowMgrView = view;
return obj;
}
} catch (e) {}
let keys;
try { keys = Object.keys(obj); } catch (e) { continue; }
const limit = Math.min(keys.length, 200);
for (let i = 0; i < limit; i++) {
let value;
try { value = obj[keys[i]]; } catch (e) { continue; }
if (value && typeof value === 'object' && !value.nodeType && !seen.has(value)) queue.push(value);
}
}
return null;
}
// Walk to another panorama exactly the way Google's own timeline and arrows do:
// view.moveTo(camera, content, transition, flow). The camera is rebuilt from the live
// pose so heading, tilt and zoom carry over untouched.
function streetViewMoveTo(info) {
const view = findStreetView();
const Flow = findStreetViewFlowClass();
const mgr = view && findStreetViewFlowManager(view);
const pose = readStreetViewPose();
if (!view || !Flow || !mgr || !pose || typeof view.moveTo !== 'function' || !info || typeof info.lat !== 'number' || !info.raw || !info.raw.place) return false;
try {
const cam = view.camera.get();
const content = view.content.get();
if (!cam || !content) return false;
const size = [Math.max(1, Math.round(compareCanvas?.clientWidth || window.innerWidth)), Math.max(1, Math.round(compareCanvas?.clientHeight || window.innerHeight))];
const aim = () => [[3, info.lng, info.lat], [pose.heading, pose.tilt], size.slice(), pose.fovDeg];
const place = info.raw.place;
const stamp = info.raw.stamp;
const inner = [
null,
[info.type === 10 ? 10 : 2, info.panoId],
null,
[null, null, info.raw.name ? [info.raw.name] : null],
null,
[[[1], [place[0], place[1], place[2]]]],
[null, null, null, null, null, null, null, stamp || null],
];
const entry = new Array(22).fill(null);
entry[0] = info.panoId;
entry[1] = 0;
entry[8] = aim();
entry[21] = inner;
const target = new content.constructor([1, null, null, null, entry]);
const camera = new cam.constructor(aim());
const flow = new Flow(mgr, 'pane.svt');
try { flow.H('show_pano', 'show_pano'); } catch (e) {}
return view.moveTo(camera, target, null, flow) !== false;
} catch (e) {
console.warn('Street View move failed', e);
return false;
}
}
function startCompare() {
compareOn = true;
compareRev++;
compareMode = 'overlap';
compareRatio = 0.5;
compareCur = null;
compareOther = null;
compareTarget = null;
compareResolving = '';
compareFailed = {id: '', at: 0};
compareNoOther = false;
compareFollowAt = 0;
compareUrlId = '';
compareShown = false;
comparePoseKey = '';
compareDateMenu = '';
compareHoldId = '';
compareSideRev = 0;
compareLeft = null;
compareRight = null;
compareHudKey = '';
disposeAllCompareEntries();
compareCam = null;
compareDirty = true;
syncCompareButton();
document.addEventListener('pointerdown', onTimelinePointer, true);
document.addEventListener('click', onTimelinePointer, true);
if (!ensureCompareLayers()) {
compareOn = false;
document.removeEventListener('pointerdown', onTimelinePointer, true);
document.removeEventListener('click', onTimelinePointer, true);
syncCompareButton();
showComparePageChrome();
Swal.fire({
title: 'This browser cannot show the comparison',
timer: 1600,
showConfirmButton: false,
allowOutsideClick: true,
backdrop: null,
customClass: {popup: 'swal-small-popup'},
});
return;
}
hideComparePageChrome();
mountCompareButton();
renderCompareHud();
markTimelinePicks();
if (!compareRaf) compareRaf = requestAnimationFrame(compareFrame);
}
function stopCompare() {
// Nothing to hand back: the camera was Google's all along, so leaving compare mode
// only removes our layers.
compareOn = false;
compareRev++;
compareCur = null;
compareOther = null;
compareTarget = null;
compareResolving = '';
compareNoOther = false;
compareShown = false;
compareLeft = null;
compareRight = null;
compareSheetCollapsed = false;
syncTimelineSheet();
document.getElementById('svt-sheet-btn')?.remove();
layoutCompareTabs();
if (compareRaf) cancelAnimationFrame(compareRaf);
compareRaf = 0;
document.removeEventListener('pointerdown', onTimelinePointer, true);
document.removeEventListener('click', onTimelinePointer, true);
document.querySelectorAll('button.aLPB6c.svt-pick-left, button.aLPB6c.svt-pick-right').forEach((btn) => {
btn.classList.remove('svt-pick-left', 'svt-pick-right');
});
disposeAllCompareEntries();
compareObserver?.disconnect();
compareObserver = null;
compareCam = null;
compareCanvas?.remove();
compareHud?.remove();
compareCanvas = null;
compareHud = null;
compareGL = null;
compareProgram = null;
compareMeshes = null;
compareUniforms = null;
showComparePageChrome();
syncCompareButton();
}
function toggleCompare() {
if (compareOn) {
stopCompare();
return;
}
const params = extractParams(location.href);
if (!params || !params.panoId) {
Swal.fire({
title: 'Open Street View first',
timer: 1400,
showConfirmButton: false,
allowOutsideClick: true,
backdrop: null,
customClass: {popup: 'swal-small-popup'},
});
return;
}
if (!timelineButtons().length) {
Swal.fire({
title: 'No timeline to compare',
timer: 1600,
showConfirmButton: false,
allowOutsideClick: true,
backdrop: null,
customClass: {popup: 'swal-small-popup'},
});
return;
}
startCompare();
}
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();
mountCompareButton();
} else {
document.getElementById('mwstmm-main')?.remove();
document.getElementById('note-btn')?.remove();
document.getElementById('settings-btn')?.remove();
document.getElementById('svt-compare-btn')?.remove();
document.getElementById('svt-sheet-btn')?.remove();
if (compareOn) stopCompare();
}
});
sceneFooterObserver.observe(sceneFooter, {
childList: true,
subtree: true,
attributes: true,
});
});
}
let streetViewHookTries = 0;
const streetViewHookTimer = setInterval(() => {
streetViewHookTries++;
hookStreetView();
if (findStreetView() || streetViewHookTries > 600) clearInterval(streetViewHookTimer);
}, 250);
if (!pageLoaded) {
window.addEventListener('load', onPageLoad);
setInterval(async () => {
hookStreetView();
if (!streetViewCtl) findStreetView();
const result = extractParams(window.location.href);
if (result && result.panoId) {
if(!document.getElementById('note-btn')) return;
mountCompareButton();
if( currentPano !== result.panoId){
const provider = document.querySelector('[jsaction^="titlecard.attributionClick"]')?.href;
if(!provider) return;
panoType = provider?.slice(29).startsWith('v') ? 2: 10;
currentPano = result.panoId;
await getLOCATION(result);
if(LOCATION && LOCATION)updateAltitudeNGeneration();
if (compareOn) markTimelinePicks();
}
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.key === 'Escape' && compareOn) {
e.preventDefault();
e.stopImmediatePropagation();
stopCompare();
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()
}
}
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: 16px !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;
}
#svt-compare-btn.zmX2Df {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 27px;
margin: 0 4px 0 0;
padding: 0;
color: #fff;
cursor: pointer;
}
#svt-compare-btn.zmX2Df[aria-pressed="true"] {
background: #fff;
color: #202124;
}
#svt-compare-view {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
z-index: 1;
pointer-events: none;
background: transparent;
user-select: none;
-webkit-user-select: none;
}
#svt-compare-hud {
position: fixed;
z-index: 1000000;
pointer-events: none;
font-family: Roboto, Arial, sans-serif;
color: #fff;
}
#svt-compare-hud .svt-top {
position: absolute;
left: 0;
right: 0;
top: 12px;
display: flex;
align-items: center;
gap: 8px;
padding: 0 12px;
box-sizing: border-box;
}
#svt-compare-hud .svt-address {
max-width: calc(50% - 90px);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 15px;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0,0,0,.85), 0 0 8px rgba(0,0,0,.45);
}
#svt-compare-hud .svt-modes {
pointer-events: auto;
position: absolute;
left: 50%;
top: 0;
transform: translateX(-50%);
display: flex;
height: 38px;
padding: 2px;
border-radius: 19px;
background: rgba(0,0,0,.6);
box-sizing: border-box;
}
#svt-compare-hud .svt-modes button {
border: 0;
background: transparent;
color: #fff;
height: 34px;
min-width: 58px;
padding: 0 14px;
border-radius: 17px;
font-size: 14px;
cursor: pointer;
}
#svt-compare-hud .svt-modes button.on {
background: #fff;
color: #1a73e8;
font-weight: 600;
}
#svt-compare-hud .svt-dates {
position: absolute;
left: 0;
right: 0;
top: 58px;
display: flex;
height: 40px;
}
#svt-compare-hud .svt-side {
position: relative;
display: flex;
align-items: flex-start;
justify-content: center;
min-width: 0;
}
#svt-compare-hud .svt-date {
pointer-events: auto;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
max-width: calc(100% - 28px);
height: 36px;
margin: 0;
padding: 0 10px 0 14px;
border: 0;
border-radius: 8px;
background: rgba(0,0,0,.55);
color: #fff;
font-size: 14px;
line-height: 36px;
cursor: pointer;
}
#svt-compare-hud .svt-date span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#svt-compare-hud .svt-date svg {
width: 16px;
height: 16px;
flex: none;
}
#svt-compare-hud .svt-side.is-open .svt-date svg {
transform: rotate(180deg);
}
#svt-compare-hud .svt-date:disabled {
cursor: default;
padding-right: 14px;
}
#svt-compare-hud .svt-side.is-empty .svt-date {
opacity: .85;
}
#svt-compare-hud .svt-date-menu {
pointer-events: auto;
position: absolute;
top: 42px;
left: 50%;
transform: translateX(-50%);
min-width: 168px;
max-height: 280px;
margin: 0;
padding: 6px;
overflow: auto;
list-style: none;
border-radius: 10px;
background: rgba(32,33,36,.94);
box-shadow: 0 8px 24px rgba(0,0,0,.35);
z-index: 3;
}
#svt-compare-hud .svt-date-menu button {
pointer-events: auto;
display: flex;
width: 100%;
align-items: center;
justify-content: space-between;
gap: 16px;
height: 32px;
margin: 0;
padding: 0 10px;
border: 0;
border-radius: 6px;
background: transparent;
color: #fff;
font-size: 13px;
white-space: nowrap;
cursor: pointer;
}
#svt-compare-hud .svt-date-menu button.on,
#svt-compare-hud .svt-date-menu button:hover {
background: rgba(255,255,255,.14);
}
#svt-compare-hud .svt-date-menu i {
font-style: normal;
color: #9aa0a6;
font-size: 12px;
}
button.aLPB6c.svt-pick-left,
button.aLPB6c.svt-pick-right {
position: relative;
box-shadow: inset 0 0 0 3px #1a73e8;
}
button.aLPB6c.svt-pick-right {
box-shadow: inset 0 0 0 3px #f9ab00;
}
button.aLPB6c.svt-pick-left .e7mild,
button.aLPB6c.svt-pick-right .e7mild {
position: absolute;
inset: 0;
pointer-events: none;
}
button.aLPB6c.svt-pick-left .e7mild::after,
button.aLPB6c.svt-pick-right .e7mild::after {
position: absolute;
left: 6px;
top: 6px;
min-width: 18px;
height: 18px;
padding: 0 4px;
border-radius: 9px;
background: #1a73e8;
color: #fff;
font-size: 12px;
line-height: 18px;
text-align: center;
}
button.aLPB6c.svt-pick-left .e7mild::after { content: "L"; }
button.aLPB6c.svt-pick-right .e7mild::after { content: "R"; background: #e37400; }
#svt-compare-hud .svt-x {
pointer-events: auto;
width: 36px;
height: 36px;
border: 0;
border-radius: 50%;
background: rgba(32,33,36,.55);
color: #fff;
font-size: 22px;
line-height: 36px;
cursor: pointer;
}
#svt-slider {
position: absolute;
top: 0;
bottom: 0;
width: 28px;
transform: translateX(-50%);
pointer-events: none;
cursor: ew-resize;
touch-action: none;
}
#svt-slider .svt-handle {
pointer-events: auto;
}
#svt-slider::before {
content: "";
position: absolute;
left: 50%;
top: 0;
bottom: 0;
width: 2px;
transform: translateX(-50%);
background: #fff;
box-shadow: 0 0 4px rgba(0,0,0,.45);
}
#svt-slider .svt-handle {
position: absolute;
top: 42%;
left: 50%;
width: 36px;
height: 36px;
transform: translate(-50%, -50%);
border-radius: 18px;
background: #fff;
box-shadow: 0 1px 6px rgba(0,0,0,.35);
}
#svt-slider .svt-handle::before,
#svt-slider .svt-handle::after {
content: "";
position: absolute;
top: 13px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
}
#svt-slider .svt-handle::before {
left: 8px;
border-right: 6px solid #5f6368;
}
#svt-slider .svt-handle::after {
right: 8px;
border-left: 6px solid #5f6368;
}
#svt-divider {
display: none;
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 2px;
transform: translateX(-50%);
background: rgba(255,255,255,.9);
box-shadow: 0 0 4px rgba(0,0,0,.4);
pointer-events: none;
}
#svt-compare-hud .svt-status {
position: absolute;
left: 50%;
top: 92px;
transform: translateX(-50%);
font-size: 13px;
text-shadow: 0 1px 2px rgba(0,0,0,.8);
pointer-events: none;
}
`);
})();