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}
+87 -13
View File
@@ -66,6 +66,67 @@ fn log_event(events: RwSignal<Vec<LiveEvent>>, message: String) {
}
}
}
const BASEMAP_KEY: &str = "rid.realtime.basemap.v1";
fn initial_basemap() -> String {
web_sys::window()
.and_then(|w| w.local_storage().ok().flatten())
.and_then(|s| s.get_item(BASEMAP_KEY).ok().flatten())
.filter(|s| s == "imagery" || s == "road")
.unwrap_or_else(|| "road".into())
}
fn basemap_layers(kind: &str) -> [&'static str; 2] {
if kind == "imagery" {
["img_w", "cia_w"]
} else {
["vec_w", "cva_w"]
}
}
fn map_label(value: &Value, kind: &str) -> String {
let name = if kind == "imagery" {
"影像图"
} else {
"路网图"
};
let states = basemap_layers(kind).map(|layer| &value["layers"][layer]);
let real = states
.iter()
.any(|s| matches!(s["source"].as_str(), Some("online" | "cache" | "offline")));
let error = states.iter().find_map(|s| s["error"].as_str());
let reason = if value["configError"].as_str().is_some() {
"本机地图配置无效"
} else if error == Some("key-or-permission") {
"密钥或服务权限错误"
} else if error == Some("rate-limited") {
"服务限流,稍后重试"
} else if error == Some("timeout") {
"请求超时,稍后重试"
} else if error.is_some() {
"网络或地图服务异常,稍后重试"
} else if value["keyConfigured"] == false {
"未配置地图密钥"
} else {
"等待地图加载"
};
if !real {
return format!("天地图 · {name} · 暂无可用底图({reason})");
}
let source = if states.iter().any(|s| s["source"] == "missing") {
"部分瓦片缺失"
} else if states.iter().all(|s| s["source"] == "online") {
"在线"
} else if states.iter().any(|s| s["source"] == "offline") {
"本地离线资源"
} else if states.iter().any(|s| s["source"] == "online") {
"在线/本地缓存"
} else {
"本地缓存"
};
if error.is_some() {
format!("天地图 · {name} · {source}({reason})")
} else {
format!("天地图 · {name} · {source}")
}
}
#[component]
pub fn Realtime() -> impl IntoView {
let ids = RwSignal::new(Vec::<String>::new());
@@ -77,7 +138,8 @@ pub fn Realtime() -> impl IntoView {
let record = RwSignal::new(None::<Value>);
let lookup = RwSignal::new("请选择目标".to_owned());
let receiver = RwSignal::new("接收状态加载中".to_owned());
let map_status = RwSignal::new("地图加载中".to_owned());
let map_status = RwSignal::new(Value::Null);
let basemap = RwSignal::new(initial_basemap());
let layout = super::realtime_layout::Layout::new();
layout.start();
let page = RwSignal::new(0usize);
@@ -180,7 +242,7 @@ pub fn Realtime() -> impl IntoView {
if stop.get() {
return;
}
if map_call("create", &["rt-map".into()]).is_ok() {
if map_call("create", &["rt-map".into(), basemap.get_untracked().into()]).is_ok() {
break;
}
TimeoutFuture::new(50).await;
@@ -331,6 +393,8 @@ pub fn Realtime() -> impl IntoView {
Effect::new(move |_| {
let stop = poll_stop.clone();
spawn_local(async move {
let mut last_refresh = 0.0;
let mut refreshed_retry = 0.0;
while !stop.get() {
let synthetic = if let Ok(r) = gloo_net::http::Request::get("/api/realtime/status")
.send()
@@ -371,16 +435,25 @@ pub fn Realtime() -> impl IntoView {
.await
&& let Ok(value) = response.json::<Value>().await
{
map_status.set(
if value["keyConfigured"] == false {
"离线底图 · 未配置在线地图密钥"
} else if value["mode"] == "offline" {
"在线地图不可用 · 使用离线资源"
} else {
"在线卫星地图 · 本地缓存"
}
.into(),
);
let states = basemap_layers(&basemap.get_untracked())
.map(|layer| &value["layers"][layer]);
let ready = states.iter().any(|s| {
matches!(s["source"].as_str(), Some("online" | "cache" | "offline"))
});
let _ = map_call("baseReady", &[JsValue::from_bool(ready)]);
let retry = value["retryAfterMs"].as_f64().unwrap_or(0.0);
let now = js_sys::Date::now();
let missing = states.iter().any(|s| s["source"] == "missing");
if value["keyConfigured"] == true
&& value["mode"] == "online-preferred"
&& ((retry > 0.0 && retry != refreshed_retry && now >= retry)
|| (missing && now - last_refresh >= 30000.0))
{
let _ = map_call("refresh", &[]);
last_refresh = now;
refreshed_retry = retry;
}
map_status.set(value);
}
TimeoutFuture::new(3000).await;
}
@@ -390,6 +463,7 @@ pub fn Realtime() -> impl IntoView {
<main class="rt-page"><div id="rt-layout" class="mc-layout-b" class:compact=move||layout.compact.get() class:dock-hidden=move||!layout.dock_visible() class:list-hidden=move||!layout.list_visible() class:detail-hidden=move||!layout.detail_visible() style=("--dock-height",move||format!("{}px",layout.height.get()))>
<section class="mc-map-area-top"><div id="rt-map" class="rt-map-canvas"></div>
<div class="mc-map-toolstrip" role="toolbar" aria-label="地图工具">
<select class="live-basemap" aria-label="底图类型" prop:value=move||basemap.get() on:change=move |e|{let value=event_target_value(&e);if !matches!(value.as_str(),"road"|"imagery"){return}basemap.set(value.clone());if let Some(s)=web_sys::window().and_then(|w|w.local_storage().ok().flatten()){let _=s.set_item(BASEMAP_KEY,&value);}let _=map_call("setBasemap",&[value.into()]);}><option value="road">"路网图"</option><option value="imagery">"影像图"</option></select>
<button title="放大" aria-label="放大" on:click=move |_|{let _=map_call("zoomIn",&[]);}>"+"</button>
<button title="缩小" aria-label="缩小" on:click=move |_|{let _=map_call("zoomOut",&[]);}>"−"</button>
<button id="rt-map-focus" title="聚焦选中目标" aria-label="聚焦选中目标" disabled=move||position.get().is_none() on:click=move |_|layout.focus()>"◎"</button>
@@ -397,7 +471,7 @@ pub fn Realtime() -> impl IntoView {
<button id="rt-list-toggle" title="显示目标目录" aria-label="显示目标目录" aria-controls="rt-directory" aria-expanded=move||layout.list_visible().to_string() on:click=move |_|layout.toggle_list()>"☷"</button>
<button id="rt-detail-toggle" title="显示目标详情" aria-label="显示目标详情" aria-controls="rt-details" aria-expanded=move||layout.detail_visible().to_string() on:click=move |_|layout.toggle_detail()>"ⓘ"</button>
</div>
<div class="mc-map-infobar">{move||map_status.get()}</div>
<div class="mc-map-infobar">{move||map_label(&map_status.get(),&basemap.get())}</div>
</section>
<aside id="rt-directory" class="mc-floating-panel live-targets" aria-label="目标目录" hidden=move||!layout.list_visible()>
<div class="live-panel-head"><h2>"目标目录"</h2><button title="收起目标目录" aria-label="收起目标目录" on:click=move |_|{layout.toggle_list();super::realtime_layout::focus("rt-list-toggle");}>"‹"</button></div><div class="live-list-controls">