feat(maps): 支持底图切换与图层状态感知

后端新增 LayerStatus 跟踪每个图层的源(online/cache/offline/missing)
及错误分类(timeout/key-or-permission/rate-limited/network),
status 端点返回完整图层状态供前端展示。

密钥加载支持从 maps/config.json 读取,环境变量优先级高于本地文件,
配置文件损坏时保留原文件并返回 configError 标记。

前端新增路网图/影像图切换下拉框,选择持久化到 localStorage;
底图切换通过 tileRevision 实现缓存失效;
infobar 展示人类可读的天地图状态(在线/缓存/离线/缺失及原因);
检测到缺失瓦片或重试时间到达时自动触发 refresh 探测服务恢复。

map-adapter.js 新增 setBasemap、baseReady 接口,
metrics 增加 basemap、camera、baseTiles、labelTiles 诊断字段。
```
This commit is contained in:
2026-10-22 18:51:54 +08:00
parent 58fd687998
commit 3cf50f2e8b
5 changed files with 410 additions and 30 deletions
+12 -6
View File
@@ -5,17 +5,21 @@ let map, layer, latest, ids = [], selected = '', pending = false;
let frameTimes = [], lastFrame = 0;
let marker=null, history=[], lastTrail=0;
let centered=false, workerWasmBytes=0, resizeObserver;
let basemap="road",tileRevision=0,mapCreations=0;
const basemapLayers={road:["vec_w","cva_w"],imagery:["img_w","cia_w"]};
function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}?v=${tileRevision}`;}
let occlusion={top:0,right:0,bottom:0,left:0};
function shader(gl, type, source) {
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
}
function create(container) {
function create(container,initialBasemap="road") {
basemap=initialBasemap==="imagery"?"imagery":"road";mapCreations++;
if (map) map.remove();
map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:35,bearing:0,attributionControl:false,
style:{version:8,sources:{
'tdt-base':{type:'raster',tiles:['/api/maps/tile/img_w/{z}/{x}/{y}'],tileSize:256,maxzoom:18,attribution:'天地图卫星 / 本地离线资源'},
'tdt-labels':{type:'raster',tiles:['/api/maps/tile/cia_w/{z}/{x}/{y}'],tileSize:256,maxzoom:18}
'tdt-base':{type:'raster',tiles:[tileUrl(0)],tileSize:256,maxzoom:18,attribution:'天地图 © 自然资源部 / 本地缓存与离线资源'},
'tdt-labels':{type:'raster',tiles:[tileUrl(1)],tileSize:256,maxzoom:18}
},layers:[
{id:'background',type:'background',paint:{'background-color':'#060c18'}},
{id:'tdt-base',type:'raster',source:'tdt-base'},
@@ -99,9 +103,11 @@ function flush(){
}
function update(positions,newIds){latest=positions;if(newIds)ids=Array.from(newIds);if(!centered&&latest.length>=4){centered=true;focusCoordinate([latest[0],latest[1]], false);}if(!pending){pending=true;requestAnimationFrame(flush);}}
function select(id){if(selected!==id){selected=id;history=[];flush();}const i=ids.indexOf(id);return i>=0&&latest?Array.from(latest.slice(i*4,i*4+4)):[];}
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');const projected=map&&latest&&ids.includes(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {selectedPixel:projected?{x:projected.x,y:projected.y}:null,occlusion:{...occlusion},mapReady:!!layer?.gl,styleReady:map?.isStyleLoaded()||false,mapCanvasWidth:map?.getCanvas().clientWidth||0,mapCanvasHeight:map?.getCanvas().clientHeight||0,samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');const projected=map&&latest&&ids.includes(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {basemap,mapCreations,camera:map?{center:map.getCenter().toArray(),zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()}:null,baseTiles:map?.getSource('tdt-base')?.tiles,labelTiles:map?.getSource('tdt-labels')?.tiles,selectedPixel:projected?{x:projected.x,y:projected.y}:null,occlusion:{...occlusion},mapReady:!!layer?.gl,styleReady:map?.isStyleLoaded()||false,mapCanvasWidth:map?.getCanvas().clientWidth||0,mapCanvasHeight:map?.getCanvas().clientHeight||0,samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
function connection(connected){const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
function refresh(){for(const [id,layer]of [['tdt-base','img_w'],['tdt-labels','cia_w']])map?.getSource(id)?.setTiles([`/api/maps/tile/${layer}/{z}/{x}/{y}`]);}
function refresh(){tileRevision++;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);}
function setBasemap(value){const next=value==='imagery'?'imagery':'road';if(next!==basemap){basemap=next;refresh();}}
function baseReady(ready){if(map?.getLayer('grid'))map.setLayoutProperty('grid','visibility',ready?'none':'visible');}
function setOcclusion(value){
occlusion=Object.fromEntries(['top','right','bottom','left'].map(k=>[k,Number.isFinite(value?.[k])?Math.max(0,value[k]):0]));
}
@@ -125,4 +131,4 @@ function focusCoordinate(center,animate=true){
if(animate)map.flyTo({...options,zoom:Math.max(map.getZoom(),13),duration:400});else map.easeTo({...options,duration:0});
}
function centerSelected(){if(!map||!latest||!selected)return;const i=ids.indexOf(selected);if(i>=0)focusCoordinate([latest[i*4],latest[i*4+1]]);}
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;occlusion={top:0,right:0,bottom:0,left:0};}};
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setBasemap,baseReady,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;occlusion={top:0,right:0,bottom:0,left:0};}};
@@ -108,3 +108,10 @@ body[data-menu-hidden=true] .workspace-pane{left:0}body[data-menu-hidden=true] .
@media(max-width:1400px){}
@media(max-width:1100px){.settings-layout{padding:24px;max-width:100%;overflow:auto}}
@media(max-width:760px){.workspace-pane{left:56px}.settings-layout{grid-template-columns:1fr;padding:18px}.settings-sidebar{display:none}.mc-dock-substatus{display:none}.homescreen{left:56px}}
/* Basemap selection uses the existing toolbar, including compact windows. */
.mc-layout-b .live-basemap{height:34px;width:82px;min-width:0;padding:4px 6px;border:1px solid var(--work-line);border-radius:6px;background:var(--work-input);color:var(--work-text);font:inherit;font-size:12px;cursor:pointer}
.mc-layout-b.compact .live-basemap{width:68px;padding:4px 2px}
.mc-layout-b.compact .mc-map-toolstrip button{min-width:28px;padding:6px 4px;font-size:12px}
.mc-layout-b .live-basemap option{background:var(--mc-bg);color:var(--work-text)}
.theme-white .mc-layout-b .live-basemap option{background:#f4f8ff;color:#243b57}