Files
fpv-rid-workbench/crates/web-ui/public/map-tile-buffer.js
T
JiuContinent cd1b717e74 ```
feat(geofences): 新增地理围栏模块并优化地图瓦片缓存

在 rid-shared 中实现二维 WGS84 地理围栏核心逻辑,支持圆形与多边形
两种几何体,包含坐标合法性校验、边界包含判断及自相交检测。
realtime-core 的 Store 新增观察者回调,在观测数据接受后按到达顺序
通知监听器。

前端方面,新增 geofence-map-adapter.js 提供基于 MapLibre 的围栏绘制
与编辑能力,配套 geofences.css 完成响应式布局样式。map-loader.js
增加懒加载入口,仅在实时工作区按需引入围栏地图模块。

同时引入 map-tile-buffer 瓦片缓冲机制,改善地图切换与刷新时的加载
体验;将默认缩放级别从 11 调整为 15,使初始视图更贴近实际监测场景。
```
2026-10-23 13:55:08 +08:00

53 lines
4.2 KiB
JavaScript

// Shared, bounded viewport warming. Visible MapLibre requests always run first.
const pairs={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
export function attachTileBuffer(map,getKind,getRevision=()=>0){
let generation=0,closed=false,timer,cooldownUntil=0,controllers=new Set(),queue=[],running=0,lastSignature='',lastPrepared=0;
const warmed=new Map();
const metrics={requested:0,hits:0,cancelled:0,failed:0};
const url=(layer,z,x,y)=>`/api/maps/tile/${layer}/${z}/${x}/${y}${getRevision()?`?v=${getRevision()}`:''}`;
function cancel(){generation++;lastSignature='';clearTimeout(timer);timer=null;queue=[];for(const c of controllers)c.abort();controllers.clear();}
function pump(token){
if(closed||token!==generation||Date.now()<cooldownUntil)return;
while(running<4&&queue.length){
const item=queue.shift(),controller=new AbortController();controllers.add(controller);running++;metrics.requested++;
fetch(item,{signal:controller.signal,cache:'default',headers:{'x-rid-prefetch':'1'}}).then(async response=>{
if(response.status===429){if(token===generation){queue.unshift(item);cooldownUntil=Date.now()+500;setTimeout(()=>pump(token),550);}return;}
if(!response.ok){if(token===generation){cooldownUntil=Date.now()+30000;queue=[];}throw Error('tile unavailable');}await response.arrayBuffer();
warmed.delete(item);warmed.set(item,Date.now());while(warmed.size>4096)warmed.delete(warmed.keys().next().value);
}).catch(error=>{if(error.name==='AbortError')metrics.cancelled++;else {metrics.failed++;if(token===generation){cooldownUntil=Date.now()+30000;queue=[];}}}).finally(()=>{
controllers.delete(controller);running--;pump(generation);
});
}
}
function prepare(){
if(closed||running||queue.length||Date.now()<cooldownUntil||map.isMoving()||!map.isStyleLoaded())return;
const w=map.getCanvas().clientWidth,h=map.getCanvas().clientHeight;
if(!w||!h)return;
const c=map.getCenter(),signature=[c.lng,c.lat,map.getZoom(),map.getPitch(),map.getBearing(),w,h,getKind(),getRevision()].join('/');
if(signature===lastSignature&&Date.now()-lastPrepared<60000)return;
cancel();const token=generation;lastSignature=signature;lastPrepared=Date.now();
// A 256px raster source uses one level above the 512px MapLibre camera scale.
const detail=Math.min(18,Math.max(0,Math.round(map.getZoom()+1)));
const kind=getKind(),groups=[pairs[kind],pairs[kind==='road'?'imagery':'road']],unique=new Set();
// Warm the immediate parent too: raster fades can request it during a pan.
for(const layers of groups)for(const z of new Set([detail,Math.max(0,detail-1)])){
const n=2**z;
const tile=p=>{const c=map.unproject(p),lat=Math.max(-85.051128,Math.min(85.051128,c.lat))*Math.PI/180;return [(c.lng+180)/360*n,(1-Math.asinh(Math.tan(lat))/Math.PI)/2*n];};
const corners=[tile([-w,-h]),tile([2*w,-h]),tile([-w,2*h]),tile([2*w,2*h])],center=tile([w/2,h/2]);
const x0=Math.floor(Math.min(...corners.map(p=>p[0]))),x1=Math.floor(Math.max(...corners.map(p=>p[0])));
const y0=Math.max(0,Math.floor(Math.min(...corners.map(p=>p[1])))),y1=Math.min(n-1,Math.floor(Math.max(...corners.map(p=>p[1]))));
const cells=[];for(let x=x0;x<=Math.min(x1,x0+n-1);x++)for(let y=y0;y<=y1;y++)cells.push([x,y,(x-center[0])**2+(y-center[1])**2]);
cells.sort((a,b)=>a[2]-b[2]);
for(const [x,y]of cells.slice(0,4096))for(const layer of layers){
const key=url(layer,z,((x%n)+n)%n,y);if(unique.has(key))continue;unique.add(key);
if(Date.now()-(warmed.get(key)||0)<240000){metrics.hits++;continue;}queue.push(key);
}
}
pump(token);
}
const schedule=()=>{if(timer)return;timer=setTimeout(()=>{timer=null;prepare();},200);};
const sourcedata=e=>{if(/^(tdt-base|tdt-labels|base|labels)$/.test(e.sourceId)&&e.isSourceLoaded&&!running&&!queue.length)schedule();};
map.on('movestart',cancel);map.on('moveend',schedule);map.on('idle',schedule);map.on('load',schedule);map.on('sourcedata',sourcedata);
return {schedule(){cancel();cooldownUntil=0;lastSignature='';schedule();},metrics:()=>({...metrics,queued:queue.length,running,warmed:warmed.size}),destroy(){closed=true;cancel();map.off('movestart',cancel);map.off('moveend',schedule);map.off('idle',schedule);map.off('load',schedule);map.off('sourcedata',sourcedata);warmed.clear();}};
}