// ==UserScript== // @name 百度街景助手 - 下载全景 // @namespace https://greasyfork.org/users/1179204 // @description 增强百度街景使用体验,支持下载全景、对比不同日期街景 // @version 1.4.0 // @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', // Info panel icons pinOnMap: isZh ? '在地图上定位' : 'Pin on map', downloadPanorama: isZh ? '下载全景图' : 'Download panorama', copyShortlink: isZh ? '复制短链' : 'Copy short link', copyScreenshot: isZh ? '复制当前视角截图' : 'Copy screenshot', seeMoreDates: isZh ? '查看更多日期' : 'See more dates', // Compare entry & modes compare: isZh ? '对比' : 'Compare', compareTitle: isZh ? '对比不同日期街景' : 'Compare capture dates', compareOn: isZh ? '退出街景对比' : 'Exit date compare', overlap: isZh ? '重叠' : 'Overlap', overlapTitle: isZh ? '重叠对比:拖动中间分隔线查看两侧' : 'Overlap: drag the divider to reveal each side', split: isZh ? '分割' : 'Split', splitTitle: isZh ? '左右分割对比' : 'Split view side by side', exitCompare: isZh ? '退出对比' : 'Exit compare', dragDivider: isZh ? '拖动分隔线' : 'Drag divider', pickDate: isZh ? '选择日期' : 'Pick a date', pickLeftDate: isZh ? '选择左侧日期' : 'Pick left date', pickRightDate: isZh ? '选择右侧日期' : 'Pick right date', leftSide: isZh ? '左侧' : 'Left', rightSide: isZh ? '右侧' : 'Right', latest: isZh ? '最近' : 'Latest', noOtherDate: isZh ? '此地点没有其它日期' : 'No other date here', needDates: isZh ? '至少需要两个拍摄日期' : 'At least two capture dates are needed', loadingCompare: isZh ? '加载对比画面…' : 'Loading comparison…', // Toasts download: isZh ? '下载' : 'Download', 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', published: (y, m, d) => (isZh ? `${y}年${Number(m)}月${Number(d)}日发布` : `Published ${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`), monthYear: (year, month) => (isZh ? `${year}年${month}月` : `${months_name[Math.max(0, (month || 1) - 1)]} ${year}`), }; 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 = i18n.published( currentPano.procdate.slice(0, 4), currentPano.procdate.slice(4, 6), 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 = `
${currentPano.road || currentAddress.street || currentAddress.road || currentAddress.town || currentAddress.village || currentAddress.road_list?.[0].name}
${formatAddress(currentAddress)}
${pinSvg}
${downloadSvg}
${cameraSvg}
${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 compareIcon = ``; let compareOn = false; let compareMode = 'overlap'; let compareRatio = 0.5; let compareLeft = null; let compareRight = null; let compareTarget = null; let compareLiveId = ''; let compareMenu = ''; let compareRev = 0; let compareSideRev = 0; let compareRaf = 0; let compareCanvas = null; let compareHud = null; let compareGL = null; let compareProgram = null; let compareUniforms = null; let compareMesh = null; let compareDirty = true; let compareCam = null; let compareHoldId = ''; let compareHudKey = ''; let compareInfo = new Map(); const compareTex = new Map(); function compareLabel(year, month) { if (!year) return i18n.unknown; return i18n.monthYear(year, month); } function compareMonth(info) { return info.year * 12 + ((info.month || 1) - 1); } function timelineEntries() { return (currentPano.timeline || []).map((tl) => { const stamp = String(tl.TimeLine || ''); const year = Number(stamp.slice(0, 4)) || Number(tl.Year) || 0; const month = Number(stamp.slice(4, 6)) || 1; return {id: tl.ID, year, month, label: compareLabel(year, month)}; }).filter((item) => item.id).sort((a, b) => compareMonth(b) - compareMonth(a)); } function infoFromMeta(meta) { const stamp = String(meta.Date || ''); const year = Number(stamp.slice(0, 4)) || 0; const month = Number(stamp.slice(4, 6)) || 1; return { id: meta.ID, heading: Number(meta.Heading) || 0, year, month, label: compareLabel(year, month), }; } async function ensureCompareInfo(id) { if (!id) return null; if (compareInfo.has(id)) return compareInfo.get(id); try { const meta = await getPanorama(id); const info = infoFromMeta(meta); compareInfo.set(id, info); return info; } catch (e) { return null; } } function baiduFovDeg(zoom) { if (viewer && viewer.isBillionPixels) { const table = [65, 45, 23, 10, 5, 2]; const index = Math.max(0, Math.min(table.length - 1, (zoom || 1) - 1)); return table[index]; } return 75 - ((zoom || 1) - 1) * 15; } // The page camera is the only camera. pitch > 0 looks up; the shader's positive pitch looks down. function readBaiduPose() { if (!viewer || typeof viewer.getPov !== 'function') return null; const pov = viewer.getPov(); const zoom = typeof viewer.getZoom === 'function' ? viewer.getZoom() : 1; const fovDeg = baiduFovDeg(zoom); if (!pov || !Number.isFinite(pov.heading) || !Number.isFinite(pov.pitch) || !(fovDeg > 1 && fovDeg < 170)) return null; return { yaw: pov.heading * Math.PI / 180, pitch: -pov.pitch * Math.PI / 180, fov: fovDeg * Math.PI / 180, heading: pov.heading, fovDeg, }; } function baiduGrid(level) { if (level <= 1) return {cols: 1, rows: 1}; return {cols: 2 ** (level - 1), rows: 2 ** (level - 2)}; } function baiduTileUrl(id, level, x, y) { return `https://mapsv0.bdimg.com/?qt=pdata&sid=${encodeURIComponent(id)}&pos=${y}_${x}&z=${level}&from=PC`; } function createCompareMesh(gl) { // Dense enough that polar tiles (y=0 / last row) do not collapse into a pie fan. const n = 48; 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; idx[k++] = a; idx[k++] = a + 1; idx[k++] = a + n + 1; idx[k++] = a + 1; idx[k++] = a + n + 2; idx[k++] = a + n + 1; } } 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}); if (!gl) return null; 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;', '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);}'; 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; compareMesh = createCompareMesh(gl); 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'), }; gl.bindBuffer(gl.ARRAY_BUFFER, compareMesh.vbo); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, compareMesh.ibo); return gl; } function compareTile(entry, level, x, y) { const grid = baiduGrid(level); x = Math.max(0, Math.min(grid.cols - 1, x)); y = Math.max(0, Math.min(grid.rows - 1, y)); const key = level + ':' + x + ':' + y; let tile = entry.tiles.get(key); if (tile) return tile; tile = {key, level, x, y, state: 'idle', tex: null, bitmap: null}; entry.tiles.set(key, tile); return tile; } function wantCompareTile(tile) { if (!tile || tile.state !== 'idle') return; tile.state = 'queued'; loadCompareTile(tile); } function loadCompareTile(tile) { const entry = tile.entry; const url = baiduTileUrl(entry.id, tile.level, tile.x, tile.y); fetch(url).then((res) => { if (!res.ok) throw new Error(String(res.status)); return res.blob(); }).then((blob) => createImageBitmap(blob)).then((bitmap) => { if (entry.dead) { bitmap.close?.(); return; } tile.bitmap = bitmap; tile.state = 'bitmap'; compareDirty = true; }).catch(() => { tile.state = 'error'; }); } function uploadCompareTile(gl, tile) { if (!tile.bitmap || tile.state !== 'bitmap') return; const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tile.bitmap); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, 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); tile.bitmap.close?.(); tile.bitmap = null; tile.tex = tex; tile.state = 'ready'; } function loadCompareTexture(info) { if (!info || !info.id) return null; const existing = compareTex.get(info.id); if (existing && !existing.dead) return existing; const entry = {id: info.id, heading: info.heading || 0, tiles: new Map(), dead: false, status: 'loading'}; compareTex.set(info.id, entry); for (const level of [2, 3]) { const grid = baiduGrid(level); for (let y = 0; y < grid.rows; y++) { for (let x = 0; x < grid.cols; x++) { const tile = compareTile(entry, level, x, y); tile.entry = entry; wantCompareTile(tile); } } } return entry; } function dropCompareTexture(id) { const entry = compareTex.get(id); if (!entry) return; entry.dead = true; entry.tiles.forEach((tile) => { if (tile.tex && compareGL) compareGL.deleteTexture(tile.tex); tile.bitmap?.close?.(); }); compareTex.delete(id); } function pruneCompareTextures() { const keep = new Set([compareLeft?.id, compareRight?.id, compareHoldId].filter(Boolean)); [...compareTex.keys()].forEach((id) => { if (!keep.has(id)) dropCompareTexture(id); }); } 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; } function ensureCompareLayers() { const street = document.querySelector('#pano-flash-wrapper canvas'); const host = street && street.parentElement; if (!host) return false; if (getComputedStyle(host).position === 'static') host.style.position = 'relative'; if (compareCanvas && compareCanvas.isConnected && compareGL && !compareGL.isContextLost()) return true; compareCanvas?.remove(); compareHud?.remove(); compareCanvas = document.createElement('canvas'); compareCanvas.id = 'svt-baidu-compare'; compareCanvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;z-index:2;pointer-events:none;background:transparent;'; host.appendChild(compareCanvas); compareHud = document.createElement('div'); compareHud.id = 'svt-baidu-hud'; document.body.appendChild(compareHud); compareHud.addEventListener('click', onCompareHudClick); compareHud.addEventListener('pointerdown', onCompareSliderDown); compareGL = initCompareGL(compareCanvas); sizeCompareCanvas(); window.addEventListener('resize', sizeCompareCanvas); if (compareLeft) loadCompareTexture(compareLeft); if (compareRight) loadCompareTexture(compareRight); compareHudKey = ''; return !!compareGL; } function compareLevel(cam, viewW, viewH) { const aspect = Math.max(viewW, 1) / Math.max(viewH, 1); const hFov = 2 * Math.atan(Math.tan(cam.fov / 2) * aspect); const need = viewW * Math.PI * 2 / Math.max(hFov, 0.3); let level = need > 6000 ? 5 : need > 3000 ? 4 : 3; const zoom = viewer && typeof viewer.getZoom === 'function' ? viewer.getZoom() : 1; const native = Math.min(5, Math.max(3, Math.round(zoom) + 3)); return Math.min(5, Math.max(level, native)); } // Baidu pdata u=0.5 faces Heading; shader az uses +Z as 0. Current (+90) was 180° off // the live canvas — use Heading - 90 so WebGL matches the native view. function imageHeading(heading) { return ((heading || 0) - 90) * Math.PI / 180; } function tilesInView(heading0, cam, tanH, tanV, level) { const grid = baiduGrid(level); const h0 = imageHeading(heading0); 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 found = []; const seen = new Set(); const steps = 10; for (let j = 0; j <= steps; j++) { const y = ((j / steps) * 2 - 1) * 1.25 * tanV; const dy2 = y * cp - sp; const dz2 = y * sp + cp; for (let i = 0; i <= steps; i++) { const x = ((i / steps) * 2 - 1) * 1.25 * tanH; const dx3 = x * cy + dz2 * sy; const dz3 = -x * sy + dz2 * cy; const az = Math.atan2(dx3, dz3); let u = (az - h0) / (Math.PI * 2) + 0.5; u -= Math.floor(u); const lat = Math.atan2(dy2, Math.hypot(dx3, dz3)); const t = 0.5 + lat / Math.PI; const col = Math.min(grid.cols - 1, Math.max(0, Math.floor(u * grid.cols))); const row = Math.min(grid.rows - 1, Math.max(0, Math.floor((1 - t) * grid.rows))); const key = col + ':' + row; if (seen.has(key)) continue; seen.add(key); found.push([col, row]); } } return found; } function drawComparePano(entry, cam, tanH, tanV, viewW, viewH) { const gl = compareGL; if (!gl || !entry || entry.dead) return false; const level = compareLevel(cam, viewW, viewH); const cells = tilesInView(entry.heading || 0, cam, tanH, tanV, level); let drew = false; gl.uniform1f(compareUniforms.h0, imageHeading(entry.heading || 0)); gl.uniform2f(compareUniforms.tan, tanH, tanV); const drawTile = (tile) => { const grid = baiduGrid(tile.level); const u0 = tile.x / grid.cols; const u1 = (tile.x + 1) / grid.cols; // Keep a hair off ±90° lat so the pole edge is not one shared vertex with // the whole tile width of UVs (that reads as a sky “pie chart”). const pole = 0.35 / Math.max(grid.rows * 48, 48); let t1 = 1 - tile.y / grid.rows; let t0 = 1 - (tile.y + 1) / grid.rows; if (tile.y === 0) t1 = Math.min(t1, 1 - pole); if (tile.y === grid.rows - 1) t0 = Math.max(t0, pole); gl.uniform4f(compareUniforms.rect, u0, u1, t0, t1); gl.uniform2f(compareUniforms.fill, 1, 1); gl.bindTexture(gl.TEXTURE_2D, tile.tex); gl.drawElements(gl.TRIANGLES, compareMesh.count, gl.UNSIGNED_SHORT, 0); }; for (const [x, y] of cells) { let tile = compareTile(entry, level, x, y); tile.entry = entry; wantCompareTile(tile); let use = tile; let shift = 0; // Level 2 is a single vertical strip (rows=1); using it near the zenith // warps a whole hemisphere into a pie. Stop fallback at level 3. while (use.state !== 'ready' && use.level > 3) { if (use.state === 'bitmap') uploadCompareTile(gl, use); if (use.state === 'ready') break; shift++; use = compareTile(entry, use.level - 1, x >> shift, y >> shift); use.entry = entry; wantCompareTile(use); } if (use.state === 'bitmap') uploadCompareTile(gl, use); if (use.state !== 'ready') continue; drawTile(use); drew = true; } if (drew && entry.id !== compareLiveId) compareHoldId = entry.id; return drew; } function paintCompareSide(info, x, sw, w, h, tanV) { if (!info || sw <= 0) return; const native = compareMode !== 'split' && info.id === compareLiveId; if (native) return; let entry = compareTex.get(info.id); if (!entry || entry.dead) entry = compareHoldId ? compareTex.get(compareHoldId) : null; if (!entry) return; const gl = compareGL; gl.enable(gl.SCISSOR_TEST); gl.scissor(x, 0, sw, h); const tanH = compareMode === 'split' ? tanV * sw / h : tanV * (w / h); if (compareMode === 'split') gl.viewport(x, 0, sw, h); else gl.viewport(0, 0, w, h); drawComparePano(entry, compareCam, tanH, tanV, compareMode === 'split' ? sw : w, h); } function drawCompare() { const gl = compareGL; const cam = compareCam; if (!gl || !cam || !compareCanvas || gl.isContextLost()) return; const w = compareCanvas.width; const h = compareCanvas.height; gl.useProgram(compareProgram); gl.bindBuffer(gl.ARRAY_BUFFER, compareMesh.vbo); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, compareMesh.ibo); gl.viewport(0, 0, w, h); gl.disable(gl.SCISSOR_TEST); 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 tanV = Math.tan(cam.fov / 2); const leftW = compareMode === 'split' ? Math.round(w / 2) : Math.round(w * compareRatio); paintCompareSide(compareLeft, 0, leftW, w, h, tanV); paintCompareSide(compareRight, leftW, w - leftW, w, h, tanV); gl.disable(gl.SCISSOR_TEST); gl.viewport(0, 0, w, h); } function placeCompareHud() { if (!compareHud || !compareCanvas) return; const host = compareCanvas.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'; const left = compareHud.querySelector('.svt-side.left'); const right = compareHud.querySelector('.svt-side.right'); const slider = compareHud.querySelector('#svt-baidu-slider'); const divider = compareHud.querySelector('#svt-baidu-divider'); if (!left || !right || !slider || !divider) return; const both = !!(compareLeft && compareRight); const leftPct = compareMode === 'overlap' && both ? compareRatio * 100 : 50; left.style.width = leftPct + '%'; right.style.width = (100 - leftPct) + '%'; left.style.visibility = leftPct < 1 ? 'hidden' : ''; right.style.visibility = (100 - leftPct) < 1 ? 'hidden' : ''; 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'; } } function compareSideHtml(name) { const info = name === 'left' ? compareLeft : compareRight; const choices = timelineEntries(); const open = compareMenu === name; const latest = choices[0]; const pickTitle = name === 'left' ? i18n.pickLeftDate : i18n.pickRightDate; const sideLabel = name === 'left' ? i18n.leftSide : i18n.rightSide; const items = choices.map((choice) => { const on = info && choice.id === info.id; const tag = latest && choice.id === latest.id ? `${i18n.latest}` : ''; return `
  • `; }).join(''); const text = info ? info.label : (name === 'right' && compareLiveId ? '' : i18n.pickDate); const dateTitle = info ? `${sideLabel}: ${info.label}` : pickTitle; return `
    ${open ? `` : ''}
    `; } function renderCompareHud() { if (!compareHud) return; const key = [compareMode, compareLeft?.id || '', compareRight?.id || '', compareMenu, timelineEntries().map((item) => item.id).join(',')].join('|'); if (key === compareHudKey) { placeCompareHud(); return; } compareHudKey = key; const modeBtn = (mode, label, title) => ``; compareHud.innerHTML = `
    ${modeBtn('overlap', i18n.overlap, i18n.overlapTitle)}${modeBtn('split', i18n.split, i18n.splitTitle)}
    ${compareSideHtml('left')}${compareSideHtml('right')}
    `; placeCompareHud(); } function sideIsLive(side) { const info = side === 'left' ? compareLeft : compareRight; return !!(info && info.id === compareLiveId); } function switchLivePano(id) { if (!viewer || typeof viewer.setPanoOptions !== 'function') return; const pov = viewer.getPov(); viewer.setPanoOptions({ panoId: id, panoType: 'street', heading: pov.heading, pitch: pov.pitch, }); } function showNativeArrows(show) { const pano = viewer && viewer.curPanorama; const topo = pano && pano.topoArrowContainer; if (!topo || typeof topo.setVisible !== 'function') return; if (show && typeof pano.__svtTopo === 'function') pano.__svtTopo.call(pano, true); else topo.setVisible(!!show); } async function refreshCompareOther(rev, sideRev) { const entries = timelineEntries().filter((item) => item.id !== compareLiveId); if (!compareTarget) return; if (!entries.length) { compareTarget = null; return; } let best = entries[0]; let bestDist = Infinity; const goal = compareTarget.year * 12 + (compareTarget.month || 1); for (const item of entries) { const dist = Math.abs(item.year * 12 + item.month - goal); if (dist < bestDist) { best = item; bestDist = dist; } } const info = await ensureCompareInfo(best.id); if (!compareOn || rev !== compareRev || sideRev !== compareSideRev || !info) return; if (compareLeft && compareLeft.id !== compareLiveId) compareLeft = info; else if (compareRight && compareRight.id !== compareLiveId) compareRight = info; else if (!compareLeft) compareLeft = info; else compareRight = info; loadCompareTexture(info); pruneCompareTextures(); compareDirty = true; compareHudKey = ''; } async function adoptCompareLive(info) { if (!info) return; const prev = compareLiveId; if (compareLeft && (compareLeft.id === info.id || compareLeft.id === prev)) compareLeft = info; else if (compareRight && (compareRight.id === info.id || compareRight.id === prev)) compareRight = info; else if (!compareRight) compareRight = info; else compareLeft = info; compareLiveId = info.id; loadCompareTexture(info); compareDirty = true; compareHudKey = ''; } async function syncCompareAfterMove() { if (!compareOn || !viewer) return; const rev = compareRev; const sideRev = compareSideRev; const info = await ensureCompareInfo(viewer.curPanoId); if (!compareOn || rev !== compareRev || !info) return; await adoptCompareLive(info); await refreshCompareOther(rev, sideRev); } async function pickCompareDate(side, id) { if (!compareOn || !id) return; const current = side === 'left' ? compareLeft : compareRight; const other = side === 'left' ? compareRight : compareLeft; if (current && current.id === id) { compareMenu = ''; compareHudKey = ''; return; } if (other && other.id === id) return; compareSideRev++; compareMenu = ''; compareHudKey = ''; const wasLive = sideIsLive(side); const info = await ensureCompareInfo(id); if (!info || !compareOn) return; if (side === 'left') compareLeft = info; else compareRight = info; loadCompareTexture(info); if (wasLive && info.id !== compareLiveId) { if (other) compareTarget = {year: other.year, month: other.month}; switchLivePano(info.id); } else if (!wasLive) { compareTarget = {year: info.year, month: info.month}; } pruneCompareTextures(); compareDirty = true; renderCompareHud(); } 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(); compareMenu = compareMenu === dateBtn.dataset.side ? '' : dateBtn.dataset.side; compareHudKey = ''; renderCompareHud(); return; } const mode = e.target.closest('[data-mode]'); if (mode) { e.preventDefault(); e.stopPropagation(); compareMode = mode.dataset.mode; compareMenu = ''; compareDirty = true; compareHudKey = ''; renderCompareHud(); return; } if (e.target.closest('[data-close]')) { e.preventDefault(); e.stopPropagation(); stopCompare(); } } function onCompareSliderDown(e) { const slider = e.target.closest('#svt-baidu-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(1, Math.max(0, (ev.clientX - rect.left) / rect.width)); compareDirty = true; placeCompareHud(); }; 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); } let compareSyncId = ''; function compareFrame() { compareRaf = 0; if (!compareOn) return; if (ensureCompareLayers()) { compareTex.forEach((entry) => { entry.tiles.forEach((tile) => { if (tile.state === 'bitmap' && compareGL) uploadCompareTile(compareGL, tile); }); }); const pose = readBaiduPose(); if (pose) { const key = pose.heading.toFixed(3) + '|' + pose.fovDeg.toFixed(2) + '|' + (viewer.getPov().pitch || 0).toFixed(3); if (!compareCam || key !== compareCam.key) compareDirty = true; pose.key = key; compareCam = pose; } if (viewer && compareLiveId && compareLiveId !== viewer.curPanoId && compareSyncId !== viewer.curPanoId) { compareSyncId = viewer.curPanoId; syncCompareAfterMove(); } if (compareDirty && compareCam) { compareDirty = false; drawCompare(); } renderCompareHud(); } compareRaf = requestAnimationFrame(compareFrame); } async function startCompare() { if (!viewer || !currentPano || !currentPano.timeline || currentPano.timeline.length < 2) { Swal.fire({title: i18n.needDates, timer: 1400, showConfirmButton: false, allowOutsideClick: true, backdrop: null, customClass: {popup: 'swal-small-popup'}}); return; } compareOn = true; compareRev++; compareMode = 'overlap'; compareRatio = 0.5; compareMenu = ''; compareHoldId = ''; compareHudKey = ''; const cur = await ensureCompareInfo(viewer.curPanoId); if (!cur || !compareOn) { compareOn = false; return; } const others = timelineEntries().filter((item) => item.id !== cur.id); const older = others.filter((item) => compareMonth(item) <= compareMonth(cur)); const pick = older[0] || others[0]; const other = pick ? await ensureCompareInfo(pick.id) : null; compareLiveId = cur.id; compareTarget = other ? {year: other.year, month: other.month} : null; if (other && compareMonth(other) <= compareMonth(cur)) { compareLeft = other; compareRight = cur; } else { compareLeft = cur; compareRight = other; } showNativeArrows(true); if (!ensureCompareLayers()) { compareOn = false; showNativeArrows(false); return; } loadCompareTexture(compareLeft); if (compareRight) loadCompareTexture(compareRight); renderCompareHud(); document.getElementById('pano-container')?.classList.add('svt-comparing'); const compareBtn = document.getElementById('svt-compare-btn'); compareBtn?.classList.add('is-on'); compareBtn?.__svtSyncLabel?.(); if (!compareRaf) compareRaf = requestAnimationFrame(compareFrame); } function stopCompare() { compareOn = false; compareRev++; compareMenu = ''; compareLeft = null; compareRight = null; compareTarget = null; compareLiveId = ''; if (compareRaf) cancelAnimationFrame(compareRaf); compareRaf = 0; [...compareTex.keys()].forEach(dropCompareTexture); compareCanvas?.remove(); compareHud?.remove(); compareCanvas = null; compareHud = null; compareGL = null; compareProgram = null; compareMesh = null; compareUniforms = null; compareCam = null; showNativeArrows(false); document.getElementById('pano-container')?.classList.remove('svt-comparing'); const compareBtn = document.getElementById('svt-compare-btn'); compareBtn?.classList.remove('is-on'); compareBtn?.__svtSyncLabel?.(); } function toggleCompare() { if (compareOn) stopCompare(); else startCompare(); } function mountCompareButton() { if (document.getElementById('svt-compare-btn')) return; const sidebar = document.getElementById('pano-sidebar'); const fold = document.getElementById('pano-fold-btn'); if (!sidebar || !fold) return; const li = document.createElement('li'); li.id = 'svt-compare-li'; const btn = document.createElement('a'); btn.className = 'pano_button'; btn.id = 'svt-compare-btn'; btn.href = 'javascript:void(0);'; const syncCompareBtnLabel = () => { const label = compareOn ? i18n.compareOn : i18n.compareTitle; btn.title = label; btn.setAttribute('aria-label', label); }; syncCompareBtnLabel(); btn.innerHTML = `${compareIcon}`; btn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); toggleCompare(); syncCompareBtnLabel(); }); const line = document.createElement('div'); line.className = 'pano-zoom-line'; line.innerHTML = '
    '; li.appendChild(btn); li.appendChild(line); sidebar.insertBefore(li, fold); if (compareOn) btn.classList.add('is-on'); btn.__svtSyncLabel = syncCompareBtnLabel; } function trackCompareButton() { mountCompareButton(); requestAnimationFrame(trackCompareButton); } requestAnimationFrame(trackCompareButton); document.addEventListener('pointerdown', (e) => { if (!compareOn || !compareMenu) return; if (e.target.closest && e.target.closest('.svt-side')) return; compareMenu = ''; compareHudKey = ''; }, true); 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', ()=>{ stopCompare(); if (compassControl) compassControl.remove(); compassControl = null; const oldPanel = document.getElementById('pano-info-panel') ; if (oldPanel) oldPanel.remove(); }) const panoObj = instance.panorama.curPanorama; if (!panoObj.__svtTopo && typeof panoObj.setTopoVisible === 'function') { panoObj.__svtTopo = panoObj.setTopoVisible; } panoObj.setTopoVisible = function(visible) { if (compareOn && typeof this.__svtTopo === 'function') return this.__svtTopo(visible); 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(); syncCompareAfterMove(); }); 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() === 'h')) { e.stopImmediatePropagation(); e.preventDefault(); document.documentElement.classList.toggle('svt-ui-hidden'); } 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; } .pano-compare.is-on { background: #fff; color: #202124; } #svt-baidu-hud { position: fixed; z-index: 10020; pointer-events: none; font-family: "PingFang SC", "Microsoft YaHei", sans-serif; color: #fff; } #svt-baidu-hud .svt-top { position: absolute; left: 0; right: 0; top: 16px; height: 38px; } #svt-baidu-hud .svt-modes { pointer-events: auto; position: absolute; left: 50%; transform: translateX(-50%); display: flex; height: 35px; padding: 0px; border-radius: 19px; background: rgba(0,0,0,.6); } #svt-baidu-hud .svt-modes button { border: 0; background: transparent; color: #fff; height: 34px; min-width: 64px; padding: 0 14px; border-radius: 17px; font-size: 14px; cursor: pointer; } #svt-baidu-hud .svt-modes button.on { background: #fff; color: #1a73e8; font-weight: 600; } #pano-container.svt-comparing #pano-info-panel { top: 124px; z-index: 10010; } #pano-container.svt-comparing #custom-compass { top: 116px; } #svt-baidu-hud .svt-x { pointer-events: auto; position: absolute; right: 96px; top: 0; width: 36px; height: 36px; border: 0; border-radius: 50%; background: rgba(32,33,36,.55); color: #fff; font-size: 22px; cursor: pointer; } #svt-baidu-hud .svt-dates { position: absolute; left: 0; right: 0; top: 62px; display: flex; height: 40px; } #svt-baidu-hud .svt-side { position: relative; display: flex; justify-content: center; min-width: 0; } #svt-baidu-hud .svt-date { pointer-events: auto; display: inline-flex; align-items: center; gap: 4px; max-width: calc(100% - 24px); height: 36px; padding: 0 10px 0 14px; border: 0; border-radius: 8px; background: rgba(0,0,0,.55); color: #fff; font-size: 14px; cursor: pointer; } #svt-baidu-hud .svt-date svg { width: 16px; height: 16px; } #svt-baidu-hud .svt-side.is-open .svt-date svg { transform: rotate(180deg); } #svt-baidu-hud .svt-date:disabled { cursor: default; } #svt-baidu-hud .svt-date-menu { pointer-events: auto; position: absolute; top: 42px; left: 50%; transform: translateX(-50%); min-width: 160px; max-height: 280px; margin: 0; padding: 6px; overflow: auto; list-style: none; border-radius: 10px; background: rgba(32,33,36,.94); z-index: 2; } #svt-baidu-hud .svt-date-menu button { display: flex; width: 100%; justify-content: space-between; gap: 12px; height: 32px; border: 0; border-radius: 6px; background: transparent; color: #fff; font-size: 13px; cursor: pointer; } #svt-baidu-hud .svt-date-menu button.on, #svt-baidu-hud .svt-date-menu button:hover { background: rgba(255,255,255,.14); } #svt-baidu-hud .svt-date-menu i { font-style: normal; color: #9aa0a6; font-size: 12px; } #svt-baidu-slider { position: absolute; top: 0; bottom: 0; width: 28px; transform: translateX(-50%); pointer-events: none; cursor: ew-resize; touch-action: none; } #svt-baidu-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-baidu-slider .svt-handle { pointer-events: auto; 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-baidu-slider .svt-handle::before, #svt-baidu-slider .svt-handle::after { content: ""; position: absolute; top: 13px; border-top: 5px solid transparent; border-bottom: 5px solid transparent; } #svt-baidu-slider .svt-handle::before { left: 8px; border-right: 6px solid #5f6368; } #svt-baidu-slider .svt-handle::after { right: 8px; border-left: 6px solid #5f6368; } #svt-compare-li .pano_button { color: #fff; } #svt-compare-li .pano_button span { display: flex; align-items: center; justify-content: center; width: 22px; height: 22px; margin: 9px; background-image: none; } #svt-compare-li .pano_button span svg { width: 18px; height: 18px; display: block; } #svt-compare-li .pano_button.is-on, #svt-compare-li .pano_button.is-on:hover { background-color: #fff; color: #252525; } html.svt-ui-hidden body * { visibility: hidden !important; } html.svt-ui-hidden canvas, html.svt-ui-hidden #svt-baidu-compare, html.svt-ui-hidden #svt-baidu-divider, html.svt-ui-hidden #svt-baidu-slider, html.svt-ui-hidden #svt-baidu-slider .svt-handle { visibility: visible !important; } html.svt-ui-hidden #svt-baidu-slider, html.svt-ui-hidden #svt-baidu-slider .svt-handle { pointer-events: auto !important; } #svt-baidu-divider { display: none; position: absolute; top: 0; bottom: 0; left: 50%; width: 2px; transform: translateX(-50%); background: #fff; } ` )} )();