// ==UserScript==
// @name 百度街景助手 - 下载全景
// @namespace https://greasyfork.org/users/1179204
// @description 增强百度街景使用体验,支持下载全景
// @version 1.3.9
// @author KaKa
// @license MIT
// @include *://map.baidu.com/*
// @tag 百度,街景,下载,全景,增强
// @icon https://www.google.com/s2/favicons?sz=64&domain=map.baidu.com
// @require https://cdn.jsdelivr.net/npm/sweetalert2@11
// @require https://unpkg.com/gcoord/dist/gcoord.global.prod.js
// @grant GM_addStyle
// @grant GM_download
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @connect j.map.baidu.com
// @connect ditu.amap.com
// ==/UserScript==
(function() {
'use strict';
const isZh = navigator.language.toLowerCase().startsWith('zh');
const originalGetContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function(type, options) {
if (type === "webgl" || type === "webgl2") {
options = {...options, preserveDrawingBuffer: true};
}
return originalGetContext.call(this, type, options);
};
const i18n = {
attribution : isZh ? '百度街景' : 'Baidu Panorama',
download: isZh ? '下载' : 'Download',
copyShortlink: isZh ? '复制短链' : 'Copy Shortlink',
seeMoreDates: isZh ? '查看更多日期' : 'See more dates',
downloading: isZh ? '下载中...' : 'Downloading...',
downloadSuccess: isZh ? '下载完成 ✔️' : 'Download Completed ✔️',
downloadError: isZh ? '下载失败 ❌' : 'Error Downloading ❌',
copySuccess: isZh ? '复制成功 ✔️' : 'Copy Succeeded ✔️',
copyError: isZh ? '复制失败 ❌' : 'Failed to Copy! ❌',
generateError: isZh ? '生成失败 ❌' : 'Error Generating ❌',
shortlinkFail: isZh ? '短链生成失败 ❌' : 'Failed to generate short link! ❌',
unknown: isZh ? '未知' : 'Unknown',
};
const pinSvg = ``
const copySvg = ``
const downloadSvg =``
const cameraSvg = ``
const MONTHS_NAME = ['January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December'];
const months_name = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const addressCache = new Map();
const shortLinkCache = new Map();
let currentPano = {};
let currentAddress;
let compassControl;
let viewer;
let isAnimating;
let animationTimestamp;
let lastHeading = 0;
function debounce(fn, delay) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
function getPanoDate(){
if(!currentPano) return null;
return `${currentPano.year}/${String(currentPano.month).padStart(2,'0')}/${String(currentPano.day).padStart(2,'0')} ${String(currentPano.hour).padStart(2,'0')}:${String(currentPano.min).padStart(2,'0')}:${String(currentPano.sec).padStart(2,'0')}`
}
async function getPanorama(id) {
const url = `https://mapsv0.bdimg.com/?qt=sdata&sid=${id}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Network error: ${response.status}`);
}
const data = await response.json();
if (data && data.content && data.content[0]) {
const meta = data.content[0];
if(meta.ID) return meta
} else {
throw new Error("Failed to retrieve Baidu panorama metadata.");
}
} catch (error) {
console.error("Error fetching panorama data:", error);
throw new Error("Request to Baidu panorama service failed.");
}
}
function extractSubProvince(addr) {
if(!addr) return null;
const parts = addr.split(",").map(s => s.trim());
const filtered = parts.filter(p => !/^\d+$/.test(p));
return filtered[filtered.length - 3];
}
async function getAddress_OSM() {
if (addressCache.has(currentPano.panoId)) {
return addressCache.get(currentPano.panoId);
}
const [lat, lng] = currentPano.location;
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();
data.address.subProvince = extractSubProvince(data.display_name)
addressCache.set(currentPano.panoId, data.address);
return data.address;
} catch (error) {
console.error("Error fetching address from OSM:", error);
return i18n.unknown;
}
}
async function getAddress_AMap() {
if (addressCache.has(currentPano.panoId)) {
return addressCache.get(currentPano.panoId);
}
const [lat, lng] = currentPano.location;
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: `https://ditu.amap.com/service/regeo?longitude=${lng}&latitude=${lat}`,
headers: {
"Accept": "application/json"
},
onload: function (res) {
try {
const data = JSON.parse(res.responseText);
if (data.data && data.data?.result === "true") {
addressCache.set(currentPano.panoId, data.data);
resolve(data.data);
}
resolve(null);
} catch (err) {
reject(err);
}
},
onerror: function (err) {
console.error("Error fetching address:", err);
reject(err);
},
timeout: 10000
});
});
}
const debouncedFetchAddress = debounce(async () => {
currentAddress = isZh ? await getAddress_AMap() : await getAddress_OSM();
if (currentAddress) renderInfoPanel();
}, 800);
function formatAddress(address) {
if (!address) return null;
const parts = [
address.city || address.subcity || address.district || address.town || address.village || address.suburb || address.quarter,
address.subProvince || address.city,
address.state || address.province || address.region
];
return isZh ? address.desc :parts.filter(Boolean).join(', ');
}
function parseMetadata(data){
if (data){
currentPano.panoId = data.ID;
currentPano.timeline = data.TimeLine;
currentPano.year = Number(data.Date.slice(0, 4));
currentPano.month = Number(data.Date.slice(4, 6));
currentPano.day = Number(data.Date.slice(6, 8));
currentPano.hour = parseInt(data.ID.substring(16, 18));
currentPano.min = parseInt(data.ID.substring(18, 20));
currentPano.sec = parseInt(data.ID.substring(20, 22));
currentPano.originHeading = data.Heading;
currentPano.originPitch = data.Pitch;
currentPano.links = data.Links;
currentPano.altitude = data.Z;
currentPano.procdate = data.procdate;
currentPano.road = data.Rname === '未知道路' ? null : data.Rname;
currentPano.X = data.X;
currentPano.Y = data.Y;
currentPano.location = gcoord.transform([data.X / 100, data.Y / 100], gcoord.BD09MC, isZh? gcoord.GCJ02 : gcoord.WGS84).reverse();
}
}
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 coverCrop( srcW, srcH, dstW, dstH ) {
const scale = Math.max(
dstW / srcW,
dstH / srcH
);
const sw = dstW / scale;
const sh = dstH / scale;
return {
sx: (srcW - sw) / 2,
sy: (srcH - sh) / 2,
sw,
sh,
};
}
function drawScaled(source, width, height) {
const {sx, sy, sw, sh} = coverCrop(
source.width,
source.height,
width,
height
);
const out = document.createElement("canvas");
out.width = width;
out.height = height;
const ctx = out.getContext("2d");
if (!ctx) return null;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
ctx.drawImage(
source,
sx,
sy,
sw,
sh,
0,
0,
width,
height
);
return out;
}
function canvasToBlob(canvas, type = "image/png",quality) {
return new Promise(
(resolve, reject) => {
canvas.toBlob(
blob => {
if (blob) {
resolve(blob);
} else {
reject(new Error("Canvas encoding failed"));
}
},
type,
quality
);
}
);
}
async function copyImage(blob) {
if (
navigator.clipboard &&
window.ClipboardItem
) {
await navigator.clipboard.write([
new ClipboardItem({
"image/png": blob,
}),
]);
return true;
}
throw new Error(
"Clipboard image is not supported"
);
}
function renderPanoView() {
try {
const canvas= document.querySelectorAll('canvas')?.[1];
const scaled = drawScaled(
canvas,
canvas.width,
canvas.height
);
if (!scaled) throw new Error("Could not create output canvas");
return scaled;
} catch(err) {
throw new Error("Error taking panroama screenshot: ",err)
}
}
async function downloadPano(fileName) {
return new Promise(async (resolve, reject) => {
try {
let canvas, ctx, tilesPerRow, tilesPerColumn, tileUrl, imageUrl;
const tileWidth = 512;
const tileHeight = 512;
tilesPerRow = 16;
tilesPerColumn = 8;
canvas = document.createElement('canvas');
ctx = canvas.getContext('2d');
canvas.width = tilesPerRow * tileWidth;
canvas.height = tilesPerColumn * tileHeight;
const loadTile = (x, y) => {
return new Promise(async (resolveTile) => {
let tile;
tileUrl = `https://mapsv0.bdimg.com/?qt=pdata&sid=${currentPano.panoId}&pos=${y}_${x}&z=5`;
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: i18n.downloadSuccess,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: {
popup: "swal-small-popup"
}})
} catch (error) {
Swal.fire({
title: i18n.downloadError,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: {
popup: "swal-small-popup"
}})
reject(error);
}
});
}
function toggleHistoryPanoSelector(){
if(!currentPano) return;
document.getElementById('pano-fold-btn').click()
}
function formatTimelineLabel(tl) {
const year = tl.TimeLine.slice(0, 4);
const month = parseInt(tl.TimeLine.slice(4, 6), 10);
const monthName = months_name[month - 1]; // MONTHS_NAME 已定义
return `${monthName} ${year}`;
}
function getCompassSvg() {
return `
`;
}
function createCompass() {
compassControl = document.createElement('div');
compassControl.id = 'custom-compass';
compassControl.innerHTML = `
`;
document.body.appendChild(compassControl)
const svg = `
`;
const src ='data:image/svg+xml;charset=utf-8,' +encodeURIComponent(svg);
compassControl.querySelector('.compass-indicator').src = src;
compassControl.addEventListener('click', animatePovNorth);
}
function resetHistoryPanoSelector(){
if(!currentPano || !currentPano.timeline) return;
const timeline = currentPano.timeline;
const oldSelector= document.querySelector('.panoAlbum-wraper');
if(oldSelector) oldSelector.style.display = 'none'
let newSelector = document.getElementById('custom-panoAlbum-wraper');
if(!newSelector){
const container = document.querySelector('.panoAlbum-container');
if(container) {
newSelector = document.createElement('div');
newSelector.id = 'custom-panoAlbum-wraper';
newSelector.className = 'panoAlbum-wraper';
newSelector.style.width ='3296px';
newSelector.style.zIndex = 1;
container.appendChild(newSelector);
}
}
else newSelector.innerHTML = '';
timeline.forEach((tl, idx) => {
const src = `//mapsv0.bdimg.com/?qt=pr3d&fovy=90&quality=90&panoid=${tl.ID}&heading=${currentPano.heading}&pitch=${currentPano.pitch}&width=198&height=108&from=PC`;
const labelText = formatTimelineLabel(tl);
const li = document.createElement('li');
li.className = 'panoAlbum-item custom-pano-item';
li.setAttribute('index', idx);
li.style.width = '198px';
li.style.height = '108px';
li.style.left = (idx * 206) + 'px';
li.index = String(idx)
li.innerHTML = `
${labelText}
`;
li.addEventListener('click', (e) => {
e.stopImmediatePropagation();
clickTimelineItem(tl.ID);
});
newSelector.appendChild(li);
});
}
function clickTimelineItem(panoId) {
const list = document.querySelector('.timethrough-list');
if (!list) return;
const target = list.querySelector(`a[data-pid="${panoId}"]`);
if (!target) return;
target.click();
}
function updateCompass(heading) {
const needle = document.querySelector('.compass-indicator');
if (!needle || heading == null || isNaN(heading)) return;
const current = ((lastHeading % 360) + 360) % 360;
let delta = heading - current;
if (delta > 180) delta -= 360;
if (delta < -180) delta += 360;
lastHeading += delta;
needle.style.transform = `rotate(${-lastHeading}deg)`;
}
function updateThumbnails() {
if (!currentPano || !currentPano.timeline) return;
const selector = document.getElementById('custom-panoAlbum-wraper');
if (!selector) return;
const panoItems = selector.querySelectorAll('.panoAlbum-item');
const timeline = currentPano.timeline;
timeline.forEach((tl, idx) => {
if (idx >= panoItems.length) return;
const src = `//mapsv0.bdimg.com/?qt=pr3d&fovy=90&quality=90&panoid=${tl.ID}&heading=${currentPano.heading}&pitch=${currentPano.pitch}&width=198&height=108&from=PC`;
const labelText = formatTimelineLabel(tl);
const item = panoItems[idx];
const img = item.querySelector('img');
if (img) img.src = src;
});
}
function animatePovNorth() {
if(!viewer) return;
const startTime = Date.now();
animationTimestamp = startTime;
const currentPov = viewer.getPov();
const currentZoom = viewer.getZoom();
const isHeadingZero = currentPov.heading % 360 === 0 || isAnimating;
const targetPov = {
heading: 0,
pitch: isHeadingZero ? 20 : 0,
};
if (Math.abs(targetPov.heading - currentPov.heading) > 180) {
targetPov.heading += 360;
}
const transitionDuration = 4 * Math.max(Math.abs(targetPov.heading - currentPov.heading), 100);
let previousTimestamp = null;
function updatePov(timestamp) {
if (animationTimestamp !== startTime) return;
if (!previousTimestamp) previousTimestamp = timestamp;
const progress = Math.min((timestamp - previousTimestamp) / transitionDuration, 1);
const easing = 1 - Math.pow(1 - progress, 3);
const newHeading = currentPov.heading + (targetPov.heading - currentPov.heading) * easing;
const newPitch = currentPov.pitch + (targetPov.pitch - currentPov.pitch) * easing;
viewer.setPov( newHeading, newPitch);
viewer.setZoom(currentZoom + (0 - currentZoom) * easing);
if (progress < 1) {
requestAnimationFrame(updatePov);
} else {
isAnimating = false;
}
}
isAnimating = true;
requestAnimationFrame(updatePov);
}
function updateFooterInfo(){
let altitudeControl = document.getElementById("altitude-control");
let coordinateControl = document.getElementById("coordinate-control");
let procdateControl = document.getElementById("procdate-control");
if(!altitudeControl && !coordinateControl && !procdateControl){
altitudeControl = document.createElement("span");
procdateControl = document.createElement("span");
coordinateControl = document.createElement("a");
altitudeControl.id = "altitude-control";
procdateControl.id = "procdate-control";
coordinateControl.id = "coordinate-control";
coordinateControl.href = "javascript:void(0)";
coordinateControl.style.cursor = "pointer";
coordinateControl.style.marginLeft = "5px";
const container = document.getElementById('pano-copyright');
if(container){
const divider1 = document.createElement("span");
const divider2 = document.createElement("span");
const divider3 = document.createElement("span");
divider1.textContent = "|";
divider2.textContent = "|";
divider3.textContent = "|";
container.insertBefore(divider1, container.firstChild);
container.insertBefore(procdateControl, container.firstChild);
container.insertBefore(divider2, container.firstChild);
container.insertBefore(coordinateControl, container.firstChild);
container.insertBefore(divider3, container.firstChild);
container.insertBefore(altitudeControl, container.firstChild);
container.style.display = "flex";
container.style.alignItems = "center";
}
coordinateControl.onclick = () => {
const [lat, lng] = currentPano.location || [];
if(lat == null || lng == null) {
Swal.fire({
title: i18n.copyError,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: { popup: "swal-small-popup" }
});
return;
}
const coordText = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
GM_setClipboard(coordText, "text");
Swal.fire({
title: i18n.copySuccess,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: { popup:"swal-small-popup" }
});
};
}
if (currentPano.altitude && currentPano.location && currentPano.procdate) {
const [lat, lng] = currentPano.location;
coordinateControl.textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
altitudeControl.textContent = `${Math.round(currentPano.altitude * 100) / 100}m`;
procdateControl.textContent = `${currentPano.procdate.slice(0,4)}年${Number(currentPano.procdate.slice(4,6))}月${Number(currentPano.procdate.slice(6,8))}日发布`;
}
}
async function generateShortLink() {
if (shortLinkCache.has(currentPano.panoId)) {
return shortLinkCache.get(currentPano.panoId);
}
return new Promise((resolve, reject) => {
const params = new URLSearchParams(location.hash.slice(1));
const baseUrl = "https://map.baidu.com/?newmap=1&shareurl=1";
const panoId = params.get("panoid");
if(!panoId) resolve(null);
const pid = params.get("pid");
const panotype = params.get("panotype");
const heading = params.get("heading");
const pitch = params.get("pitch");
const zoom = params.get("l");
const tn = params.get("tn");
const sc = params.get("sc");
const fullUrl = `${baseUrl}`
+ (panoId ? `&panoid=${panoId}` : "")
+ (pid ? `&pid=${pid}` : "")
+ (panotype ? `&panotype=${panotype}` : "")
+ (heading ? `&heading=${heading}` : "")
+ (pitch ? `&pitch=${pitch}` : "")
+ (zoom ? `&l=${zoom}` : "")
+ (tn ? `&tn=${tn}` : "")
+ (sc ? `&sc=${sc}` : "");
const apiUrl = `https://j.map.baidu.com/?url=${encodeURIComponent(fullUrl)}&web=true&pcevaname=pc4.1&newfrom=zhuzhan_webmap`;
GM_xmlhttpRequest({
method: "GET",
url: apiUrl,
onload: function(response) {
try {
const data = JSON.parse(response.responseText);
if (data && data.url) {
shortLinkCache.set(currentPano.panoId, data.url);
resolve(data.url);
} else {
reject("No URL found in response.");
}
} catch (error) {
reject("Failed to parse response: " + error);
}
},
onerror: reject
});
});
}
async function generateUpdateReport() {
if(!currentPano) return;
//let position_word;
try{
const [shortLink, address] = await Promise.all([
generateShortLink(),
getAddress()
]);
/*if(currentPano.road){
position_word='on'
}
else position_word='in'*/
const reportParts = [
`:flag_cn:`,
'[Baidu]',
currentPano.timeline.length < 2 ?':newroad:' : '',
`${MONTHS_NAME[currentPano.month - 1]} ${currentPano.year}`,
`in ${formatAddress(address)}, China`,
shortLink || `https://map.baidu.com/?newmap=1&panotype=street&panoid=${currentPano.panoId}`
].filter(Boolean);
const reportText = reportParts.join(' ');
GM_setClipboard(reportText, 'text');
Swal.fire({
title: i18n.copySuccess,
timer:5000,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: {
popup:"swal-small-popup"
}
});
}
catch(e){
console.error('Error generating update report text: '+e)
Swal.fire({
title: i18n.generateError,
timer: 2000,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: {
popup: "swal-small-popup"
}})
}
}
async function getShortLink(){
const shortLink = await generateShortLink()
if(shortLink){
GM_setClipboard(shortLink, 'text');
Swal.fire({
title: i18n.copySuccess,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: {
popup: "swal-small-popup"
}
});
}
else{
Swal.fire({
title: i18n.shortlinkFail,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: {
popup: "swal-small-popup"
}
})
}
}
function renderInfoPanel() {
let oldPanel = document.querySelector('#pano-info-panel');
if (oldPanel) {
oldPanel.querySelector('.pano-title').textContent = currentPano.road || currentAddress.street || currentAddress.road || currentAddress.town || currentAddress.village ||currentAddress.road_list?.[0].name;
oldPanel.querySelector('.pano-sub').textContent = formatAddress(currentAddress);
oldPanel.querySelector('.pano-date').textContent = getPanoDate();
}
else{
const panel = document.createElement('div');
panel.id = 'pano-info-panel';
panel.innerHTML = `
${getPanoDate()}
${i18n.seeMoreDates}
`;
const container = document.querySelector('#pano-container') || document.body;
container.appendChild(panel);
panel.querySelector('.pano-download').addEventListener('click', () => {
Swal.fire({
title: i18n.downloading,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
allowEscapeKey: false,
didOpen: () => {
Swal.showLoading();
},
customClass: {
popup: "swal-small-popup"
}
});
downloadPano(`${currentPano.panoId}.jpg`);
});
panel.querySelector('.pano-screenshot').addEventListener('click', async (e) => {
try{
viewer.curPanorama.setTopoVisible(false);
const output = await renderPanoView();
const blob = await canvasToBlob(output);
const fileName = `${currentPano.year}-${currentPano.month}_${formatAddress(currentAddress)}.png`;
await copyImage(blob);
Swal.fire({
title: i18n.copySuccess,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: { popup:"swal-small-popup" }
});
}
catch(e){
Swal.fire({
title: i18n.copyError,
timer: 1500,
showConfirmButton: false,
allowOutsideClick:true,
backdrop:null,
customClass: { popup:"swal-small-popup" }
});
console.error('Error taking screenshot', e)
}
});
panel.querySelector('.pano-pin').addEventListener('click', async (e) => {
try{
document.getElementById('pano-return-btn').click();
map.panTo(new BMap.Point( currentPano.X/100, currentPano.Y/100));
map.setZoom(20);
}
catch(e){
}
});
panel.querySelector('.pano-shortlink').addEventListener('click', async () => {
getShortLink();
});
panel.querySelector('.pano-history').addEventListener('click', () => {
toggleHistoryPanoSelector();
});
}
}
const observer = new MutationObserver(async (mutations, obs) => {
const panoWrapper = document.getElementById('pano-flash-wrapper');
const container = document.querySelector('.panoAlbum-container');
if (panoWrapper && container && !compassControl) {
try{
for (const key in $BAIDU$._instances) {
if (key.startsWith("TANGRAM_")) {
const instance = $BAIDU$._instances[key];
if (instance && instance.panorama) {
document.getElementById('pano-return-btn')?.addEventListener('click', ()=>{
if (compassControl) compassControl.remove();
compassControl = null;
const oldPanel = document.getElementById('pano-info-panel') ;
if (oldPanel) oldPanel.remove();
})
instance.panorama.curPanorama.setTopoVisible = function(visbile) {
this.topoArrowContainer.setVisible(false);
};
viewer = instance.panorama;
if(!compassControl){
createCompass();
currentPano.heading = viewer.getPov().heading;
currentPano.pitch = viewer.getPov().pitch;
updateCompass(currentPano.heading);
const metadata= await getPanorama(viewer.curPanoId);
if (metadata) {
parseMetadata(metadata);
currentAddress = isZh ? await getAddress_AMap() : await getAddress_OSM();
if(currentAddress) renderInfoPanel();
resetHistoryPanoSelector();
updateFooterInfo();
}
}
viewer.addEventListener("loadPanoramaDataCompleted", (e) => {
const data = e.data?.content?.[0];
parseMetadata(data);
currentPano.heading =viewer.getPov().heading;
currentPano.pitch =viewer.getPov().pitch;
updateCompass(currentPano.heading);
debouncedFetchAddress();
if(currentAddress) renderInfoPanel();
resetHistoryPanoSelector();
updateFooterInfo();
});
viewer.addEventListener("povChanged", (e) => {
updateCompass(e.data.heading);
currentPano.heading = e.data.heading;
currentPano.pitch = e.data.pitch;
updateThumbnails();
});
break;
}
}
}
}
catch(e){
console.log(e)
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
let onKeyDown =async (e) => {
if (e.target.tagName === 'INPUT' ||e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) {
return;
}
if (!e.ctrlKey&&!e.metaKey&&(e.key.toLowerCase() === 'c')){
e.stopImmediatePropagation();
await getShortLink();
}
if (!e.ctrlKey&&!e.metaKey&&(e.key.toLowerCase() === 'n')){
e.stopImmediatePropagation();
animatePovNorth();
}
if (!e.ctrlKey&&!e.metaKey&&(e.key.toLowerCase() === 'v')) {
e.stopImmediatePropagation();
await generateUpdateReport();
}
}
document.addEventListener("keydown", onKeyDown);
GM_addStyle(`
#pano-container{
z-index: 1002 !important;
}
#pano-info-panel {
position: absolute;
top: 64px;
left: 16px;
width: 320px;
background: #202124;
color: #e8eaed;
font-family: Roboto, Arial, sans-serif;
border-radius: 12px;
padding: 16px 20px;
box-shadow: 0 4px 12px rgba(0,0,0,0.5);
z-index: 2147483647;
pointer-events: auto;
}
.pano-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
}
.pano-text {
flex: 1;
min-width: 0;
}
.pano-title {
font-size: 16px;
font-weight: 600;
color: #ffffff;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.pano-sub {
font-size: 13px;
color: #9aa0a6;
margin-top: 6px;
padding: 0;
}
.pano-sub,
.pano-title,
.pano-date {
user-select: text !important;
-webkit-user-select: text !important;
}
.pano-icons {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-left: 2px;
}
.pano-icon {
width: 25px;
height: 25px;
display: flex;
color: #ababab;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 50%;
}
.pano-icon:hover {
color: #fff;
}
.pano-pin:hover {
color: #f72e32
}
.pano-source {
color: #9aa0a6;
margin-bottom: 2px;
}
.pano-date {
color: #e8eaed;
font-weight: 500;
font-size: 13px;
}
.pano-divider {
height: 1px;
background: rgba(255,255,255,0.12);
margin: 10px 0px;
}
.pano-attribution {
display: flex;
align-items: center;
gap: 6px;
margin-top: 10px;
}
.pano-attribution-logo {
width: 18px;
height: 18px;
background-image: url("https://www.google.com/s2/favicons?sz=64&domain=map.baidu.com");
background-size: cover;
border-radius: 50%;
}
.pano-attribution-text {
font-size: 15px;
color: #8ab4f8;
text-decoration: none;
}
.pano-attribution-text:hover {
text-decoration: underline;
}
.pano-meta {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
}
.pano-history {
color: #8ab4f8;
cursor: pointer;
font-size: 12px;
}
.pano-history:hover {
text-decoration: underline;
}
#custom-compass {
position: absolute;
top: 12px;
right: 12px;
z-index: 9999;
}
.compass-wrapper {
display: flex;
}
.compass-btn {
width: 72px;
height: 72px;
border-radius: 50%;
background: #000000;
border: none;
cursor: default;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.compass-circle {
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(0,0,0,0.6);
}
.compass-indicator {
width: 16px;
height: 64px;
transition: transform 0.2s ease-out;
transform-origin: 50% 50%;
pointer-events: none;
}
.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;
z-index:1004 !important;
}`
)}
)();