feat(web-ui): 添加历史轨迹功能与地图适配

- 在 web-ui 中新增历史轨迹查询与回放功能,允许用户查看历史数据。
- 更新 map-loader.js 和 history-map-adapter.js,支持历史轨迹的地图渲染与交互。
- 修改 CSS 文件以改善历史轨迹界面的样式,确保在不同主题下的视觉一致性。
- 在 receivers.js 中更新接收机配置,支持 UID 身份隔离与状态显示优化。
- 在 map_settings.rs 中设置默认经纬度,提升地图初始化体验。
This commit is contained in:
2026-11-02 15:28:01 +08:00
parent 87d0ec8352
commit 7af8fb32cf
43 changed files with 3107 additions and 302 deletions
+82 -27
View File
@@ -5,17 +5,20 @@ maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
let tileBuffer;
let map, layer, latest, ids = [], selected = '', pending = false;
let frameTimes = [], lastFrame = 0;
let marker=null, history=[], lastTrail=0, generations=null, selectedGeneration=null;
let markers=new Map(), idIndexes=new Map(), markerInfos=null, markerScanDirty=true, lastMarkerScan=0, lastMarkerText=0;
let history=[], lastTrail=0, generations=null, selectedGeneration=null, liveConnected=true;
const MAX_VISIBLE_CARDS=120;
let centered=false, workerWasmBytes=0, resizeObserver, rawFocus=null;
let basemap="imagery",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}${tileRevision?`?v=${tileRevision}`:''}`;}
let classification=new Map(),listFilter="all",sourceIds=null;
function setSources(value){sourceIds=value?new Set(Array.from(value)):null;flush();}
function setSources(value){sourceIds=value?new Set(Array.from(value)):null;markerScanDirty=true;flush();}
function targetKind(id){return classification.get(id)||"unknown";}
function located(id,i=ids.indexOf(id)){return i>=0&&latest&&Number.isFinite(latest[i*4])&&Number.isFinite(latest[i*4+1]);}
function targetVisible(id,i=ids.indexOf(id)){return (!sourceIds||sourceIds.has(id))&&located(id,i)&&(listFilter==="all"||targetKind(id)===listFilter);}
function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";flush();}
function located(id,i=ids.indexOf(id)){if(i<0||!latest)return false;const lon=latest[i*4],lat=latest[i*4+1];return Number.isFinite(lon)&&Number.isFinite(lat)&&Math.abs(lon)<=180&&Math.abs(lat)<=90&&(lon!==0||lat!==0);}
function passesFilters(id){return (!sourceIds||sourceIds.has(id))&&(listFilter==="all"||targetKind(id)===listFilter);}
function targetVisible(id,i=ids.indexOf(id)){return passesFilters(id)&&located(id,i);}
function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";markerScanDirty=true;flush();}
let occlusion={top:0,right:0,bottom:0,left:0};
let fenceEntries=[],fenceMarkers=[];
function clearFenceMarkers(){for(const marker of fenceMarkers)marker.remove();fenceMarkers=[];}
@@ -66,8 +69,9 @@ function create(container,initialBasemap="imagery",preferences=null) {
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
tileBuffer?.destroy();
clearFenceMarkers();
clearTargetMarkers();
if (map) map.remove();
const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[120.1538,30.2874];
const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[118.778863,32.043828];
// A configured startup camera takes precedence over the legacy first-target fallback.
centered=!!(preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude));
const initialZoom=Number.isFinite(preferences?.zoom)?Math.max(0,Math.min(18,preferences.zoom)):15;
@@ -144,6 +148,7 @@ function create(container,initialBasemap="imagery",preferences=null) {
for(let i=0;i<ids.length;i++){if(!targetVisible(ids[i],i))continue;const p=map.project([latest[i*4],latest[i*4+1]]);const d=Math.hypot(p.x-event.point.x,p.y-event.point.y);if(d<distance){index=i;distance=d;}}
if(index>=0)window.dispatchEvent(new CustomEvent('rid-select',{detail:ids[index]}));
});
map.on('moveend',()=>{markerScanDirty=true;syncTargetMarkers(true);});
map.on('error',e=>{if(!e.sourceId?.startsWith('tdt-'))console.error('map:',e.error?.message || e);});
return true;
}
@@ -155,32 +160,82 @@ function flush(){
if(index>=0&&targetVisible(selected)){
rawFocus=null;
const coordinate=[latest[index*4],latest[index*4+1]];
const kind=targetKind(selected);
placeMarker(coordinate,selected+(kind==="black"?" · 黑名单":kind==="white"?" · 白名单":""),kind);
const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200);
map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});}
}else if(rawFocus){placeMarker(rawFocus,selected+' · 定位待核实','');history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
else{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
}else{history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
syncTargetMarkers();
}
function update(positions,newIds,newGenerations){latest=positions;generations=newGenerations;if(newIds)ids=Array.from(newIds);const selectedIndex=ids.indexOf(selected);const generation=selectedIndex>=0?generations?.[selectedIndex]:null;if(!located(selected)||generation!==selectedGeneration){history=[];lastTrail=0;}selectedGeneration=generation;if(!centered){const i=ids.findIndex(located);if(i>=0){centered=true;focusCoordinate([latest[i*4],latest[i*4+1]], false);}}if(!pending){pending=true;requestAnimationFrame(flush);}}
function placeMarker(coordinate,text,kind){
if(!marker){
const root=document.createElement('div');root.className='rt-target-pin';
const label=document.createElement('div');label.className='rt-target-label';
const icon=document.createElement('div');icon.className='rt-drone-icon';icon.innerHTML='<svg viewBox="0 0 32 32" width="22" height="22" aria-hidden="true"><path d="M7 7 L25 25 M25 7 L7 25" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><circle cx="7" cy="7" r="3.1" fill="currentColor"/><circle cx="25" cy="7" r="3.1" fill="currentColor"/><circle cx="7" cy="25" r="3.1" fill="currentColor"/><circle cx="25" cy="25" r="3.1" fill="currentColor"/><circle cx="16" cy="16" r="3.3" fill="#f7fbff" stroke="currentColor" stroke-width="1.4"/></svg>';
const point=document.createElement('i');point.className='rt-drone-point';
root.append(label,icon,point);
marker=new maplibre.Marker({element:root,anchor:'bottom'}).setLngLat(coordinate).addTo(map);
function update(positions,newIds,newGenerations,newMarkerInfos){latest=positions;generations=newGenerations;markerInfos=newMarkerInfos||null;if(newIds){ids=Array.from(newIds);idIndexes=new Map(ids.map((id,index)=>[id,index]));markerScanDirty=true;}const selectedIndex=ids.indexOf(selected);if(selected&&selectedIndex<0){selected='';rawFocus=null;markerScanDirty=true;}const generation=selectedIndex>=0?generations?.[selectedIndex]:null;if(!located(selected)||generation!==selectedGeneration){history=[];lastTrail=0;}selectedGeneration=generation;if(!centered){const i=ids.findIndex(located);if(i>=0){centered=true;focusCoordinate([latest[i*4],latest[i*4+1]], false);}}if(!pending){pending=true;requestAnimationFrame(flush);}}
function clearTargetMarkers(){for(const entry of markers.values())entry.marker.remove();markers.clear();markerScanDirty=true;lastMarkerScan=0;lastMarkerText=0;}
function markerCoordinate(id,index){
if(targetVisible(id,index))return {coordinate:[latest[index*4],latest[index*4+1]],unverified:false};
if(id===selected&&rawFocus&&passesFilters(id))return {coordinate:rawFocus,unverified:true};
return null;
}
function markerAge(value){if(!liveConnected)return '连接断开';if(!Number.isFinite(value)||value<0)return '—';if(value<1000)return `${Math.round(value)} ms`;if(value<10000)return `${(value/1000).toFixed(1)} 秒`;return `${Math.round(value/1000)} 秒`;}
function createTargetMarker(id,coordinate){
const root=document.createElement('div');root.className='rt-target-pin';
const card=document.createElement('div');card.className='rt-target-info';
const header=document.createElement('div');header.className='rt-target-info-head';
const name=document.createElement('span');name.className='rt-target-info-id';name.textContent=id;name.title=id;
const age=document.createElement('span');age.className='rt-target-info-age';age.title='该目标最近一次接收数据到服务端生成推送数据的时间,不代表定位精度或完整传输延迟';
header.append(name,age);
const coordinates=document.createElement('div');coordinates.className='rt-target-info-coordinates';
const longitude=document.createElement('span');const latitude=document.createElement('span');coordinates.append(longitude,latitude);
const height=document.createElement('div');height.className='rt-target-info-height';
const verification=document.createElement('div');verification.className='rt-target-info-verification';
card.append(header,coordinates,height,verification);
const icon=document.createElement('button');icon.type='button';icon.className='rt-drone-icon';icon.setAttribute('aria-label',`选择目标 ${id}`);
icon.innerHTML='<svg viewBox="0 0 32 32" width="23" height="23" aria-hidden="true"><path d="M2.5 10.5h9M20.5 10.5h9M7 10.5v3M25 10.5v3M7 14h5l1.5-2h5l1.5 2h5l-1.5 5h-4l-1.5 2h-4l-1.5-2h-4zM10 21v2h4M22 21v2h-4" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"/><circle cx="16" cy="17" r="1" fill="currentColor"/></svg>';
icon.addEventListener('click',event=>{event.stopPropagation();window.dispatchEvent(new CustomEvent('rid-select',{detail:id}));});
const point=document.createElement('i');point.className='rt-drone-point';
root.append(card,icon,point);
const marker=new maplibre.Marker({element:root,anchor:'bottom'}).setLngLat(coordinate).addTo(map);
return {marker,root,card,name,age,longitude,latitude,height,verification,icon,coordinate:[...coordinate]};
}
function syncTargetMarkers(force=false){
if(!map||!latest)return;
const now=performance.now(),scan=force||markerScanDirty||now-lastMarkerScan>=250;
if(scan){
const wanted=new Set(),canvas=map.getCanvas(),width=canvas.clientWidth,height=canvas.clientHeight;
const chosen=idIndexes.get(selected);
if(chosen!==undefined&&markerCoordinate(selected,chosen))wanted.add(selected);
for(let i=0;i<ids.length&&wanted.size<MAX_VISIBLE_CARDS;i++){
const id=ids[i];if(wanted.has(id)||!targetVisible(id,i))continue;
const pixel=map.project([latest[i*4],latest[i*4+1]]);
// Cards just outside the viewport can still extend into it.
if(pixel.x>=-240&&pixel.x<=width+240&&pixel.y>=-150&&pixel.y<=height+150)wanted.add(id);
}
for(const [id,entry] of markers){if(!wanted.has(id)){entry.marker.remove();markers.delete(id);}}
for(const id of wanted){if(!markers.has(id)){const i=idIndexes.get(id),position=markerCoordinate(id,i);if(position)markers.set(id,createTargetMarker(id,position.coordinate));}}
lastMarkerScan=now;markerScanDirty=false;
}
const el=marker.getElement();
const label=el.querySelector('.rt-target-label');
label.textContent=text;label.dataset.listKind=kind||'';el.dataset.listKind=kind||'';
marker.setLngLat(coordinate);
const updateText=force||scan||now-lastMarkerText>=200;
for(const [id,entry] of markers){
const index=idIndexes.get(id),position=index===undefined?null:markerCoordinate(id,index);
if(!position){entry.marker.remove();markers.delete(id);continue;}
const [lon,lat]=position.coordinate;
if(entry.coordinate[0]!==lon||entry.coordinate[1]!==lat){entry.marker.setLngLat(position.coordinate);entry.coordinate=[lon,lat];}
if(!updateText)continue;
const selectedNow=id===selected,kind=targetKind(id);
entry.root.dataset.listKind=kind;entry.root.dataset.selected=selectedNow?'true':'false';entry.root.style.zIndex=selectedNow?'10':'1';entry.icon.setAttribute('aria-pressed',selectedNow?'true':'false');
entry.name.textContent=id+(kind==='black'?' · 黑名单':kind==='white'?' · 白名单':'');entry.name.title=entry.name.textContent;
entry.longitude.textContent=`经度 ${lon.toFixed(6)}`;entry.latitude.textContent=`纬度 ${lat.toFixed(6)}`;
const value=markerInfos?.[index*3+1],heightKind=markerInfos?.[index*3+2];
const label=({1:'高度',2:'几何高度',3:'离地高度',4:'相对高度(原始)',5:'气压高度'})[heightKind]||'高度';
entry.height.textContent=`${label} ${Number.isFinite(value)?`${value.toFixed(1)} m`:'—'}`;
entry.age.textContent=`数据年龄 ${markerAge(markerInfos?.[index*3])}`;
entry.verification.textContent=position.unverified?'坐标待核实':'';
}
if(updateText)lastMarkerText=now;
}
function focusRaw(point){const lon=Number(point?.[0]),lat=Number(point?.[1]);if(!map||!selected||!Number.isFinite(lon)||!Number.isFinite(lat)||Math.abs(lon)>180||Math.abs(lat)>90)return;rawFocus=[lon,lat];focusCoordinate(rawFocus);placeMarker(rawFocus,selected+' · 定位待核实','');}
function select(id){if(selected!==id){selected=id;history=[];rawFocus=null;selectedGeneration=generations?.[ids.indexOf(id)]??null;flush();}if(located(id)){rawFocus=null;centerSelected();}const i=ids.indexOf(id);return located(id)?Array.from(latest.slice(i*4,i*4+4)):[];}
function rawPoint(point){if(!Array.isArray(point)||point.length<2)return null;const [lon,lat]=point;return Number.isFinite(lon)&&Number.isFinite(lat)&&Math.abs(lon)<=180&&Math.abs(lat)<=90&&(lon!==0||lat!==0)?[lon,lat]:null;}
function updateRaw(point){if(!map||!selected||!ids.includes(selected))return;const next=rawPoint(point);if((next?.[0]??null)!==(rawFocus?.[0]??null)||(next?.[1]??null)!==(rawFocus?.[1]??null))markerScanDirty=true;rawFocus=next;flush();}
function focusRaw(point){const position=rawPoint(point);if(!map||!selected||!ids.includes(selected)||!position)return;rawFocus=position;markerScanDirty=true;focusCoordinate(position);flush();}
function select(id){if(selected!==id){selected=id;history=[];rawFocus=null;selectedGeneration=generations?.[ids.indexOf(id)]??null;markerScanDirty=true;flush();}if(located(id)){rawFocus=null;centerSelected();}const i=ids.indexOf(id);return located(id)?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&&located(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {tileBuffer:tileBuffer?.metrics(),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,visibleTargets:ids.filter(targetVisible).length,listFilter,classifiedTargets:{white:ids.filter(id=>targetKind(id)==="white").length,black:ids.filter(id=>targetKind(id)==="black").length},renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes,fences:fenceEntries.length};}
function connection(connected){const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
function connection(connected){const changed=liveConnected!==connected;liveConnected=connected;const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';if(changed)syncTargetMarkers(true);}
function refresh(){tileRevision++;tileBuffer?.schedule();for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);}
function setBasemap(value){const next=value==='road'?'road':'imagery';if(next!==basemap){basemap=next;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);tileBuffer?.schedule();}}
function baseReady(ready){if(map?.getLayer('grid'))map.setLayoutProperty('grid','visibility',ready?'none':'visible');}
@@ -208,4 +263,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&&located(selected))focusCoordinate([latest[i*4],latest[i*4+1]]);}
window.ridMap={setSources,setFences,workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,focusRaw,metrics,connection,refresh,setBasemap,setClassification,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(){clearFenceMarkers();fenceEntries=[];tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];rawFocus=null;generations=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;classification=new Map();listFilter="all";sourceIds=null;occlusion={top:0,right:0,bottom:0,left:0};}};
window.ridMap={setSources,setFences,workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,focusRaw,updateRaw,metrics,connection,refresh,setBasemap,setClassification,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(){clearFenceMarkers();fenceEntries=[];tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;clearTargetMarkers();history=[];rawFocus=null;generations=null;markerInfos=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];idIndexes.clear();selected='';liveConnected=true;centered=false;classification=new Map();listFilter="all";sourceIds=null;occlusion={top:0,right:0,bottom:0,left:0};}};