// Map rendering only. History queries and playback state live in Rust. import * as ml from './vendor/maplibre-gl.mjs'; import {attachTileBuffer} from './map-tile-buffer.js'; ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs'); let map,buffer,observer,marker,points=[],projected=[],index=0,progress=0,fitPending=false,kind='imagery'; let labels = true, registered, registrationGeneration = 0; const layers={imagery:['img_w','cia_w'],road:['vec_w','cva_w']}; const url=i=>`/api/maps/tile/${layers[kind][i]}/{z}/{x}/{y}`; function coordinate(point){ const lon=point?.longitude,lat=point?.latitude; return Number.isFinite(lon)&&Number.isFinite(lat)&&Math.abs(lon)<=180&&Math.abs(lat)<=90?[lon,lat]:null; } function paint(){ const source=map?.getSource('history-track'); if(!source)return; const segments=[];let segment=[]; for(const point of points){ const position=coordinate(point); if(!position)continue; if(point.segmentStart&&segment.length){if(segment.length>1)segments.push(segment);segment=[];} segment.push(position); } if(segment.length>1)segments.push(segment); source.setData({type:'FeatureCollection',features:segments.map(coordinates=>({type:'Feature',properties:{},geometry:{type:'LineString',coordinates}}))}); paintMarker(); if(fitPending&&points.length){ const bounds=new ml.LngLatBounds(); for(const point of points){const position=coordinate(point);if(position)bounds.extend(position);} if(!bounds.isEmpty())map.fitBounds(bounds,{padding:60,maxZoom:16,duration:0}); fitPending=false; } } const angleDelta = (from, to) => ((to - from + 540) % 360) - 180; function makeDroneMarker() { const element = window.ridDroneMap.createMarker(window.ridDroneMap.registrationColors(registered)); return new ml.Marker({element, anchor:'center', rotationAlignment:'map', pitchAlignment:'map', subpixelPositioning:true}); } function pointAlongEdge(from, to, fraction) { const east = to.x - from.x; const dx = Math.abs(east) > 0.5 ? east - Math.sign(east) : east; return new ml.MercatorCoordinate(from.x + dx * fraction, from.y + (to.y - from.y) * fraction, 0) .toLngLat().toArray(); } function paintMarker() { const current = points[index]; const from = coordinate(current); if (!map || !from) { marker?.remove(); marker = null; return; } const next = points[index + 1]; const to = !next?.segmentStart && next?.timeMs > current.timeMs ? coordinate(next) : null; const previous = !current.segmentStart ? coordinate(points[index - 1]) : null; const direction = (a, b) => window.ridDroneMap.trackHeading(a[1], a[0], b[1], b[0]); const course = to ? direction(from, to) : previous ? direction(previous, from) : undefined; const heading = Number.isFinite(current.headingDeg) ? current.headingDeg : course ?? 0; const destinationHeading = to && Number.isFinite(next.headingDeg) ? next.headingDeg : heading; const angle = heading + angleDelta(heading, destinationHeading) * progress; const position = to && progress > 0 ? pointAlongEdge(projected[index], projected[index + 1], progress) : from; if (!marker) marker = makeDroneMarker().setLngLat(position).setRotation(angle).addTo(map); else { if (marker.getRotation() !== angle) marker.setRotation(angle); const previousPosition = marker.getLngLat(); if (previousPosition.lng !== position[0] || previousPosition.lat !== position[1]) { marker.setLngLat(position); } } } export function setMapOptions(options) { const next = options.basemap === 'road' ? 'road' : 'imagery'; if (next !== kind) { kind = next; map?.getSource('base')?.setTiles([url(0)]); map?.getSource('labels')?.setTiles([url(1)]); buffer?.schedule(); } labels = options.labels !== false; if (map?.getLayer('labels')) map.setLayoutProperty('labels', 'visibility', labels ? 'visible' : 'none'); } export function open(p){ setMapOptions(p); if(map){map.resize();return;} try{ map=new ml.Map({container:'history-map',center:[p.longitude,p.latitude],zoom:p.zoom??15,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,attributionControl:false, style:{version:8,sources:{base:{type:'raster',tiles:[url(0)],tileSize:256,maxzoom:18},labels:{type:'raster',tiles:[url(1)],tileSize:256,maxzoom:18}}, layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels',layout:{visibility:labels?'visible':'none'}}]}}); buffer=attachTileBuffer(map,()=>kind);observer=new ResizeObserver(()=>map?.resize());observer.observe(document.getElementById('history-map')); map.addControl(new ml.NavigationControl({showCompass:false}),'bottom-right'); map.addControl(new ml.AttributionControl({customAttribution:'天地图 © 自然资源部 · 历史轨迹',compact:true}),'bottom-right'); map.on('style.load',()=>{map.addSource('history-track',{type:'geojson',data:{type:'FeatureCollection',features:[]}}); map.addLayer({id:'history-track',type:'line',source:'history-track',paint:{'line-color':'#80c4ff','line-width':4,'line-opacity':.95}});paint();}); map.on('error',e=>{if(!['base','labels'].includes(e.sourceId))window.dispatchEvent(new Event('rid-history-map-error'));}); }catch{close();window.dispatchEvent(new Event('rid-history-map-error'));} } export function setPoints(value, target) { points = Array.isArray(value) ? value : []; registered = undefined; marker?.remove(); marker = null; const generation = ++registrationGeneration; if (target && points.length) { fetch('/api/target-registration-status?' + new URLSearchParams({ids:target}), {cache:'no-store'}) .then(response => response.ok ? response.json() : null).then(result => { if (generation !== registrationGeneration || !result?.entries?.length) return; registered = result.entries[0].registered; const element = marker?.getElement(); if (element) { const {fill, glow} = window.ridDroneMap.registrationColors(registered); element.style.setProperty('--rid-drone-fill', fill); element.style.setProperty('--rid-drone-glow', glow); } }).catch(() => {}); } projected = points.map(point => { const position = coordinate(point); return position ? ml.MercatorCoordinate.fromLngLat(position) : null; }); index = 0; progress = 0; fitPending = true; paint(); } export function setCursor(value, fraction) { index = Math.max(0, Math.min(points.length - 1, Number(value) || 0)); progress = Math.max(0, Math.min(1, Number(fraction) || 0)); paintMarker(); } export function close(){buffer?.destroy();buffer=null;observer?.disconnect();observer=null;marker?.remove();marker=null;map?.remove();map=null;} export function metrics(){return {ready:!!map?.getSource('history-track'),points:points.length,index};}