2483 lines
113 KiB
JavaScript
2483 lines
113 KiB
JavaScript
let liveMap3D;
|
||
let wantMap3D = true;
|
||
let map3DActive = false;
|
||
let mapModeVersion = 0;
|
||
let applyingCamera = false;
|
||
let sceneFrame;
|
||
let resizeFrame;
|
||
let leafletZooming = false;
|
||
const trailSources = new Map();
|
||
let map = L.map('map', { zoomControl: false, zoomSnap: 0 }).setView([39.0708, 117.0271], 16);
|
||
const flightTrails = L.layerGroup();
|
||
const flightTrailToggle = document.getElementById('showFlightTrails');
|
||
const modelLabelToggle = document.getElementById('showModelLabels');
|
||
const pilotMarkerToggle = document.getElementById('showPilotMarkers');
|
||
const mapViewToggle = document.getElementById('mapViewToggle');
|
||
L.control.zoom({ position: 'bottomleft' }).addTo(map);
|
||
L.TileLayer.mergeOptions({ errorTileUrl: '/workbench/blank-tile.svg' });
|
||
|
||
|
||
// 页面通过 RID 接口适配器读取本机数据。
|
||
const apiPollState = { drones:false, alerts:false, stations:false };
|
||
async function apiFetchJson(url, options = {}, timeoutMs = 6000, retries = 0) {
|
||
let lastErr = null;
|
||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||
try {
|
||
const r = await window.ridWorkbenchApi.fetch(url, { cache:'no-store', ...options, signal: controller.signal });
|
||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||
return await r.json();
|
||
} catch (e) {
|
||
lastErr = e;
|
||
if (attempt < retries) await new Promise(resolve => setTimeout(resolve, 300));
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
}
|
||
throw lastErr || new Error('请求失败');
|
||
}
|
||
|
||
// V3.0:可选地图源 + 标注图层。
|
||
// V340.6:数据库/API始终保持原始 WGS84;仅高德地图/高德卫星显示层转换为 GCJ-02。
|
||
// 天地图、OSM、Esri 等底图继续直接使用 WGS84。所有坐标转换只发生在前端显示层。
|
||
// 天地图Key由平台后端 / 地图管理页面保存,瓦片请求统一走 /map_tiles 代理。
|
||
|
||
// 本地版实时目标缓存:接口偶发空列表时,不立即清空地图,避免“显示一下就消失/不更新”。
|
||
const recentlySeenDrones = new Map();
|
||
const DRONE_MAP_TTL_MS = 90 * 1000;
|
||
let droneLastSeenAt = {};
|
||
let trackedDroneKey = null;
|
||
let overviewLocked = false;
|
||
let suppressAutoFocusUntil = 0;
|
||
|
||
// V340.7.7 地图视图状态:
|
||
// auto = 尚未人工接管时允许首次目标自动定位;
|
||
// overview = 用户点击“空域总览”,只执行一次全局适配;
|
||
// station = 用户点击侦测器,停留在该侦测器位置;
|
||
// tracking = 用户点击无人机目标,持续跟踪该目标;
|
||
// manual = 用户手动拖动/缩放后永久保持当前视角,直到再次点击总览/侦测器/无人机。
|
||
let mapViewMode = 'auto';
|
||
const MAP_VIEW_STORAGE_KEY = 'bsrid_manual_map_view_v1';
|
||
let viewReady = false;
|
||
let savedCamera = null;
|
||
let viewSaveTimer;
|
||
let viewSaveChain = Promise.resolve();
|
||
|
||
function saveViewPatch(patch, keepalive = false) {
|
||
const write = () => window.ridWorkbenchApi.request('/api/workbench/view', 'PUT', patch, {keepalive});
|
||
const result = viewSaveChain.then(write, write);
|
||
viewSaveChain = result.catch(() => {});
|
||
return result;
|
||
}
|
||
|
||
function viewSaveError(error) {
|
||
console.warn('工作台状态保存失败', error);
|
||
const notice = document.getElementById('rid-workbench-status');
|
||
notice.hidden = false;
|
||
notice.textContent = '工作台状态保存失败,请检查服务连接后重试。';
|
||
}
|
||
|
||
function setMapViewMode(mode, trackKey = null) {
|
||
mapViewMode = mode || 'auto';
|
||
overviewLocked = mapViewMode === 'overview';
|
||
trackedDroneKey = mapViewMode === 'tracking' ? (trackKey || trackedDroneKey) : null;
|
||
// 进入明确的人工/总览/设备视角后,不允许后台轮询重新抢地图中心。
|
||
suppressAutoFocusUntil = mapViewMode === 'auto' ? 0 : Number.MAX_SAFE_INTEGER;
|
||
try { renderDrones(); } catch (_) {}
|
||
}
|
||
|
||
function takeManualMapControl() {
|
||
if (drawing) return;
|
||
|
||
if (mapViewMode === 'manual' && !trackedDroneKey && !overviewLocked) return;
|
||
setMapViewMode('manual');
|
||
}
|
||
|
||
function saveManualMapView() {
|
||
if (!viewReady) return;
|
||
try {
|
||
const c = map.getCenter();
|
||
const raw = fromMapLatLng(c.lat, c.lng);
|
||
const payload = {
|
||
lat: Number(raw[0]),
|
||
lng: Number(raw[1]),
|
||
zoom: Number(map.getZoom()),
|
||
pitch: liveMap3D?.getCamera().pitch ?? savedCamera?.pitch ?? 52,
|
||
bearing: liveMap3D?.getCamera().bearing ?? savedCamera?.bearing ?? 0,
|
||
mode3d: wantMap3D
|
||
};
|
||
if (Number.isFinite(payload.lat) && Number.isFinite(payload.lng) && Number.isFinite(payload.zoom)) {
|
||
try { localStorage.setItem(MAP_VIEW_STORAGE_KEY, JSON.stringify(payload)); } catch (_) {}
|
||
savedCamera = payload;
|
||
clearTimeout(viewSaveTimer);
|
||
viewSaveTimer = setTimeout(() => saveViewPatch({camera:payload}).catch(viewSaveError), 400);
|
||
}
|
||
} catch (_) {}
|
||
}
|
||
|
||
function restoreManualMapView(camera) {
|
||
try {
|
||
const saved = camera || JSON.parse(localStorage.getItem(MAP_VIEW_STORAGE_KEY) || 'null');
|
||
if (!saved || !Number.isFinite(Number(saved.lat)) || !Number.isFinite(Number(saved.lng)) || !Number.isFinite(Number(saved.zoom))) return false;
|
||
setMapViewMode('manual');
|
||
savedCamera = {lat:Number(saved.lat), lng:Number(saved.lng), zoom:Number(saved.zoom),
|
||
pitch:saved.pitch ?? 52, bearing:saved.bearing ?? 0, mode3d:saved.mode3d ?? true};
|
||
wantMap3D = savedCamera.mode3d;
|
||
mapSetViewWgs84(Number(saved.lat), Number(saved.lng), Number(saved.zoom), { animate: false });
|
||
return true;
|
||
} catch (_) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
const TDT_KEY = '';
|
||
let customMapCoord = 'wgs84';
|
||
let customMapName = '专网自定义地图';
|
||
let customMapMaxZoom = 18;
|
||
|
||
// V3.16:地图瓦片本地缓存。所有底图走本地代理,平台会在 map_cache 文件夹保存瓦片。
|
||
function cachedTileUrl(source) {
|
||
const layers = { tdt_vec: 'vec_w', tdt_cva: 'cva_w', tdt_img: 'img_w', tdt_cia: 'cia_w' };
|
||
return layers[source] ? `/api/maps/tile/${layers[source]}/{z}/{x}/{y}` : '/workbench/blank-tile.svg';
|
||
}
|
||
|
||
const tdtVectorBase = L.tileLayer(cachedTileUrl('tdt_vec'), {
|
||
subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'], maxZoom: 18, attribution: '© 天地图'
|
||
});
|
||
const tdtVectorLabel = L.tileLayer(cachedTileUrl('tdt_cva'), {
|
||
subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'], maxZoom: 18
|
||
});
|
||
const tdtSatelliteBase = L.tileLayer(cachedTileUrl('tdt_img'), {
|
||
subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'], maxZoom: 18, attribution: '© 天地图'
|
||
});
|
||
const tdtSatelliteLabel = L.tileLayer(cachedTileUrl('tdt_cia'), {
|
||
subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'], maxZoom: 18
|
||
});
|
||
const amapVectorBase = L.tileLayer(cachedTileUrl('amap_vec'), {
|
||
subdomains: ['1', '2', '3', '4'], maxZoom: 18, attribution: '© 高德地图'
|
||
});
|
||
const amapSatelliteBase = L.tileLayer(cachedTileUrl('amap_img'), {
|
||
subdomains: ['1', '2', '3', '4'], maxZoom: 18, attribution: '© 高德地图'
|
||
});
|
||
const amapSatelliteLabel = L.tileLayer(cachedTileUrl('amap_lbl'), {
|
||
subdomains: ['1', '2', '3', '4'], maxZoom: 18
|
||
});
|
||
const osmVectorBase = L.tileLayer(cachedTileUrl('osm'), {
|
||
maxZoom: 19, attribution: '© OpenStreetMap'
|
||
});
|
||
const esriSatelliteBase = L.tileLayer(cachedTileUrl('esri_img'), {
|
||
maxZoom: 19, attribution: 'Tiles © Esri'
|
||
});
|
||
const customXyzBase = L.tileLayer(cachedTileUrl('custom_xyz'), {
|
||
maxZoom: 22, attribution: '© 自定义地图源'
|
||
});
|
||
|
||
const baseLayers = {
|
||
'tdt-satellite': { name: '天地图影像', icon: '▧', needKey: true, base: tdtSatelliteBase, label: tdtSatelliteLabel, coord: 'wgs84' },
|
||
'tdt-vector': { name: '天地图矢量', icon: '▦', needKey: true, base: tdtVectorBase, label: tdtVectorLabel, coord: 'wgs84' },
|
||
'amap-vector': { name: '高德地图', icon: '▦', base: amapVectorBase, label: null, coord: 'gcj02' },
|
||
'amap-satellite': { name: '高德卫星', icon: '▧', base: amapSatelliteBase, label: amapSatelliteLabel, coord: 'gcj02' },
|
||
'osm-vector': { name: 'OSM地图', icon: '▦', base: osmVectorBase, label: null, coord: 'wgs84' },
|
||
'esri-satellite': { name: 'Esri卫星', icon: '▧', base: esriSatelliteBase, label: tdtSatelliteLabel, coord: 'wgs84' },
|
||
'custom-xyz': { name: '专网自定义地图', icon: '▦', base: customXyzBase, label: null, coord: 'wgs84' }
|
||
};
|
||
const DEFAULT_MAP_KEY = 'tdt-satellite';
|
||
function mapKeyFromConfigValue(value) {
|
||
const v = String(value || '').trim();
|
||
if (baseLayers[v]) return v;
|
||
const hit = Object.entries(baseLayers).find(([, cfg]) => cfg.name === v);
|
||
return hit ? hit[0] : DEFAULT_MAP_KEY;
|
||
}
|
||
function mapNameFromKey(key) {
|
||
if (key === 'custom-xyz') return customMapName || '专网自定义地图';
|
||
return baseLayers[key]?.name || baseLayers[DEFAULT_MAP_KEY].name;
|
||
}
|
||
|
||
// V340.6:沿用云平台 V3.41.44 已验证的“只转换显示层”思路。
|
||
// 数据库、接口、RID解析及报警判断全部继续使用 WGS84 原始坐标。
|
||
const GCJ_PI = Math.PI;
|
||
const GCJ_A = 6378245.0;
|
||
const GCJ_EE = 0.00669342162296594323;
|
||
|
||
function isGcjMapKey(key) {
|
||
if (key === 'custom-xyz') return customMapCoord === 'gcj02';
|
||
return baseLayers[key]?.coord === 'gcj02';
|
||
}
|
||
|
||
function outOfChina(lat, lng) {
|
||
return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271;
|
||
}
|
||
|
||
function gcjTransformLat(x, y) {
|
||
let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
|
||
ret += (20.0 * Math.sin(6.0 * x * GCJ_PI) + 20.0 * Math.sin(2.0 * x * GCJ_PI)) * 2.0 / 3.0;
|
||
ret += (20.0 * Math.sin(y * GCJ_PI) + 40.0 * Math.sin(y / 3.0 * GCJ_PI)) * 2.0 / 3.0;
|
||
ret += (160.0 * Math.sin(y / 12.0 * GCJ_PI) + 320 * Math.sin(y * GCJ_PI / 30.0)) * 2.0 / 3.0;
|
||
return ret;
|
||
}
|
||
|
||
function gcjTransformLng(x, y) {
|
||
let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
|
||
ret += (20.0 * Math.sin(6.0 * x * GCJ_PI) + 20.0 * Math.sin(2.0 * x * GCJ_PI)) * 2.0 / 3.0;
|
||
ret += (20.0 * Math.sin(x * GCJ_PI) + 40.0 * Math.sin(x / 3.0 * GCJ_PI)) * 2.0 / 3.0;
|
||
ret += (150.0 * Math.sin(x / 12.0 * GCJ_PI) + 300.0 * Math.sin(x / 30.0 * GCJ_PI)) * 2.0 / 3.0;
|
||
return ret;
|
||
}
|
||
|
||
function wgs84ToGcj02(lat, lng) {
|
||
lat = Number(lat); lng = Number(lng);
|
||
if (!Number.isFinite(lat) || !Number.isFinite(lng) || outOfChina(lat, lng)) return [lat, lng];
|
||
let dLat = gcjTransformLat(lng - 105.0, lat - 35.0);
|
||
let dLng = gcjTransformLng(lng - 105.0, lat - 35.0);
|
||
const radLat = lat / 180.0 * GCJ_PI;
|
||
let magic = Math.sin(radLat);
|
||
magic = 1 - GCJ_EE * magic * magic;
|
||
const sqrtMagic = Math.sqrt(magic);
|
||
dLat = (dLat * 180.0) / ((GCJ_A * (1 - GCJ_EE)) / (magic * sqrtMagic) * GCJ_PI);
|
||
dLng = (dLng * 180.0) / (GCJ_A / sqrtMagic * Math.cos(radLat) * GCJ_PI);
|
||
return [lat + dLat, lng + dLng];
|
||
}
|
||
|
||
// 高德地图上绘制防控区时,需要把用户点击的 GCJ-02 显示坐标反算回 WGS84 后再保存。
|
||
// 采用迭代反算,避免把高德坐标写入数据库造成二次偏移。
|
||
function gcj02ToWgs84(lat, lng) {
|
||
lat = Number(lat); lng = Number(lng);
|
||
if (!Number.isFinite(lat) || !Number.isFinite(lng) || outOfChina(lat, lng)) return [lat, lng];
|
||
let wLat = lat, wLng = lng;
|
||
for (let i = 0; i < 8; i++) {
|
||
const g = wgs84ToGcj02(wLat, wLng);
|
||
const dLat = g[0] - lat;
|
||
const dLng = g[1] - lng;
|
||
wLat -= dLat;
|
||
wLng -= dLng;
|
||
if (Math.abs(dLat) < 1e-8 && Math.abs(dLng) < 1e-8) break;
|
||
}
|
||
return [wLat, wLng];
|
||
}
|
||
|
||
function toMapLatLngForKey(lat, lng, key) {
|
||
lat = Number(lat); lng = Number(lng);
|
||
return isGcjMapKey(key) ? wgs84ToGcj02(lat, lng) : [lat, lng];
|
||
}
|
||
|
||
function fromMapLatLngForKey(lat, lng, key) {
|
||
lat = Number(lat); lng = Number(lng);
|
||
return isGcjMapKey(key) ? gcj02ToWgs84(lat, lng) : [lat, lng];
|
||
}
|
||
|
||
function toMapLatLng(lat, lng) {
|
||
return toMapLatLngForKey(lat, lng, currentBaseLayerKey);
|
||
}
|
||
|
||
function fromMapLatLng(lat, lng) {
|
||
return fromMapLatLngForKey(lat, lng, currentBaseLayerKey);
|
||
}
|
||
|
||
function mapSetViewWgs84(lat, lng, zoom, options) {
|
||
const p = toMapLatLng(lat, lng);
|
||
map.setView(p, zoom, options);
|
||
}
|
||
|
||
function mapPanToWgs84(lat, lng, options) {
|
||
const p = toMapLatLng(lat, lng);
|
||
map.panTo(p, options);
|
||
}
|
||
|
||
function toMapHeatPoints(points) {
|
||
// 统一热力点入口:输入始终按 WGS84,[lat,lng,weight?] 输出当前底图显示坐标。
|
||
return (points || []).map(p => {
|
||
const lat = Array.isArray(p) ? p[0] : p.lat;
|
||
const lng = Array.isArray(p) ? p[1] : p.lng;
|
||
const weight = Array.isArray(p) ? p[2] : (p.weight ?? p.value);
|
||
const m = toMapLatLng(lat, lng);
|
||
return weight === undefined ? [m[0], m[1]] : [m[0], m[1], weight];
|
||
});
|
||
}
|
||
|
||
let currentBaseLayerKey = DEFAULT_MAP_KEY;
|
||
let currentBaseLayer = null;
|
||
let currentLabelLayer = null;
|
||
let mapLabelsVisible = true;
|
||
setBaseMap(currentBaseLayerKey);
|
||
let drones = [], markers = {}, tracks = {}, droneTrackRaw = {}, zones = [], zoneLayers = {}, alerts = [], deviceMarkers = {}, stationMarkers = {}, localStations = [];
|
||
const pilotMarkers = new Map();
|
||
let lastDeviceStatus = null;
|
||
let drawing = false, drawMode = 'polygon', drawPoints = [], drawLayer = null;
|
||
let activeSearchKey = '';
|
||
const sideState = { left: true, right: true };
|
||
const compactOverview = window.matchMedia('(max-width: 1100px)');
|
||
let activeOverviewSide = null;
|
||
const clearedAlarmKey = 'rid-workbench-cleared-alarm-id';
|
||
let alarmDurationMs = 10000;
|
||
let alertCounts = { read: 0, unread: 0 };
|
||
let alertReadRevision = 0;
|
||
let canAcknowledgeAlert = false;
|
||
const alarmPageOpenedAt = Date.now();
|
||
const alertPriority = {unfiled:2, unregistered:3, blacklist:4, geofence_enter:5};
|
||
let clearedAlarmId = readClearedAlarmId();
|
||
let latestAlarmId = 0;
|
||
let activeAlarm = null;
|
||
let alarmTimer;
|
||
let pendingAlarmEffects = [];
|
||
let lastAutoFocusKey = null;
|
||
let lastAutoFocusAt = 0;
|
||
let lastAlarmSoundAt = 0;
|
||
let lastAlarmSoundKey = '';
|
||
let currentAlertAudio = null;
|
||
|
||
// V340.7.7 六套语音:
|
||
// 防区外 discovery;防区内 alarm。
|
||
// 1=未登记(以及其它未单独指定类别兜底),2=白名单,3=黑名单。
|
||
const alertAudioBank = {
|
||
discovery: {
|
||
1: new Audio('/workbench/assets/discovery_1.wav'),
|
||
2: new Audio('/workbench/assets/discovery_2.wav'),
|
||
3: new Audio('/workbench/assets/discovery_3.wav')
|
||
},
|
||
alarm: {
|
||
1: new Audio('/workbench/assets/alarm_1.wav'),
|
||
2: new Audio('/workbench/assets/alarm_2.wav'),
|
||
3: new Audio('/workbench/assets/alarm_3.wav')
|
||
}
|
||
};
|
||
Object.values(alertAudioBank).forEach(group => Object.values(group).forEach(a => { try { a.preload = 'auto'; } catch (_) {} }));
|
||
|
||
function headingNumber(v) {
|
||
const m = String(v ?? '').match(/-?\d+(?:\.\d+)?/);
|
||
if (!m) return null;
|
||
const n = Number(m[0]);
|
||
return Number.isFinite(n) ? ((n % 360) + 360) % 360 : null;
|
||
}
|
||
function registryMeta(item) {
|
||
const cls = item?.flightClass || 'unknown';
|
||
const meta = window.ridFlightStatus.meta(cls);
|
||
return {cls,label:meta.label,tag:'flightTag '+meta.tone};
|
||
}
|
||
|
||
function addModelLabel(body, model) {
|
||
const badge = document.createElement('span');
|
||
badge.className = 'rid-pair-label';
|
||
badge.title = model;
|
||
badge.textContent = model;
|
||
body.append(badge);
|
||
}
|
||
|
||
function makeDroneIcon(item) {
|
||
const body = window.ridDroneMap.createMarker({
|
||
...window.ridFlightStatus.colors(item.flightClass), heading: item.heading ?? 0, opacity: item.online ? 1 : 0.68
|
||
});
|
||
addModelLabel(body, item.model);
|
||
return L.divIcon({ className: '', html: body, iconSize: [32, 32], iconAnchor: [16, 16] });
|
||
}
|
||
|
||
function makePilotIcon(model, slot = 0) {
|
||
const body = document.createElement('div');
|
||
body.className = 'rid-pilot-marker';
|
||
body.setAttribute('aria-hidden', 'true');
|
||
body.textContent = '🎮';
|
||
body.style.setProperty('--rid-pilot-label-offset', slot * 27 + 'px');
|
||
addModelLabel(body, model);
|
||
return L.divIcon({ className: '', html: body, iconSize: [32, 32], iconAnchor: [16, 16] });
|
||
}
|
||
const deviceIcon = L.divIcon({ className: '', html: '<div title="侦测器" style="width:30px;height:30px;border-radius:8px;display:grid;place-items:center;background:rgba(72,140,255,.94);border:2px solid rgba(255,255,255,.92);box-shadow:0 0 16px rgba(72,140,255,.85);font-size:17px">📡</div>', iconSize: [32, 32], iconAnchor: [16, 16] });
|
||
const deviceOfflineIcon = L.divIcon({ className: '', html: '<div title="侦测器离线" style="width:30px;height:30px;border-radius:8px;display:grid;place-items:center;background:rgba(255,76,96,.94);border:2px solid rgba(255,255,255,.92);box-shadow:0 0 16px rgba(255,76,96,.78);font-size:17px">📡</div>', iconSize: [32, 32], iconAnchor: [16, 16] });
|
||
|
||
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, m => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m])) }
|
||
function escAttr(s) { return esc(s).replace(/`/g, '`') }
|
||
|
||
function safeText(id, text) {
|
||
const el = document.getElementById(id);
|
||
if (el) el.textContent = text ?? '';
|
||
return !!el;
|
||
}
|
||
function safeHtml(id, html) {
|
||
const el = document.getElementById(id);
|
||
if (el) el.innerHTML = html ?? '';
|
||
return !!el;
|
||
}
|
||
function validCoord(x, y) {
|
||
const one = v => {
|
||
if (v === null || v === undefined || v === '' || v === '待解析') return false;
|
||
const n = Number(v);
|
||
return Number.isFinite(n);
|
||
};
|
||
if (!one(x)) return false;
|
||
if (arguments.length < 2) return true;
|
||
if (!one(y)) return false;
|
||
const lat = Number(x), lng = Number(y);
|
||
if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return false;
|
||
// 0,0是设备未定位常见占位值,不能作为真实坐标显示。
|
||
if (Math.abs(lat) < 1e-7 && Math.abs(lng) < 1e-7) return false;
|
||
return true;
|
||
}
|
||
function haversineMeters(lat1, lng1, lat2, lng2) {
|
||
const R = 6371000;
|
||
const toRad = d => d * Math.PI / 180;
|
||
const p1 = toRad(lat1), p2 = toRad(lat2);
|
||
const dp = toRad(lat2 - lat1), dl = toRad(lng2 - lng1);
|
||
const a = Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
|
||
return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||
}
|
||
function fmtDistanceMeters(m) {
|
||
if (!isFinite(m)) return '--';
|
||
return m >= 1000 ? (m / 1000).toFixed(2) + 'km' : Math.round(m) + 'm';
|
||
}
|
||
|
||
// V340.7.12 轨迹显示稳定保护。
|
||
// 只作用于地图显示/轨迹绘制,不修改数据库原始RID记录、解析、报警、防控区判断。
|
||
// 目的:过滤“上一帧在A -> 单帧突然跳到远处B -> 下一帧马上回A”的明显异常尖刺。
|
||
const droneDisplayPositionState = {};
|
||
const TRACK_SPIKE_BASE_METERS = 260;
|
||
const TRACK_SPIKE_MAX_SPEED_MPS = 120; // 非常宽松,远高于常规无人机速度,避免误伤真实飞行。
|
||
const TRACK_SPIKE_CONFIRM_METERS = 220;
|
||
const TRACK_SPIKE_CONFIRM_MS = 6000;
|
||
|
||
function maxReasonableTrackJumpMeters(dtSec) {
|
||
const dt = Number.isFinite(Number(dtSec)) ? Math.max(0.5, Number(dtSec)) : 1.5;
|
||
return TRACK_SPIKE_BASE_METERS + TRACK_SPIKE_MAX_SPEED_MPS * dt;
|
||
}
|
||
|
||
function stableDisplayPosition(key, lat, lng, time, sampleId) {
|
||
let st = droneDisplayPositionState[key];
|
||
if (!st) {
|
||
const result = {lat, lng, accepted:true};
|
||
droneDisplayPositionState[key] = { lat, lng, acceptedAt:time, pending:null, sampleId, result };
|
||
return result;
|
||
}
|
||
if (st.sampleId === sampleId) return st.result;
|
||
st.sampleId = sampleId;
|
||
|
||
const dist = haversineMeters(st.lat, st.lng, lat, lng);
|
||
const dtSec = Math.max(0.5, (time - st.acceptedAt) / 1000);
|
||
const limit = maxReasonableTrackJumpMeters(dtSec);
|
||
|
||
if (dist <= limit) {
|
||
Object.assign(st, {lat, lng, acceptedAt:time, pending:null});
|
||
return st.result = {lat, lng, accepted:true};
|
||
}
|
||
|
||
// 大跳变先只挂起一帧。下一帧如果再次落在同一新区域,才认为是真实位置变化;
|
||
// 如果下一帧回到原轨迹,则本帧不会进入地图轨迹。
|
||
if (st.pending && time >= st.pending.at && time - st.pending.at <= TRACK_SPIKE_CONFIRM_MS) {
|
||
const confirmDist = haversineMeters(st.pending.lat, st.pending.lng, lat, lng);
|
||
if (confirmDist <= TRACK_SPIKE_CONFIRM_METERS) {
|
||
Object.assign(st, {lat, lng, acceptedAt:time, pending:null});
|
||
return st.result = {lat, lng, accepted:true, confirmedJump:true};
|
||
}
|
||
}
|
||
st.pending = {lat, lng, at:time};
|
||
return st.result = {lat:st.lat, lng:st.lng, accepted:false};
|
||
}
|
||
|
||
function pad2(n) { return String(n).padStart(2, '0'); }
|
||
function toDatetimeLocalValue(d) {
|
||
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
||
}
|
||
function metersBetween(a, b) { return map.distance([a.lat, a.lng], [b.lat, b.lng]) }
|
||
function formatMeters(m) {
|
||
const n = Number(m);
|
||
if (!isFinite(n)) return '--';
|
||
if (n >= 1000) return (n / 1000).toFixed(n >= 10000 ? 1 : 2) + 'km';
|
||
return Math.round(n) + 'm';
|
||
}
|
||
function polygonAreaMeters(points) {
|
||
if (!points || points.length < 3) return 0;
|
||
const lat0 = points.reduce((sum, p) => sum + Number(p.lat || 0), 0) / points.length;
|
||
const kx = 111320 * Math.cos(lat0 * Math.PI / 180);
|
||
const ky = 110540;
|
||
const xy = points.map(p => ({ x: Number(p.lng) * kx, y: Number(p.lat) * ky }));
|
||
let area = 0;
|
||
for (let i = 0, j = xy.length - 1; i < xy.length; j = i++) {
|
||
area += (xy[j].x * xy[i].y - xy[i].x * xy[j].y);
|
||
}
|
||
return Math.abs(area / 2);
|
||
}
|
||
function formatArea(area) {
|
||
const n = Number(area);
|
||
if (!isFinite(n) || n <= 0) return '--';
|
||
if (n >= 1000000) return (n / 1000000).toFixed(2) + 'km²';
|
||
return Math.round(n) + 'm²';
|
||
}
|
||
function zoneMeasureText(z) {
|
||
const pts = z.points || [];
|
||
if (z.type === 'circle' && pts.length) {
|
||
const r = Number(pts[0].radius || 0);
|
||
return '半径 ' + formatMeters(r) + ',直径 ' + formatMeters(r * 2);
|
||
}
|
||
if (z.type === 'rectangle' && pts.length >= 2) {
|
||
const a = pts[0], b = pts[1];
|
||
const width = metersBetween({ lat: a.lat, lng: a.lng }, { lat: a.lat, lng: b.lng });
|
||
const height = metersBetween({ lat: a.lat, lng: a.lng }, { lat: b.lat, lng: a.lng });
|
||
return '长 ' + formatMeters(Math.max(width, height)) + ',宽 ' + formatMeters(Math.min(width, height));
|
||
}
|
||
if (z.type === 'polygon' && pts.length >= 3) {
|
||
return '面积约 ' + formatArea(polygonAreaMeters(pts));
|
||
}
|
||
return '';
|
||
}
|
||
const zoneTypeNames = { circle: '圆形', rectangle: '矩形', polygon: '多边形' };
|
||
|
||
function zonePopupInfo(zone) {
|
||
return {
|
||
name: zone.name,
|
||
description: [zoneTypeNames[zone.type], zoneMeasureText(zone)].filter(Boolean).join(' · ')
|
||
};
|
||
}
|
||
|
||
function createZonePopupContent({name, description}) {
|
||
const content = document.createElement('div');
|
||
content.className = 'zonePopupCard';
|
||
const title = document.createElement('strong');
|
||
title.textContent = name;
|
||
content.append(title);
|
||
if (description) {
|
||
const details = document.createElement('div');
|
||
details.className = 'zonePopupMeta';
|
||
details.textContent = description;
|
||
content.append(details);
|
||
}
|
||
return content;
|
||
}
|
||
function normText(s) { return String(s ?? '').toLowerCase().replace(/\s+/g, '') }
|
||
function fuzzyMatch(text, key) {
|
||
const t = normText(text);
|
||
const k = normText(key);
|
||
if (!k) return true;
|
||
if (t.includes(k)) return true;
|
||
let i = 0;
|
||
for (const ch of t) {
|
||
if (ch === k[i]) i++;
|
||
if (i >= k.length) return true;
|
||
}
|
||
return false;
|
||
}
|
||
function getDroneSearchText(x) {
|
||
return [x.uasId, x.model, x.bssid, x.rssi, x.lat, x.lng].join(' ');
|
||
}
|
||
function getFilteredDrones(rows = drones) {
|
||
return rows.filter(x => fuzzyMatch(getDroneSearchText(x), activeSearchKey));
|
||
}
|
||
|
||
|
||
function setBaseMap(key) {
|
||
const cfg = baseLayers[key];
|
||
if (!cfg) return;
|
||
|
||
// V3.18:天地图 Key 改由后端 map_cache_settings.json 统一保存,
|
||
// 前端所有瓦片均走 /map_tiles 代理,因此这里不再用本地空 TDT_KEY 拦截切换。
|
||
// V340.6:切换底图时只切换“显示坐标系”,原始数据仍保持 WGS84。
|
||
const oldKey = currentBaseLayerKey;
|
||
const oldCenter = map.getCenter();
|
||
const oldZoom = map.getZoom();
|
||
const centerWgs = fromMapLatLngForKey(oldCenter.lat, oldCenter.lng, oldKey);
|
||
|
||
if (currentLabelLayer) {
|
||
map.removeLayer(currentLabelLayer);
|
||
currentLabelLayer = null;
|
||
}
|
||
if (currentBaseLayer) {
|
||
map.removeLayer(currentBaseLayer);
|
||
}
|
||
|
||
currentBaseLayerKey = key;
|
||
currentBaseLayer = cfg.base;
|
||
currentBaseLayer.addTo(map);
|
||
if (mapLabelsVisible && cfg.label) {
|
||
currentLabelLayer = cfg.label;
|
||
currentLabelLayer.addTo(map);
|
||
}
|
||
|
||
const newCenter = toMapLatLngForKey(centerWgs[0], centerWgs[1], key);
|
||
map.setView(newCenter, oldZoom, { animate: false });
|
||
|
||
const icon = document.getElementById('baseMapIcon');
|
||
if (icon) icon.textContent = cfg.icon || '▦';
|
||
const sel = document.getElementById('mapSourceSelect');
|
||
if (sel && sel.value !== key) sel.value = key;
|
||
const labelCtl = document.getElementById('labelToggle');
|
||
if (labelCtl) labelCtl.disabled = !cfg.label;
|
||
|
||
setTimeout(() => {
|
||
map.invalidateSize();
|
||
try { redrawCoordinateLayers(); } catch (e) { console.warn('坐标图层重绘失败', e); }
|
||
}, 0);
|
||
showMapCoordNotice();
|
||
if (map3DActive) {
|
||
liveMap3D.setBasemap(sceneBasemap());
|
||
sync3DCamera();
|
||
}
|
||
}
|
||
|
||
function redrawCoordinateLayers() {
|
||
Object.values(zoneLayers).forEach(layer => map.removeLayer(layer));
|
||
zoneLayers = {};
|
||
for (const zone of zones) if (zone.enabled) zoneLayers[zone.id] = drawZoneLayer(zone);
|
||
updateMapStations(localStations);
|
||
updateMapDevices(lastDeviceStatus);
|
||
updateMapDrones(false);
|
||
refreshSceneFences();
|
||
}
|
||
|
||
async function applySavedDefaultMap() {
|
||
try {
|
||
const data = await apiGet('/api/platform_configs');
|
||
const item = (data.configs || []).find(x => x.key === 'default_map');
|
||
const key = mapKeyFromConfigValue(item?.value);
|
||
setBaseMap(key);
|
||
} catch (e) {
|
||
console.warn('读取默认地图失败,使用当前底图', e);
|
||
}
|
||
}
|
||
|
||
async function refreshMapCacheQuickToggle() {
|
||
try {
|
||
const data = await apiGet('/api/map_cache/status');
|
||
customMapCoord = data.customCoord === 'gcj02' ? 'gcj02' : 'wgs84';
|
||
customMapName = data.customTileName || '专网自定义地图';
|
||
customMapMaxZoom = Number(data.customMaxZoom || 18);
|
||
if (baseLayers['custom-xyz']) { baseLayers['custom-xyz'].name = customMapName; baseLayers['custom-xyz'].coord = customMapCoord; customXyzBase.options.maxZoom = customMapMaxZoom; }
|
||
const el = document.getElementById('mapCacheQuickToggle');
|
||
if (el) el.checked = data.enabled !== false;
|
||
} catch (e) {}
|
||
}
|
||
|
||
async function toggleMapCacheQuick(enabled) {
|
||
try {
|
||
const cur = await apiGet('/api/map_cache/status').catch(() => ({}));
|
||
const data = await apiSend('/api/map_cache/settings', 'POST', { enabled: !!enabled, offlineOnly: cur.offlineOnly === true });
|
||
const el = document.getElementById('mapCacheResult');
|
||
if (el) el.innerHTML = renderMapCacheStatus(data);
|
||
reloadBaseMapLayer();
|
||
} catch (e) {
|
||
alert('地图缓存设置保存失败:' + e);
|
||
refreshMapCacheQuickToggle();
|
||
}
|
||
}
|
||
|
||
function toggleMapLabels(show) {
|
||
mapLabelsVisible = !!show;
|
||
const cfg = baseLayers[currentBaseLayerKey];
|
||
if (currentLabelLayer) {
|
||
map.removeLayer(currentLabelLayer);
|
||
currentLabelLayer = null;
|
||
}
|
||
if (mapLabelsVisible && cfg && cfg.label) {
|
||
currentLabelLayer = cfg.label;
|
||
currentLabelLayer.addTo(map);
|
||
}
|
||
if (map3DActive) liveMap3D.setBasemap(sceneBasemap());
|
||
}
|
||
|
||
function showMapCoordNotice() {
|
||
const cfg = baseLayers[currentBaseLayerKey];
|
||
if (!cfg) return;
|
||
if (cfg.coord === 'gcj02') {
|
||
console.info('高德底图:显示层已启用 WGS84 → GCJ-02 转换;数据库/API仍保持原始 WGS84。');
|
||
}
|
||
}
|
||
|
||
// 保留旧函数名,避免旧按钮或缓存页面调用时报错。
|
||
function toggleBaseMap() {
|
||
setBaseMap(currentBaseLayerKey === 'amap-vector' ? 'amap-satellite' : 'amap-vector');
|
||
}
|
||
|
||
function toggleSidePanel(side) {
|
||
if (compactOverview.matches) {
|
||
activeOverviewSide = activeOverviewSide === side ? null : side;
|
||
} else {
|
||
sideState[side] = !sideState[side];
|
||
}
|
||
syncOverviewPanels();
|
||
}
|
||
|
||
function syncOverviewPanels() {
|
||
const main = document.querySelector('.main');
|
||
for (const [side, label, openArrow, closeArrow] of [
|
||
['left', '设备与目标', '›', '‹'],
|
||
['right', '防控区与告警', '‹', '›'],
|
||
]) {
|
||
const expanded = compactOverview.matches ? activeOverviewSide === side : sideState[side];
|
||
main.classList.toggle(side + '-collapsed', !expanded);
|
||
const button = main.querySelector('.' + side + 'Toggle');
|
||
button.textContent = expanded ? closeArrow : openArrow;
|
||
button.title = (expanded ? '收起' : '展开') + label;
|
||
button.setAttribute('aria-expanded', String(expanded));
|
||
}
|
||
setTimeout(() => map.invalidateSize(), 260);
|
||
}
|
||
|
||
compactOverview.addEventListener('change', () => {
|
||
activeOverviewSide = null;
|
||
syncOverviewPanels();
|
||
});
|
||
syncOverviewPanels();
|
||
|
||
function getPilotPosition(x) {
|
||
if (!validCoord(x.pilotLat, x.pilotLng)) return null;
|
||
return { lat: Number(x.pilotLat), lng: Number(x.pilotLng) };
|
||
}
|
||
|
||
function shouldPlayAlarm() {
|
||
const el = document.getElementById('soundAlarmToggle');
|
||
return !el || el.checked;
|
||
}
|
||
|
||
function shouldFlashAlarm() {
|
||
const el = document.getElementById('flashAlarmToggle');
|
||
return !el || el.checked;
|
||
}
|
||
|
||
function alertSoundProfile(item) {
|
||
const cls = String(item?.registryClass || '').toLowerCase();
|
||
if (cls === 'blacklist') return 3;
|
||
if (cls === 'whitelist') return 2;
|
||
// 未登记明确使用1;重点关注/普通已登记等未单独指定类别也使用1作为安全兜底。
|
||
return 1;
|
||
}
|
||
|
||
function stopCurrentAlertSound() {
|
||
try {
|
||
if (currentAlertAudio) {
|
||
currentAlertAudio.pause();
|
||
currentAlertAudio.currentTime = 0;
|
||
}
|
||
} catch (_) {}
|
||
currentAlertAudio = null;
|
||
}
|
||
|
||
function playDroneCue(droneItem, inZone = false, force = false) {
|
||
if (!shouldPlayAlarm()) return;
|
||
const kind = inZone ? 'alarm' : 'discovery';
|
||
const profile = alertSoundProfile(droneItem);
|
||
const soundKey = `${kind}_${profile}`;
|
||
const now = Date.now();
|
||
// 同一轮刷新里可能同时命中名单与防控区;统一由这里选择最终语音,避免重复叠音。
|
||
if (!force && soundKey === lastAlarmSoundKey && now - lastAlarmSoundAt < 700) return;
|
||
lastAlarmSoundAt = now;
|
||
lastAlarmSoundKey = soundKey;
|
||
const audio = alertAudioBank[kind]?.[profile];
|
||
if (!audio) return;
|
||
try {
|
||
stopCurrentAlertSound();
|
||
currentAlertAudio = audio;
|
||
audio.currentTime = 0;
|
||
audio.play().catch(() => {
|
||
console.warn('浏览器阻止了自动播放。请先点击页面任意位置,或点击“测试报警”。');
|
||
});
|
||
} catch (err) {
|
||
console.warn('提示音播放失败:', err);
|
||
}
|
||
}
|
||
|
||
function readClearedAlarmId() {
|
||
try {
|
||
const saved = Number(localStorage.getItem(clearedAlarmKey));
|
||
if (Number.isSafeInteger(saved) && saved >= 0) return saved;
|
||
} catch (_) {}
|
||
return 0;
|
||
}
|
||
|
||
function renderAlarmEffect() {
|
||
const overlay = document.getElementById('alarmOverlay');
|
||
const tone = window.ridFlightStatus.meta(activeAlarm?.kind).tone;
|
||
const show = shouldFlashAlarm() && (tone === 'danger' || tone === 'warning');
|
||
overlay.classList.toggle('active', show);
|
||
overlay.classList.toggle('alarm', show && tone === 'danger');
|
||
overlay.classList.toggle('warning', show && tone === 'warning');
|
||
const title = overlay.querySelector('.alarmText');
|
||
const text = activeAlarm ? [activeAlarm.type, activeAlarm.uasId].filter(Boolean).join(' · ') : '';
|
||
if (title.textContent !== text) title.textContent = text;
|
||
document.getElementById('clearAlarm').disabled = !activeAlarm && alerts.length === 0;
|
||
}
|
||
|
||
function stopAlarmEffect() {
|
||
clearTimeout(alarmTimer);
|
||
activeAlarm = null;
|
||
stopCurrentAlertSound();
|
||
renderAlarmEffect();
|
||
}
|
||
|
||
function showAlarmEffect(notice, test = false) {
|
||
clearTimeout(alarmTimer);
|
||
activeAlarm = notice;
|
||
alarmTimer = setTimeout(stopAlarmEffect, alarmDurationMs);
|
||
renderAlarmEffect();
|
||
playDroneCue({registryClass:notice.kind}, test || ['geofence_enter','blacklist'].includes(notice.kind), test);
|
||
}
|
||
|
||
function syncAlarmEffects() {
|
||
if (!activeAlarm && !pendingAlarmEffects.length) return;
|
||
const online = new Set(drones.filter(drone => drone.online).map(drone => drone.uasId));
|
||
const exempt = new Set(drones.filter(drone => drone.flightClass === 'whitelist').map(drone => drone.uasId));
|
||
if (activeAlarm && exempt.has(activeAlarm.uasId)) stopAlarmEffect();
|
||
const now = Date.now();
|
||
let next;
|
||
pendingAlarmEffects = pendingAlarmEffects.filter(notice => {
|
||
if (exempt.has(notice.uasId) || notice.id <= clearedAlarmId || now - notice.timeMs >= alarmDurationMs) return false;
|
||
if (!online.has(notice.uasId)) return true;
|
||
if (!next || (alertPriority[notice.kind] || 0) > (alertPriority[next.kind] || 0)
|
||
|| notice.kind === next.kind && notice.id > next.id) next = notice;
|
||
return false;
|
||
});
|
||
if (next && (next.uasId === activeAlarm?.uasId
|
||
|| (alertPriority[next.kind] || 0) >= (alertPriority[activeAlarm?.kind] || 0))) {
|
||
showAlarmEffect(next);
|
||
}
|
||
}
|
||
|
||
async function clearCurrentAlerts() {
|
||
if (!viewReady) return;
|
||
const button = document.getElementById('clearAlarm');
|
||
button.disabled = true;
|
||
try {
|
||
const saved = await saveViewPatch({clearedAlarmId:Math.max(clearedAlarmId, latestAlarmId)});
|
||
clearedAlarmId = saved.clearedAlarmId;
|
||
try { localStorage.setItem(clearedAlarmKey, String(clearedAlarmId)); } catch (_) {}
|
||
pendingAlarmEffects = pendingAlarmEffects.filter(notice => notice.id > clearedAlarmId);
|
||
alerts = alerts.filter(notice => notice.id > clearedAlarmId);
|
||
alertCounts = { read: alerts.filter(notice => notice.handled).length, unread: alerts.filter(notice => !notice.handled).length };
|
||
++alertReadRevision;
|
||
stopAlarmEffect();
|
||
renderAlertList();
|
||
} catch (error) { viewSaveError(error); }
|
||
finally { renderAlarmEffect(); }
|
||
}
|
||
|
||
function testAlarm() {
|
||
if (!activeAlarm?.uasId) showAlarmEffect({kind:'geofence_enter', type:'测试红色报警'}, true);
|
||
}
|
||
|
||
function applyDroneRows(rows) {
|
||
const now = Date.now();
|
||
const online = new Set();
|
||
const confirmedMacs = new Set();
|
||
drones = [...rows];
|
||
for (const drone of rows) {
|
||
const id = droneKeyFromItem(drone);
|
||
online.add(id);
|
||
recentlySeenDrones.set(id, { drone, time: now });
|
||
if (drone.bssid && drone.source && id !== 'MAC-' + drone.bssid) {
|
||
confirmedMacs.add(drone.source + '/' + drone.bssid);
|
||
}
|
||
}
|
||
for (const [id, last] of recentlySeenDrones) {
|
||
if (now - last.time >= DRONE_MAP_TTL_MS) recentlySeenDrones.delete(id);
|
||
else if (!online.has(id)) {
|
||
const { bssid, source } = last.drone;
|
||
if (bssid && id === 'MAC-' + bssid && confirmedMacs.has(source + '/' + bssid)) {
|
||
recentlySeenDrones.delete(id);
|
||
delete droneLastSeenAt[id];
|
||
removeLivePilot(id);
|
||
} else {
|
||
drones.push({ ...last.drone, online: false });
|
||
}
|
||
}
|
||
}
|
||
syncAlarmEffects();
|
||
}
|
||
|
||
let pendingLiveFrame;
|
||
window.addEventListener('rid-live-frame', () => {
|
||
if (pendingLiveFrame) return;
|
||
pendingLiveFrame = requestAnimationFrame(() => {
|
||
pendingLiveFrame = undefined;
|
||
applyDroneRows(window.ridWorkbenchApi.cachedLiveRows());
|
||
updateMapDrones();
|
||
});
|
||
});
|
||
|
||
async function loadDrones() {
|
||
if (apiPollState.drones) return;
|
||
apiPollState.drones = true;
|
||
try {
|
||
const d = await apiFetchJson('/api/drones', {}, 6000, 0);
|
||
applyDroneRows(window.ridWorkbenchApi.cachedLiveRows());
|
||
lastDeviceStatus = d.status;
|
||
renderDrones(); updateMapDrones(); updateMapDevices(lastDeviceStatus);
|
||
} catch (e) {
|
||
console.warn('loadDrones temporary failure', e);
|
||
// 短时网络/后端忙碌时保留上一帧,不再把整个目标列表替换成 Failed to fetch。
|
||
const list = document.getElementById('droneList');
|
||
if (list && !drones.length) list.innerHTML = '<div class="muted">平台数据暂时未响应,正在自动重试…</div>';
|
||
} finally {
|
||
apiPollState.drones = false;
|
||
}
|
||
}
|
||
|
||
function droneKeyFromItem(x) {
|
||
if (!x) return '';
|
||
if (validCoord(x.lat) && validCoord(x.lng) && !isZeroZero(Number(x.lat), Number(x.lng))) return makeDroneKey(x, Number(x.lat), Number(x.lng));
|
||
return x.uasId || x.bssid || x.model || '';
|
||
}
|
||
|
||
function droneHeightLines(drone) {
|
||
const heights = [
|
||
['椭球高', drone.alt], ['几何高度', drone.geometricAltitude], ['气压高度', drone.pressureAltitude],
|
||
['离地高度', drone.heightAgl], ['相对高度', drone.relativeHeight]
|
||
].filter(([, value]) => Number.isFinite(value));
|
||
return heights.length
|
||
? heights.map(([label, value]) => label + ':' + Number(value.toFixed(1)) + ' m')
|
||
: ['高度:未上报'];
|
||
}
|
||
|
||
function droneDetectionDistance(drone, lat = drone.lat, lng = drone.lng) {
|
||
if (!drone.online || drone.positionUnverified || !validCoord(lat, lng)) return '—';
|
||
|
||
const receiver = window.ridWorkbenchApi.detectionReceiver(drone.source);
|
||
const position = receiver && stationPosition(receiver);
|
||
if (!position) return '设备位置不可用';
|
||
|
||
const distance = fmtDistanceMeters(haversineMeters(position.lat, position.lng, Number(lat), Number(lng)));
|
||
return receiver.name ? distance + ' · ' + receiver.name : distance;
|
||
}
|
||
|
||
function renderDrones() {
|
||
const list = document.getElementById('droneList');
|
||
const onlineDrones = drones.filter(drone => drone.online);
|
||
safeText('kpiTargets', onlineDrones.length);
|
||
const alarmingTargets=onlineDrones.filter(d=>['unregistered','unfiled','geofence_enter','blacklist'].includes(d.flightClass)).length;
|
||
safeHtml('targetSummary', `<span class="countOk">在线 ${onlineDrones.length}</span><span class="countWarning">告警 ${alarmingTargets}</span>`);
|
||
const arr = getFilteredDrones(onlineDrones);
|
||
const markup = arr.length ? arr.map(x => {
|
||
const key = droneKeyFromItem(x);
|
||
const pilot = getPilotPosition(x);
|
||
const isTracked = trackedDroneKey && trackedDroneKey === key;
|
||
const rmeta = registryMeta(x);
|
||
const positioned = validCoord(x.lat, x.lng) && !x.positionUnverified && !isZeroZero(x.lat, x.lng);
|
||
const color = window.ridFlightStatus.colors(x.flightClass).fill;
|
||
return `<article class="targetCard${isTracked ? ' active' : ''}" data-target-id="${escAttr(key)}" style="--target-accent:${color}">
|
||
<header class="targetCardHead"><strong>${esc(x.model || 'RID 目标')}</strong><span class="tag green">在线</span></header>
|
||
<div class="targetIdentity"><code title="${escAttr(x.uasId)}">${esc(x.uasId || '—')}</code><span class="tag ${rmeta.tag}">${esc(rmeta.label)}</span></div>
|
||
<div class="targetTelemetry"><span>${esc(droneHeightLines(x)[0])}</span><span>速度 ${Number.isFinite(x.speed) ? esc(x.speed) + ' m/s' : '—'}</span></div>
|
||
<p class="targetSecondary">距侦测设备 ${esc(droneDetectionDistance(x))}</p>
|
||
${x.sourceCount > 1 ? `<p class="targetSecondary">${x.sourceCount} 台设备侦测 · 定位来源 ${esc(getStationByKey(x.source)?.name || x.source)}</p>` : ''}
|
||
${positioned ? `<p class="targetSecondary">${Number(x.lat).toFixed(6)}, ${Number(x.lng).toFixed(6)}</p>` : ''}
|
||
<p class="targetSecondary">${pilot ? `飞手坐标 · ${pilot.lat.toFixed(6)}, ${pilot.lng.toFixed(6)}` : '飞手位置未上报'}</p>
|
||
<div class="targetActions">
|
||
<button class="smallBtn" data-rid-click="trackDrone" data-rid-arg0="${escAttr(key)}">${isTracked ? '跟踪中' : '跟踪'}</button>
|
||
${isTracked ? '<button class="smallBtn gray" data-rid-click="unlockDroneTracking">解锁</button>' : ''}
|
||
${positioned ? `<button class="smallBtn gray" data-rid-click="shareDroneLocation" data-rid-arg0="${escAttr(key)}" data-rid-arg1="drone">分享位置</button>` : ''}
|
||
${pilot ? `<button class="smallBtn gray" data-rid-click="shareDroneLocation" data-rid-arg0="${escAttr(key)}" data-rid-arg1="pilot">飞手位置</button>` : ''}
|
||
<button class="smallBtn gray" data-rid-click="copyDroneRid" data-rid-arg0="${escAttr(key)}">复制 RID</button>
|
||
</div>
|
||
</article>`;
|
||
}).join('') : `<div class="muted">${activeSearchKey ? '没有匹配目标' : '暂无目标'}</div>`;
|
||
if (list.dataset.renderedTargets === markup) return;
|
||
const focused = document.activeElement?.closest('#droneList button');
|
||
list.innerHTML = markup;
|
||
list.dataset.renderedTargets = markup;
|
||
if (focused) {
|
||
const card = [...list.children].find(node => node.dataset.targetId === focused.closest('.targetCard')?.dataset.targetId);
|
||
[...(card?.querySelectorAll('button') || [])].find(button => button.dataset.ridClick === focused.dataset.ridClick
|
||
&& button.dataset.ridArg1 === focused.dataset.ridArg1)?.focus({preventScroll:true});
|
||
}
|
||
}
|
||
|
||
function applySearch() {
|
||
activeSearchKey = document.getElementById('search').value.trim();
|
||
renderDrones();
|
||
}
|
||
|
||
function locateSearchResult() {
|
||
activeSearchKey = document.getElementById('search').value.trim();
|
||
const arr = getFilteredDrones().filter(x => validCoord(x.lat) && validCoord(x.lng));
|
||
renderDrones();
|
||
if (!arr.length) {
|
||
alert(activeSearchKey ? '没有找到可定位的匹配目标' : '暂无可定位目标');
|
||
return;
|
||
}
|
||
focusDrone(arr[0].uasId);
|
||
}
|
||
|
||
function clearSearch() {
|
||
document.getElementById('search').value = '';
|
||
activeSearchKey = '';
|
||
renderDrones();
|
||
}
|
||
|
||
function pointInPolygonJs(lat, lng, points) {
|
||
if (!points || points.length < 3) return false;
|
||
const x = Number(lng);
|
||
const y = Number(lat);
|
||
let inside = false;
|
||
let j = points.length - 1;
|
||
for (let i = 0; i < points.length; i++) {
|
||
const xi = Number(points[i].lng);
|
||
const yi = Number(points[i].lat);
|
||
const xj = Number(points[j].lng);
|
||
const yj = Number(points[j].lat);
|
||
if (((yi > y) !== (yj > y))) {
|
||
const crossX = (xj - xi) * (y - yi) / ((yj - yi) || 1e-12) + xi;
|
||
if (x < crossX) inside = !inside;
|
||
}
|
||
j = i;
|
||
}
|
||
return inside;
|
||
}
|
||
|
||
function pointInRectangleJs(lat, lng, points) {
|
||
if (!points || points.length < 2) return false;
|
||
const lat1 = Number(points[0].lat), lng1 = Number(points[0].lng);
|
||
const lat2 = Number(points[1].lat), lng2 = Number(points[1].lng);
|
||
return Math.min(lat1, lat2) <= lat && lat <= Math.max(lat1, lat2)
|
||
&& Math.min(lng1, lng2) <= lng && lng <= Math.max(lng1, lng2);
|
||
}
|
||
|
||
function pointInCircleJs(lat, lng, points) {
|
||
if (!points || !points.length) return false;
|
||
const center = points[0];
|
||
const radius = Number(center.radius || 0);
|
||
if (!radius) return false;
|
||
return map.distance([lat, lng], [Number(center.lat), Number(center.lng)]) <= radius;
|
||
}
|
||
|
||
function pointInZoneJs(lat, lng, zone) {
|
||
if (!zone || !zone.enabled) return false;
|
||
if (zone.type === 'circle') return pointInCircleJs(lat, lng, zone.points);
|
||
if (zone.type === 'rectangle') return pointInRectangleJs(lat, lng, zone.points);
|
||
return pointInPolygonJs(lat, lng, zone.points);
|
||
}
|
||
|
||
function getHitZone(lat, lng) {
|
||
return zones.find(z => z.enabled && pointInZoneJs(lat, lng, z));
|
||
}
|
||
|
||
function makeDroneKey(drone, lat, lng) {
|
||
return drone.uasId || drone.bssid || (drone.model + '_' + lat + '_' + lng);
|
||
}
|
||
|
||
function isZeroZero(lat, lng) {
|
||
return Math.abs(Number(lat)) < 1e-7 && Math.abs(Number(lng)) < 1e-7;
|
||
}
|
||
|
||
function liveAgHeight(drone) {
|
||
return Number.isFinite(drone.heightAgl) && drone.heightAgl >= 0 ? drone.heightAgl : null;
|
||
}
|
||
|
||
function rememberTrail(drone, key, lat, lng, height, append, confirmedJump) {
|
||
const raw = droneTrackRaw[key] ??= [];
|
||
const previousSource = trailSources.get(key);
|
||
if (!append || !drone.online) return raw;
|
||
if (previousSource && !previousSource.lost && previousSource.sampleId === drone.sampleId
|
||
&& previousSource.generation === drone.positionGeneration) return raw;
|
||
|
||
const time = drone.receivedAtMs;
|
||
const elapsed = time - previousSource?.time;
|
||
const interrupted = !previousSource || previousSource.lost || confirmedJump
|
||
|| drone.source !== previousSource.source || drone.positionGeneration !== previousSource.generation
|
||
|| elapsed < 0 || elapsed >= window.ridDroneMap.MAX_LINK_GAP_MS;
|
||
const previousPoint = raw.at(-1);
|
||
const moved = previousPoint && haversineMeters(previousPoint[0], previousPoint[1], lat, lng) >= 1;
|
||
const changedHeight = previousPoint && ((previousPoint[2] == null) !== (height == null)
|
||
|| (height != null && Math.abs(previousPoint[2] - height) >= 1));
|
||
if (moved || changedHeight || interrupted) {
|
||
raw.push([lat, lng, height, interrupted]);
|
||
if (raw.length > 500) raw.shift();
|
||
}
|
||
const heading = interrupted ? null : moved
|
||
? window.ridDroneMap.trackHeading(previousPoint[0], previousPoint[1], lat, lng) : previousSource.heading;
|
||
trailSources.set(key, {source:drone.source, generation:drone.positionGeneration, time, sampleId:drone.sampleId, heading});
|
||
return raw;
|
||
}
|
||
|
||
function trackSegments(raw) {
|
||
const segments = [];
|
||
for (const [lat, lng, , starts] of raw) {
|
||
if (starts || !segments.length) segments.push([]);
|
||
segments.at(-1).push(toMapLatLng(lat, lng));
|
||
}
|
||
return segments;
|
||
}
|
||
|
||
function drawLeafletTrail(key, raw) {
|
||
if (leafletZooming) return;
|
||
let line = tracks[key];
|
||
if (!line) {
|
||
line = L.polyline([], {color:'#39e88f', weight:3}).addTo(flightTrails);
|
||
tracks[key] = line;
|
||
}
|
||
const tail = raw.at(-1);
|
||
if (line.trailTail === tail && line.trailBasemap === currentBaseLayerKey) return;
|
||
line.setLatLngs(trackSegments(raw));
|
||
line.trailTail = tail;
|
||
line.trailBasemap = currentBaseLayerKey;
|
||
}
|
||
|
||
function sceneBasemap() {
|
||
const style = baseLayers[currentBaseLayerKey];
|
||
return {tiles:style.base._url, labels:mapLabelsVisible ? style.label?._url : undefined};
|
||
}
|
||
|
||
function sync3DCamera() {
|
||
if (!map3DActive || applyingCamera) return;
|
||
const center = map.getCenter();
|
||
liveMap3D.setView([center.lng, center.lat], map.getZoom());
|
||
}
|
||
|
||
function scheduleMapResize() {
|
||
cancelAnimationFrame(resizeFrame);
|
||
resizeFrame = requestAnimationFrame(() => {
|
||
map.invalidateSize({animate:false, debounceMoveend:true});
|
||
liveMap3D?.resize();
|
||
});
|
||
}
|
||
|
||
function shapeFeature(layer) {
|
||
if (!(layer instanceof L.Circle)) return layer.toGeoJSON(false).geometry;
|
||
const center = layer.getLatLng();
|
||
const radians = Math.PI / 180;
|
||
const latitude = center.lat * radians;
|
||
const radius = layer.getRadius() / 6371000;
|
||
const ring = [];
|
||
for (let index = 0; index < 48; index += 1) {
|
||
const angle = index / 48 * Math.PI * 2;
|
||
const lat = Math.asin(Math.sin(latitude) * Math.cos(radius)
|
||
+ Math.cos(latitude) * Math.sin(radius) * Math.cos(angle));
|
||
const lon = Math.atan2(Math.sin(angle) * Math.sin(radius) * Math.cos(latitude),
|
||
Math.cos(radius) - Math.sin(latitude) * Math.sin(lat));
|
||
ring.push([center.lng + lon / radians, lat / radians]);
|
||
}
|
||
ring.push(ring[0]);
|
||
return {type:'Polygon', coordinates:[ring]};
|
||
}
|
||
|
||
function refreshSceneFences() {
|
||
if (!map3DActive) return;
|
||
liveMap3D.setFences(zones.filter(zone => zoneLayers[zone.id]).map(zone => ({
|
||
type:'Feature', geometry:shapeFeature(zoneLayers[zone.id]), properties:zonePopupInfo(zone)
|
||
})));
|
||
}
|
||
|
||
function queue3DScene() {
|
||
if (!map3DActive || sceneFrame != null) return;
|
||
sceneFrame = requestAnimationFrame(() => {
|
||
sceneFrame = undefined;
|
||
if (!map3DActive) return;
|
||
const entries = [];
|
||
const addMarker = (id, marker, details) => {
|
||
const position = marker.getLatLng();
|
||
entries.push({
|
||
id, position:[position.lng, position.lat], icon:marker.getElement()?.firstElementChild,
|
||
popup:marker.getPopup()?.getContent() || '', ...details
|
||
});
|
||
};
|
||
for (const drone of drones) {
|
||
const key = droneKeyFromItem(drone);
|
||
if (markers[key] && validCoord(drone.lat, drone.lng) && !drone.positionUnverified) {
|
||
const height = liveAgHeight(drone);
|
||
const pilot = pilotMarkers.get(key)?.marker.getLatLng();
|
||
addMarker('aircraft:' + key, markers[key], {label:'飞机 · ' + drone.uasId,
|
||
heading:markers[key].flightHeading, height,
|
||
heightLabel:height == null ? droneHeightLines(drone)[0] : '离地 ' + Number(height.toFixed(1)) + ' m',
|
||
trail:flightTrailToggle.checked ? droneTrackRaw[key] : undefined,
|
||
pilot:pilot ? [pilot.lng, pilot.lat] : null});
|
||
}
|
||
}
|
||
for (const [key, {marker}] of pilotMarkers) {
|
||
addMarker('pilot:' + key, marker, {label:'飞手位置 · ' + key});
|
||
}
|
||
for (const group of [deviceMarkers, stationMarkers]) {
|
||
for (const [id, marker] of Object.entries(group)) {
|
||
addMarker('侦测设备:' + id, marker, {label:'侦测设备'});
|
||
}
|
||
}
|
||
liveMap3D.updateEntries(entries);
|
||
});
|
||
}
|
||
|
||
function paintMapMode(active) {
|
||
map3DActive = active;
|
||
const container = document.getElementById('liveMap3D');
|
||
container.closest('.mapWrap').dataset.mapMode = active ? '3d' : '2d';
|
||
container.hidden = !active;
|
||
mapViewToggle.setAttribute('aria-pressed', String(active));
|
||
liveMap3D?.setActive(active);
|
||
scheduleMapResize();
|
||
}
|
||
|
||
async function setMap3D(active) {
|
||
if (active && drawing) return;
|
||
wantMap3D = active;
|
||
const version = ++mapModeVersion;
|
||
if (!active) {
|
||
paintMapMode(false);
|
||
saveManualMapView();
|
||
return;
|
||
}
|
||
const container = document.getElementById('liveMap3D');
|
||
try {
|
||
if (!liveMap3D) {
|
||
const {openLiveMap} = await import('/workbench/live-map-3d.js');
|
||
if (version !== mapModeVersion) return;
|
||
container.hidden = false;
|
||
const center = map.getCenter();
|
||
liveMap3D = openLiveMap(container, {
|
||
createZonePopupContent,
|
||
pitch:savedCamera?.pitch, bearing:savedCamera?.bearing,
|
||
center:[center.lng, center.lat], zoom:map.getZoom(), basemap:sceneBasemap(),
|
||
trackCoords(lat, lng) {
|
||
const position = toMapLatLng(lat, lng);
|
||
return [position[1], position[0]];
|
||
},
|
||
onCamera(position, zoom) {
|
||
if (!map3DActive) return;
|
||
applyingCamera = true;
|
||
try { map.setView([position.lat, position.lng], zoom, {animate:false}); }
|
||
finally { applyingCamera = false; }
|
||
saveManualMapView();
|
||
},
|
||
onError() {
|
||
setMap3D(false);
|
||
liveMap3D?.destroy();
|
||
liveMap3D = undefined;
|
||
reportMapFailure();
|
||
}
|
||
});
|
||
}
|
||
if (version !== mapModeVersion) return;
|
||
paintMapMode(true);
|
||
liveMap3D.setBasemap(sceneBasemap());
|
||
sync3DCamera();
|
||
refreshSceneFences();
|
||
queue3DScene();
|
||
saveManualMapView();
|
||
} catch (error) {
|
||
if (version !== mapModeVersion) return;
|
||
console.warn('3D 地图初始化失败', error);
|
||
setMap3D(false);
|
||
reportMapFailure();
|
||
}
|
||
}
|
||
|
||
function reportMapFailure() {
|
||
const message = document.getElementById('rid-workbench-status');
|
||
message.hidden = false;
|
||
message.textContent = '当前浏览器无法打开 3D 地图,已切换到平面视角。';
|
||
clearTimeout(message.hideTimer);
|
||
message.hideTimer = setTimeout(() => {message.hidden = true;}, 5000);
|
||
}
|
||
|
||
function openLiveDroneDetails(key) {
|
||
if (map3DActive) liveMap3D.showTarget('aircraft:' + key);
|
||
else markers[key]?.openPopup();
|
||
}
|
||
|
||
function removeLivePilot(key) {
|
||
const pilot = pilotMarkers.get(key);
|
||
if (!pilot) return;
|
||
map.removeLayer(pilot.marker);
|
||
if (pilot.link) map.removeLayer(pilot.link);
|
||
pilotMarkers.delete(key);
|
||
}
|
||
|
||
function updateLivePilot(drone, key, position, aircraft) {
|
||
if (!position || !pilotMarkerToggle.checked) {
|
||
removeLivePilot(key);
|
||
return;
|
||
}
|
||
|
||
const mapPosition = toMapLatLng(position.lat, position.lng);
|
||
const distance = aircraft ? '<br>机控距离:' + fmtDistanceMeters(aircraft.distance) : '';
|
||
const popup = `<b>飞手位置</b><br>关联目标:${esc(drone.uasId)}<br>机型:${esc(drone.model)}<br>坐标:${position.lat.toFixed(6)}, ${position.lng.toFixed(6)}${distance}`;
|
||
let pilot = pilotMarkers.get(key);
|
||
if (!pilot) {
|
||
if (!drone.online) return;
|
||
const title = '飞手位置 · ' + drone.uasId;
|
||
const marker = L.marker(mapPosition, {icon:makePilotIcon(drone.model), title}).addTo(map).bindPopup(popup);
|
||
pilot = {marker, model:drone.model, slot:0, lastSeenAt:0, link:null};
|
||
pilotMarkers.set(key, pilot);
|
||
} else {
|
||
if (!pilot.marker.getLatLng().equals(mapPosition, 0)) pilot.marker.setLatLng(mapPosition);
|
||
if (pilot.marker.getPopup().getContent() !== popup) pilot.marker.setPopupContent(popup);
|
||
if (pilot.model !== drone.model) {
|
||
pilot.model = drone.model;
|
||
pilot.marker.setIcon(makePilotIcon(pilot.model, pilot.slot));
|
||
}
|
||
}
|
||
if (drone.online) pilot.lastSeenAt = Date.now();
|
||
|
||
if (!aircraft) {
|
||
if (pilot.link) map.removeLayer(pilot.link);
|
||
pilot.link = null;
|
||
return;
|
||
}
|
||
const line = [aircraft.position, mapPosition];
|
||
const tooltip = '机控距离:' + fmtDistanceMeters(aircraft.distance);
|
||
if (!pilot.link) {
|
||
pilot.link = L.polyline(line, {color:'#00d5ff', weight:2.5, opacity:.82, dashArray:'6,8'})
|
||
.addTo(map).bindTooltip(tooltip, {sticky:true, direction:'center'});
|
||
} else {
|
||
const [from, to] = pilot.link.getLatLngs();
|
||
if (!from.equals(line[0], 0) || !to.equals(line[1], 0)) pilot.link.setLatLngs(line);
|
||
if (pilot.link.getTooltip().getContent() !== tooltip) pilot.link.setTooltipContent(tooltip);
|
||
}
|
||
}
|
||
|
||
function separateSharedPilotLabels() {
|
||
const byPosition = new Map();
|
||
for (const pilot of pilotMarkers.values()) {
|
||
const {lat, lng} = pilot.marker.getLatLng();
|
||
const key = lat.toFixed(6) + ',' + lng.toFixed(6);
|
||
if (!byPosition.has(key)) byPosition.set(key, []);
|
||
byPosition.get(key).push(pilot);
|
||
}
|
||
for (const group of byPosition.values()) {
|
||
group.forEach((pilot, slot) => {
|
||
if (pilot.slot === slot) return;
|
||
pilot.slot = slot;
|
||
pilot.marker.setIcon(makePilotIcon(pilot.model, slot));
|
||
});
|
||
}
|
||
}
|
||
|
||
function updateMapDrones(appendTrack = true) {
|
||
const seenKeys = new Set();
|
||
drones.forEach(x => {
|
||
const key = droneKeyFromItem(x);
|
||
const pilot = getPilotPosition(x);
|
||
let aircraft = null;
|
||
const rmeta = registryMeta(x);
|
||
const posValid = validCoord(x.lat) && validCoord(x.lng)
|
||
&& !x.positionUnverified && !isZeroZero(Number(x.lat), Number(x.lng));
|
||
const lat = posValid ? Number(x.lat) : null;
|
||
const lng = posValid ? Number(x.lng) : null;
|
||
const physicalHitZone = (x.online && posValid) ? getHitZone(lat, lng) : null;
|
||
|
||
if (x.online && !posValid && markers[key]) {
|
||
map.removeLayer(markers[key]);
|
||
delete markers[key];
|
||
}
|
||
|
||
if (posValid) {
|
||
const stablePos = stableDisplayPosition(key, lat, lng, x.receivedAtMs, x.sampleId);
|
||
const displayLat = Number(stablePos.lat), displayLng = Number(stablePos.lng);
|
||
const mapPos = toMapLatLng(displayLat, displayLng);
|
||
if (x.online) {
|
||
seenKeys.add(key);
|
||
droneLastSeenAt[key] = Date.now();
|
||
}
|
||
const pilotDistance = pilot ? haversineMeters(displayLat, displayLng, pilot.lat, pilot.lng) : null;
|
||
const pilotLine = pilot ? `<br>飞手坐标:${pilot.lat.toFixed(6)}, ${pilot.lng.toFixed(6)}<br>机控距离:${fmtDistanceMeters(pilotDistance)}` : '<br>飞手位置未上报';
|
||
aircraft = {position:mapPos, distance:pilotDistance};
|
||
const zoneText = physicalHitZone
|
||
? `防控区:${esc(physicalHitZone.name || '防控区')}${rmeta.cls === 'whitelist' ? '(白名单免报警)' : ''}`
|
||
: '非防控区';
|
||
const raw = rememberTrail(x, key, displayLat, displayLng, liveAgHeight(x),
|
||
appendTrack && stablePos.accepted, stablePos.confirmedJump);
|
||
const measuredHeading = headingNumber(x.heading);
|
||
const heading = measuredHeading ?? trailSources.get(key)?.heading;
|
||
const headingText = Number.isFinite(heading) ? `<br>航向:${esc(Number(heading.toFixed(1)))}°${measuredHeading == null ? '(轨迹推算)' : ''}` : '';
|
||
const protoText = x.protocolType ? `<br>协议:${esc(x.protocolType)} ${x.ridVersion ? '/' + esc(x.ridVersion) : ''}` : '';
|
||
const registryText = `飞行状态:${esc(rmeta.label)}${x.flightReason ? ' · '+esc(x.flightReason) : ''}`;
|
||
const pop = `<b>${esc(x.model)}</b><br>状态:${x.online ? '在线' : '离线'} / ${zoneText}<br>${registryText}<br>UAS ID:${esc(x.uasId)}<br>无人机坐标:${displayLat}, ${displayLng}${pilotLine}<br>距侦测设备:${esc(droneDetectionDistance(x, displayLat, displayLng))}<br>${droneHeightLines(x).map(esc).join('<br>')}<br>速度:${esc(x.speed)}${headingText}${protoText}<br>信号:${esc(x.rssi)} dBm`;
|
||
const signature = [heading, x.online, x.flightClass, x.model].join(':');
|
||
const iconItem = {...x, heading};
|
||
drawLeafletTrail(key, raw);
|
||
|
||
if (!markers[key]) {
|
||
markers[key] = L.marker(mapPos, {icon:makeDroneIcon(iconItem), title:'飞机 · ' + x.uasId}).addTo(map).bindPopup(pop);
|
||
markers[key].iconSignature = signature;
|
||
if (mapViewMode === 'auto' && !overviewLocked && !trackedDroneKey && Date.now() > suppressAutoFocusUntil) {
|
||
map.invalidateSize();
|
||
mapSetViewWgs84(displayLat, displayLng, Math.max(map.getZoom(), 17));
|
||
setTimeout(() => openLiveDroneDetails(key), 120);
|
||
}
|
||
} else if (!leafletZooming) {
|
||
const marker = markers[key];
|
||
if (!marker.getLatLng().equals(mapPos, 0)) marker.setLatLng(mapPos);
|
||
if (marker.iconSignature !== signature) {
|
||
marker.setIcon(makeDroneIcon(iconItem));
|
||
marker.iconSignature = signature;
|
||
}
|
||
if (marker.getPopup()?.getContent() !== pop) marker.setPopupContent(pop);
|
||
}
|
||
markers[key].flightHeading = heading;
|
||
}
|
||
updateLivePilot(x, key, pilot, aircraft);
|
||
});
|
||
|
||
const nowFocus = Date.now();
|
||
if (mapViewMode === 'tracking' && trackedDroneKey && markers[trackedDroneKey]) {
|
||
const ll = markers[trackedDroneKey].getLatLng();
|
||
map.invalidateSize();
|
||
map.setView(ll, Math.max(map.getZoom(), 17), { animate: false });
|
||
openLiveDroneDetails(trackedDroneKey);
|
||
} else if (mapViewMode === 'auto' && appendTrack && !overviewLocked && nowFocus > suppressAutoFocusUntil) {
|
||
const focusCandidate = drones.find(x => x.online && validCoord(x.lat) && validCoord(x.lng) && !isZeroZero(Number(x.lat), Number(x.lng)))
|
||
|| drones.find(x => validCoord(x.lat) && validCoord(x.lng) && !isZeroZero(Number(x.lat), Number(x.lng)));
|
||
if (focusCandidate) {
|
||
const flat = Number(focusCandidate.lat), flng = Number(focusCandidate.lng);
|
||
const fkey = makeDroneKey(focusCandidate, flat, flng);
|
||
const now = Date.now();
|
||
if (lastAutoFocusKey !== fkey || now - lastAutoFocusAt > 20000) {
|
||
lastAutoFocusKey = fkey;
|
||
lastAutoFocusAt = now;
|
||
map.invalidateSize();
|
||
mapSetViewWgs84(flat, flng, Math.max(map.getZoom(), 17));
|
||
if (markers[fkey]) setTimeout(() => openLiveDroneDetails(fkey), 150);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 清理不在当前接口结果中的旧无人机点;但接口短暂空列表时不立即清空,防止目标“闪现后消失”。
|
||
const allowClearMissing = true;
|
||
const nowCleanup = Date.now();
|
||
if (allowClearMissing) {
|
||
Object.keys(markers).forEach(key => {
|
||
if (!droneLastSeenAt[key] || nowCleanup - droneLastSeenAt[key] > DRONE_MAP_TTL_MS) { map.removeLayer(markers[key]); delete markers[key]; if (trackedDroneKey === key) trackedDroneKey = null; }
|
||
});
|
||
Object.keys(tracks).forEach(key => {
|
||
if (!droneLastSeenAt[key] || nowCleanup - droneLastSeenAt[key] > DRONE_MAP_TTL_MS) {
|
||
flightTrails.removeLayer(tracks[key]); delete tracks[key]; delete droneTrackRaw[key];
|
||
trailSources.delete(key);
|
||
}
|
||
});
|
||
|
||
for (const [key, pilot] of pilotMarkers) {
|
||
if (nowCleanup - pilot.lastSeenAt > DRONE_MAP_TTL_MS) removeLivePilot(key);
|
||
else if (!markers[key] && pilot.link) {
|
||
map.removeLayer(pilot.link);
|
||
pilot.link = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
for (const [key, source] of trailSources) {
|
||
if (!seenKeys.has(key)) {
|
||
source.lost = true;
|
||
source.heading = null;
|
||
delete droneDisplayPositionState[key];
|
||
}
|
||
}
|
||
separateSharedPilotLabels();
|
||
queue3DScene();
|
||
}
|
||
function updateMapDevices(status) {
|
||
const list = (status && status.tcpDevices) || [];
|
||
const seen = new Set();
|
||
list.forEach(dev => {
|
||
const lat = dev.deviceLat || dev.lat || dev.gnssLat;
|
||
const lng = dev.deviceLng || dev.lng || dev.gnssLng;
|
||
const key = dev.id || (dev.host + ':' + dev.port);
|
||
if (!validCoord(lat, lng) || !key) return;
|
||
seen.add(key);
|
||
const pop = `<b>📡 侦测设备</b><br>名称:${esc(dev.deviceName || key)}<br>状态:${dev.connected ? '在线' : '离线'}<br>IP:${esc(dev.deviceIp || dev.host || '')}<br>固件:${esc(dev.firmware || '-')}<br>坐标:${Number(lat).toFixed(6)}, ${Number(lng).toFixed(6)}`;
|
||
const dIcon = dev.connected ? deviceIcon : deviceOfflineIcon;
|
||
const mapPos = toMapLatLng(Number(lat), Number(lng));
|
||
if (!deviceMarkers[key]) deviceMarkers[key] = L.marker(mapPos, { icon: dIcon }).addTo(map).bindPopup(pop);
|
||
else deviceMarkers[key].setLatLng(mapPos).setIcon(dIcon).bindPopup(pop);
|
||
});
|
||
// 侦测器位置来自台账/心跳,离线后不从地图移除;删除台账后由 /api/local_stations 清理。
|
||
}
|
||
|
||
|
||
async function loadLocalStations() {
|
||
// 本地版监测站单独刷新,绝不影响无人机 /api/drones 实时目标。
|
||
if (apiPollState.stations) return;
|
||
apiPollState.stations = true;
|
||
try {
|
||
const data = await apiFetchJson('/api/local_stations', {}, 4500, 1);
|
||
localStations = data.stations || [];
|
||
updateMapStations(localStations);
|
||
renderStationList(localStations);
|
||
queue3DScene();
|
||
} catch (e) {
|
||
console.warn('loadLocalStations temporary failure', e);
|
||
const list = document.getElementById('stationList');
|
||
if (list && !localStations.length) list.innerHTML = '<div class="muted">设备状态暂时未响应,正在自动重试…</div>';
|
||
} finally {
|
||
apiPollState.stations = false;
|
||
}
|
||
}
|
||
|
||
function stationKeyFromItem(dev) {
|
||
if (!dev) return '';
|
||
return String(dev.id || dev.sn || dev.deviceCode || dev.identifier || dev.deviceIp || dev.name || '');
|
||
}
|
||
|
||
function getStationByKey(key) {
|
||
key = String(key || '');
|
||
return (localStations || []).find(dev => stationKeyFromItem(dev) === key);
|
||
}
|
||
|
||
const stationBadges = {
|
||
online: { label: '在线', color: 'green' },
|
||
waiting: { label: '等待数据', color: 'yellow' },
|
||
offline: { label: '离线', color: 'gray' }
|
||
};
|
||
const stationTransportNames = { serial: 'USB 串口', udp: 'UDP 监听', 'tcp-listen': 'TCP 监听' };
|
||
|
||
function stationPosition(dev) {
|
||
const gnss = dev.gnss;
|
||
if (!gnss?.fixAvailable || !validCoord(gnss.latitude, gnss.longitude)) return null;
|
||
return { lat: gnss.latitude, lng: gnss.longitude };
|
||
}
|
||
|
||
function renderStationList(stations) {
|
||
const list = document.getElementById('stationList');
|
||
if (!list) return;
|
||
const onlineCount = stations.filter(station => station.linkState === 'online').length;
|
||
const waitingCount = stations.filter(station => station.linkState === 'waiting').length;
|
||
safeText('kpiStations', stations.length);
|
||
safeHtml('stationSummary', `<span class="countOk">在线 ${onlineCount}</span><span class="countMuted">离线 ${stations.length-onlineCount-waitingCount}</span>${waitingCount ? `<span class="countWarning">等待 ${waitingCount}</span>` : ''}`);
|
||
if (!stations?.length) {
|
||
list.innerHTML = '<div class="muted">暂无侦测设备</div>';
|
||
delete list.dataset.renderedStations;
|
||
return;
|
||
}
|
||
|
||
const expanded = new Set([...list.querySelectorAll('details[open]')].map(el => el.dataset.stationId));
|
||
const stationOrder = {online:0, waiting:1, offline:2};
|
||
const markup = [...stations].sort((a,b) => (stationOrder[a.linkState] ?? 3) - (stationOrder[b.linkState] ?? 3)).map(dev => {
|
||
const key = stationKeyFromItem(dev);
|
||
const gnss = dev.gnss;
|
||
const position = stationPosition(dev);
|
||
const badge = stationBadges[dev.linkState] || stationBadges.offline;
|
||
const title = dev.name || dev.sn || dev.deviceIp || '侦测设备';
|
||
const transport = stationTransportNames[dev.transport] || '未知接入方式';
|
||
const address = [dev.deviceIp, dev.endpoint].filter(Boolean).join(' → ') || dev.sn;
|
||
const antenna = ({ ok: '正常', open: '开路', short: '短路' })[gnss?.antenna] || '—';
|
||
const satellites = gnss?.satellitesBySystem?.map(({system, count}) => system + ' ' + count).join(' / ');
|
||
const dimension = gnss?.fixDimension === 3 ? ' · 3D' : gnss?.fixDimension === 2 ? ' · 2D' : '';
|
||
const fix = gnss?.fixAvailable === true ? 'GNSS 已定位' + dimension
|
||
: gnss?.fixAvailable === false ? 'GNSS 未定位' : '暂无定位数据';
|
||
const metrics = gnss ? `<dl class="stationMetrics">
|
||
<div><dt>可见 / 解算</dt><dd title="${escAttr(satellites)}">${esc(gnss.satellitesVisible ?? '—')} / ${esc(gnss.satellitesUsed ?? '—')}</dd></div>
|
||
<div><dt>HDOP</dt><dd>${esc(gnss.hdop ?? '—')}</dd></div>
|
||
<div><dt>天线</dt><dd>${antenna}</dd></div>
|
||
</dl>` : '';
|
||
const utc = gnss?.utcTime ? ['UTC', gnss.utcDate, gnss.utcTime].filter(Boolean).join(' ') : null;
|
||
const extra = [
|
||
gnss?.altitudeMslM != null ? '海拔 ' + gnss.altitudeMslM + ' m' : null,
|
||
gnss?.speedKmh != null ? '地速 ' + gnss.speedKmh.toFixed(1) + ' km/h' : null,
|
||
gnss?.courseDeg != null ? '航向 ' + gnss.courseDeg.toFixed(1) + '°' : null,
|
||
gnss?.pdop != null ? 'PDOP ' + gnss.pdop : null,
|
||
gnss?.vdop != null ? 'VDOP ' + gnss.vdop : null,
|
||
utc
|
||
].filter(Boolean).join(' · ');
|
||
const note = [dev.status, gnss && fix].filter(Boolean).join(' · ');
|
||
return `<details class="stationCard${dev.linkState === 'offline' ? ' offline' : ''}" data-station-id="${escAttr(key)}">
|
||
<summary class="stationCardHead">
|
||
<strong class="stationName">${esc(title)}</strong>
|
||
<span class="stationTransport">${transport}</span>
|
||
<span class="tag ${badge.color}">${badge.label}</span>
|
||
</summary>
|
||
<div class="stationCardBody">
|
||
${address ? `<div class="stationAddress" title="${escAttr(address)}">${esc(address)}</div>` : ''}
|
||
${note ? `<p class="stationFix${position ? ' fixed' : ''}">${esc(note)}</p>` : ''}
|
||
${metrics}
|
||
${position ? `<div class="stationPosition">
|
||
<span>${position.lat.toFixed(6)}, ${position.lng.toFixed(6)}</span>
|
||
<button type="button" class="smallBtn gray" data-rid-click="focusStationByKey" data-rid-arg0="${escAttr(key)}">定位</button>
|
||
<button type="button" class="smallBtn gray" data-rid-click="shareStationLocation" data-rid-arg0="${escAttr(key)}">复制位置</button>
|
||
</div>` : ''}
|
||
${satellites ? `<p class="stationExtra">${esc(satellites)}</p>` : ''}
|
||
${extra ? `<p class="stationExtra">${esc(extra)}</p>` : ''}
|
||
</div>
|
||
</details>`;
|
||
}).join('');
|
||
|
||
if (list.dataset.renderedStations === markup) return;
|
||
const focused = document.activeElement?.closest('#stationList summary, #stationList button[data-rid-click]');
|
||
const stationId = focused?.closest('.stationCard')?.dataset.stationId;
|
||
const action = focused?.dataset.ridClick;
|
||
list.innerHTML = markup;
|
||
list.dataset.renderedStations = markup;
|
||
for (const card of list.children) {
|
||
if (expanded.has(card.dataset.stationId)) card.open = true;
|
||
if (stationId && card.dataset.stationId === stationId) {
|
||
const selector = action ? `[data-rid-click="${CSS.escape(action)}"]` : 'summary';
|
||
card.querySelector(selector)?.focus({ preventScroll: true });
|
||
}
|
||
}
|
||
}
|
||
|
||
function focusStationByKey(key) {
|
||
const dev = getStationByKey(key);
|
||
if (!dev) { alert('未找到该侦测设备'); return; }
|
||
const position = stationPosition(dev);
|
||
if (!position) { alert('该设备暂无有效位置'); return; }
|
||
const { lat, lng } = position;
|
||
// 点击侦测器是明确的用户定位动作:跳过去后保持,不允许新目标/报警再抢视角。
|
||
setMapViewMode('station');
|
||
map.invalidateSize();
|
||
mapSetViewWgs84(lat, lng, Math.max(map.getZoom(), 17));
|
||
const markerKey = 'station_' + (dev.id || dev.sn || dev.deviceCode || (lat + '_' + lng));
|
||
setTimeout(() => {
|
||
if (map3DActive) liveMap3D.showTarget('侦测设备:' + markerKey);
|
||
else stationMarkers[markerKey]?.openPopup();
|
||
}, 120);
|
||
}
|
||
|
||
function shareStationLocation(key) {
|
||
const dev = getStationByKey(key);
|
||
if (!dev) { alert('未找到该侦测设备'); return; }
|
||
const position = stationPosition(dev);
|
||
if (!position) { alert('该设备暂无有效位置'); return; }
|
||
const { lat, lng } = position;
|
||
const name = encodeURIComponent(`侦测设备 ${(dev.name || dev.deviceIp || dev.sn || '').trim()}`.trim());
|
||
|
||
navigator.clipboard.writeText(`${name} ${lat}, ${lng}`).then(() => alert('已复制位置')).catch(() => alert('无法复制位置'));
|
||
}
|
||
|
||
function updateMapStations(stations) {
|
||
const seen = new Set();
|
||
const stacks = new Map();
|
||
const located = (stations || []).map(dev => ({ dev, position: stationPosition(dev) }))
|
||
.filter(station => station.position);
|
||
for (const station of located) {
|
||
const position = station.position;
|
||
const stack = `${position.lat.toFixed(5)},${position.lng.toFixed(5)}`;
|
||
if (!stacks.has(stack)) stacks.set(stack, []);
|
||
station.stack = stacks.get(stack);
|
||
station.stack.push(station);
|
||
}
|
||
located.forEach(station => {
|
||
const { dev, position, stack } = station;
|
||
const { lat, lng } = position;
|
||
const key = 'station_' + (dev.id || dev.sn || dev.deviceCode || (lat + '_' + lng));
|
||
seen.add(key);
|
||
const status = dev.status || '状态未知';
|
||
const name = dev.name || '侦测设备';
|
||
const pop = `<b>${esc(name)}</b><br>状态:${esc(status)}<br>类型:${esc(dev.deviceType || '本地')}<br>SN:${esc(dev.sn || dev.deviceCode || '-')}<br>IP:${esc(dev.deviceIp || '-')}<br>卫星:${esc(dev.gnss.satellitesUsed ?? '—')} HDOP:${esc(dev.gnss.hdop ?? '—')}<br>坐标:${lat.toFixed(6)}, ${lng.toFixed(6)}`;
|
||
const slot = stack.indexOf(station);
|
||
const columns = Math.min(stack.length, 4);
|
||
const x = (slot % columns - (columns - 1) / 2) * 36;
|
||
const y = -Math.floor(slot / columns) * 36;
|
||
const state = stationBadges[dev.linkState] ? dev.linkState : 'offline';
|
||
const html = `<div class="rid-station-marker ${state}" style="translate:${x}px ${y}px"><span aria-hidden="true">📡</span></div>`;
|
||
const mapPos = toMapLatLng(lat, lng);
|
||
if (!stationMarkers[key]) {
|
||
stationMarkers[key] = L.marker(mapPos, { icon: L.divIcon({ className:'', html, iconSize:[32, 32], iconAnchor:[16, 16] }) }).addTo(map).bindPopup(pop);
|
||
} else {
|
||
const marker = stationMarkers[key];
|
||
marker.setLatLng(mapPos).setPopupContent(pop);
|
||
if (marker.options.icon.options.html !== html) {
|
||
marker.setIcon(L.divIcon({ className:'', html, iconSize:[32, 32], iconAnchor:[16, 16] }));
|
||
}
|
||
}
|
||
stationMarkers[key].getElement()?.setAttribute('aria-label', name);
|
||
});
|
||
Object.keys(stationMarkers).forEach(key => {
|
||
if (!seen.has(key)) {
|
||
map.removeLayer(stationMarkers[key]);
|
||
delete stationMarkers[key];
|
||
}
|
||
});
|
||
}
|
||
|
||
function getDroneByKey(key) {
|
||
return (drones || []).find(x => droneKeyFromItem(x) === key || x.uasId === key || x.bssid === key);
|
||
}
|
||
function focusDroneByKey(key, lock=false) {
|
||
const d = getDroneByKey(key);
|
||
const mapKey = d ? droneKeyFromItem(d) : key;
|
||
const m = markers[mapKey] || markers[key];
|
||
if (m) {
|
||
map.invalidateSize();
|
||
if (lock) setMapViewMode('tracking', mapKey);
|
||
else setMapViewMode('station');
|
||
map.setView(m.getLatLng(), 18);
|
||
openLiveDroneDetails(mapKey);
|
||
}
|
||
}
|
||
function focusDrone(id) { focusDroneByKey(id); }
|
||
function trackDrone(key) { focusDroneByKey(key, true); }
|
||
function unlockDroneTracking() {
|
||
setMapViewMode('manual');
|
||
saveManualMapView();
|
||
}
|
||
function copyText(txt, okText) {
|
||
if (!txt) { alert('暂无可复制内容'); return; }
|
||
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(txt).then(()=>alert(okText || '已复制')).catch(()=>prompt('请手动复制', txt));
|
||
else prompt('请手动复制', txt);
|
||
}
|
||
function copyDroneRid(key) {
|
||
const d = getDroneByKey(key);
|
||
copyText((d && (d.uasId || d.bssid)) || key, 'RID编码已复制');
|
||
}
|
||
function shareDroneLocation(key, type = 'drone') {
|
||
const d = getDroneByKey(key);
|
||
if (!d) { alert('未找到该目标'); return; }
|
||
let lat = null;
|
||
let lng = null;
|
||
let label = '';
|
||
if (type === 'pilot') {
|
||
const pilot = getPilotPosition(d);
|
||
if (!pilot) { alert('该目标暂无有效飞手位置'); return; }
|
||
lat = pilot.lat;
|
||
lng = pilot.lng;
|
||
label = '飞手位置';
|
||
} else {
|
||
if (!validCoord(d.lat) || !validCoord(d.lng)) { alert('该目标暂无有效无人机位置'); return; }
|
||
lat = Number(d.lat);
|
||
lng = Number(d.lng);
|
||
label = '无人机位置';
|
||
}
|
||
const name = encodeURIComponent(`${label} ${(d.model || 'RID目标')} ${(d.uasId || '')}`.trim());
|
||
|
||
navigator.clipboard.writeText(`${name} ${lat}, ${lng}`).then(() => alert('已复制位置')).catch(() => alert('无法复制位置'));
|
||
}
|
||
function fitAll() {
|
||
if (activeModuleName) closeModule(false);
|
||
// 总览一次性适配当前所有地图对象。
|
||
setMapViewMode('overview');
|
||
const bounds = L.latLngBounds([]);
|
||
Object.values(markers).forEach(m => { if (m && map.hasLayer(m)) bounds.extend(m.getLatLng()); });
|
||
for (const {marker} of pilotMarkers.values()) bounds.extend(marker.getLatLng());
|
||
Object.values(deviceMarkers).forEach(m => { if (m && map.hasLayer(m)) bounds.extend(m.getLatLng()); });
|
||
Object.values(stationMarkers).forEach(m => { if (m && map.hasLayer(m)) bounds.extend(m.getLatLng()); });
|
||
Object.values(zoneLayers).forEach(z => {
|
||
try {
|
||
if (z && z.getBounds) {
|
||
const zb = z.getBounds();
|
||
if (zb && zb.isValid()) bounds.extend(zb);
|
||
}
|
||
} catch (_) {}
|
||
});
|
||
if (bounds.isValid()) map.fitBounds(bounds.pad(.12), { animate: false, maxZoom: 17 });
|
||
renderDrones();
|
||
}
|
||
|
||
// 只有用户本人在地图上按下/触摸/滚轮缩放时才算“人工接管”。
|
||
// 后台 setView/fitBounds 不会触发这些 DOM 输入事件,因此不会误判。
|
||
const mapContainer = map.getContainer();
|
||
mapContainer.addEventListener('mousedown', takeManualMapControl, { passive: true });
|
||
mapContainer.addEventListener('touchstart', takeManualMapControl, { passive: true });
|
||
mapContainer.addEventListener('wheel', takeManualMapControl, { passive: true });
|
||
map.on('moveend zoomend', () => {
|
||
sync3DCamera();
|
||
saveManualMapView();
|
||
});
|
||
map.on('zoomstart', () => {leafletZooming = true;});
|
||
map.on('zoomend', () => {
|
||
leafletZooming = false;
|
||
updateMapDrones(false);
|
||
});
|
||
const liveMapContainer = document.getElementById('liveMap3D');
|
||
for (const kind of ['pointerdown', 'wheel']) {
|
||
liveMapContainer.addEventListener(kind, takeManualMapControl, {passive:true});
|
||
}
|
||
mapViewToggle.addEventListener('click', () => setMap3D(!wantMap3D));
|
||
const legendToggle = document.querySelector('.mapLegendToggle');
|
||
legendToggle.addEventListener('click', () => {
|
||
legendToggle.setAttribute('aria-expanded', String(legendToggle.getAttribute('aria-expanded') !== 'true'));
|
||
});
|
||
legendToggle.closest('.legend').addEventListener('keydown', event => {
|
||
if (event.key !== 'Escape' || legendToggle.getAttribute('aria-expanded') !== 'true' || !legendToggle.offsetWidth) return;
|
||
event.preventDefault();
|
||
legendToggle.setAttribute('aria-expanded', 'false');
|
||
legendToggle.focus();
|
||
});
|
||
for (const [toggle, apply] of [
|
||
[flightTrailToggle, visible => {
|
||
if (visible) flightTrails.addTo(map);
|
||
else flightTrails.remove();
|
||
queue3DScene();
|
||
}],
|
||
[pilotMarkerToggle, () => {updateMapDrones(false);queue3DScene();}],
|
||
[modelLabelToggle, visible => {
|
||
modelLabelToggle.closest('.mapWrap').toggleAttribute('data-hide-models', !visible);
|
||
}]
|
||
]) {
|
||
const storageKey = 'bsrid_map_display_' + toggle.id;
|
||
try { toggle.checked = localStorage.getItem(storageKey) !== 'false'; } catch (_) {}
|
||
apply(toggle.checked);
|
||
toggle.addEventListener('change', () => {
|
||
apply(toggle.checked);
|
||
try { localStorage.setItem(storageKey, String(toggle.checked)); } catch (_) {}
|
||
});
|
||
}
|
||
new ResizeObserver(scheduleMapResize).observe(mapContainer);
|
||
window.addEventListener('resize', scheduleMapResize);
|
||
|
||
map.on('click', e => {
|
||
if (!drawing) return;
|
||
if (drawMode === 'rectangle' && drawPoints.length >= 2) return;
|
||
if (drawMode === 'circle' && drawPoints.length >= 2) return;
|
||
const raw = fromMapLatLng(e.latlng.lat, e.latlng.lng);
|
||
drawPoints.push({ lat: raw[0], lng: raw[1] });
|
||
previewDrawLayer();
|
||
});
|
||
|
||
function previewDrawLayer() {
|
||
if (drawLayer) map.removeLayer(drawLayer);
|
||
if (drawMode === 'polygon') {
|
||
drawLayer = L.polygon(drawPoints.map(p => toMapLatLng(p.lat, p.lng)), { color: '#ff5b6a', weight: 2, fillOpacity: .12 }).addTo(map)
|
||
} else if (drawMode === 'rectangle' && drawPoints.length >= 2) {
|
||
const a = toMapLatLng(drawPoints[0].lat, drawPoints[0].lng);
|
||
const b = toMapLatLng(drawPoints[1].lat, drawPoints[1].lng);
|
||
drawLayer = L.rectangle([a, b], { color: '#ff5b6a', weight: 2, fillOpacity: .12 }).addTo(map)
|
||
} else if (drawMode === 'circle' && drawPoints.length >= 2) {
|
||
const radius = metersBetween(drawPoints[0], drawPoints[1]);
|
||
drawLayer = L.circle(toMapLatLng(drawPoints[0].lat, drawPoints[0].lng), { radius, color: '#ff5b6a', weight: 2, fillOpacity: .12 }).addTo(map)
|
||
} else if (drawPoints.length === 1) {
|
||
drawLayer = L.circleMarker(toMapLatLng(drawPoints[0].lat, drawPoints[0].lng), { radius: 6, color: '#ffd35a' }).addTo(map)
|
||
}
|
||
}
|
||
function startDrawZone(mode) {
|
||
if (zoneSaving) return;
|
||
document.getElementById('zoneCoordinateEntry').open = false;
|
||
document.getElementById('zoneDrawEditor').hidden = false;
|
||
zoneFeedback('');
|
||
if (!drawing) {
|
||
drawing = true;
|
||
mapViewToggle.disabled = true;
|
||
// Drawing uses the flat map without changing the preferred camera mode.
|
||
++mapModeVersion;
|
||
paintMapMode(false);
|
||
}
|
||
drawMode = mode; drawPoints = [];
|
||
if (drawLayer) map.removeLayer(drawLayer);
|
||
const hint = { polygon: '多边形:依次点击边界点,至少3个点,然后点完成。', rectangle: '矩形:点击两个对角点,然后点完成。', circle: '圆形:先点圆心,再点半径边界点,然后点完成。' }[mode];
|
||
safeText('drawHint', hint);
|
||
}
|
||
function cancelDrawZone() {
|
||
const wasDrawing = drawing;
|
||
drawing = false;
|
||
drawPoints = [];
|
||
if (drawLayer) {
|
||
map.removeLayer(drawLayer);
|
||
drawLayer = null;
|
||
}
|
||
document.getElementById('zoneDrawEditor').hidden = true;
|
||
mapViewToggle.disabled = false;
|
||
if (wasDrawing && wantMap3D) setMap3D(true);
|
||
}
|
||
|
||
let zoneSaving = false;
|
||
|
||
function zoneFeedback(message, error = false) {
|
||
const feedback = document.getElementById('zoneFeedback');
|
||
feedback.textContent = message;
|
||
feedback.classList.toggle('error', error);
|
||
feedback.hidden = !message;
|
||
}
|
||
|
||
async function saveNewZone(name, type, points) {
|
||
if (zoneSaving) return null;
|
||
zoneSaving = true;
|
||
const buttons = [document.getElementById('zoneDrawSave'), document.getElementById('coordinateZoneSave')];
|
||
buttons.forEach(button => { button.disabled = true; });
|
||
zoneFeedback('正在保存防控区…');
|
||
try {
|
||
const response = await window.ridWorkbenchApi.fetch('/api/zones', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ name, type, points, enabled: true })
|
||
});
|
||
const saved = await response.json();
|
||
if (!response.ok || !saved.ok) throw new Error(saved.error || '无法保存防控区');
|
||
zoneFeedback(name + '已保存,并已启用。');
|
||
await loadZones().catch(() => zoneFeedback(name + '已保存,刷新页面后查看。'));
|
||
return saved.id;
|
||
} catch (error) {
|
||
zoneFeedback(error.message, true);
|
||
return null;
|
||
} finally {
|
||
zoneSaving = false;
|
||
buttons.forEach(button => { button.disabled = false; });
|
||
}
|
||
}
|
||
|
||
async function finishDrawZone() {
|
||
if (!drawing) return zoneFeedback('请先选择地图上的区域绘制工具。', true);
|
||
const required = drawMode === 'polygon' ? 3 : 2;
|
||
if (drawPoints.length < required) return zoneFeedback('请在地图上至少标记 ' + required + ' 个点。', true);
|
||
const points = drawMode === 'circle'
|
||
? [{...drawPoints[0], radius: metersBetween(drawPoints[0], drawPoints[1])}]
|
||
: drawPoints;
|
||
const nameInput = document.getElementById('zoneName');
|
||
if (await saveNewZone(nameInput.value.trim() || '防控区', drawMode, points)) {
|
||
cancelDrawZone();
|
||
nameInput.value = '';
|
||
}
|
||
}
|
||
|
||
function parseZonePoints(value, type) {
|
||
const lines = value.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
|
||
if (type === 'circle' && lines.length !== 1) throw new Error('圆形需要一行圆心坐标。');
|
||
if (type === 'rectangle' && lines.length !== 2) throw new Error('矩形需要两行对角点坐标。');
|
||
if (type === 'polygon' && (lines.length < 3 || lines.length > 128)) {
|
||
throw new Error('多边形需要 3 到 128 个顶点。');
|
||
}
|
||
const decimal = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
||
const points = lines.map((line, index) => {
|
||
const columns = line.split(/\s*[,,]\s*|\s+/);
|
||
const [lng, lat] = columns.map(Number);
|
||
if (columns.length !== 2 || !columns.every(column => decimal.test(column)) ||
|
||
Math.abs(lng) > 180 || Math.abs(lat) > 90) {
|
||
throw new Error('第 ' + (index + 1) + ' 行坐标无效,请按经度、纬度顺序输入。');
|
||
}
|
||
return {lat, lng};
|
||
});
|
||
if (type === 'rectangle' && (points[0].lat === points[1].lat || points[0].lng === points[1].lng)) {
|
||
throw new Error('矩形两个对角点的经度和纬度都应不同。');
|
||
}
|
||
return points;
|
||
}
|
||
|
||
function initZoneCoordinates() {
|
||
const panel = document.getElementById('zoneCoordinateEntry');
|
||
const form = document.getElementById('zoneCoordinateForm');
|
||
const name = document.getElementById('coordinateZoneName');
|
||
const type = document.getElementById('coordinateZoneType');
|
||
const coordinates = document.getElementById('zoneCoordinates');
|
||
const radius = document.getElementById('zoneRadius');
|
||
function updateShape() {
|
||
const circle = type.value === 'circle';
|
||
document.getElementById('zoneRadiusField').hidden = !circle;
|
||
radius.disabled = !circle;
|
||
radius.required = circle;
|
||
safeText('zoneCoordinateHelp', {
|
||
polygon: '按边界顺序输入 3 到 128 个顶点,每行一个。',
|
||
rectangle: '输入两个对角点,每行一个。',
|
||
circle: '输入一行圆心坐标,并填写半径。'
|
||
}[type.value]);
|
||
}
|
||
type.addEventListener('change', updateShape);
|
||
panel.addEventListener('toggle', () => {
|
||
if (panel.open && drawing) cancelDrawZone();
|
||
});
|
||
form.addEventListener('input', () => {
|
||
if (!zoneSaving) zoneFeedback('');
|
||
});
|
||
form.addEventListener('submit', async event => {
|
||
event.preventDefault();
|
||
if (zoneSaving) return;
|
||
try {
|
||
if (!name.value.trim()) throw new Error('请输入防控区名称。');
|
||
const points = parseZonePoints(coordinates.value, type.value);
|
||
if (type.value === 'circle') points[0].radius = radius.valueAsNumber;
|
||
const id = await saveNewZone(name.value.trim(), type.value, points);
|
||
if (!id) return;
|
||
form.reset();
|
||
updateShape();
|
||
panel.open = false;
|
||
focusZoneByKey(id);
|
||
} catch (error) {
|
||
zoneFeedback(error.message, true);
|
||
}
|
||
});
|
||
}
|
||
|
||
function drawZoneLayer(z) {
|
||
const popup = createZonePopupContent(zonePopupInfo(z));
|
||
const options = {className:'zoneMapPopup', maxWidth:260};
|
||
if (z.type === 'circle' && z.points.length) {
|
||
return L.circle(toMapLatLng(z.points[0].lat, z.points[0].lng), { radius: z.points[0].radius || 0, color: '#ff5b6a', weight: 2, fillOpacity: .15 }).addTo(map).bindPopup(popup, options);
|
||
}
|
||
if (z.type === 'rectangle' && z.points.length >= 2) {
|
||
return L.rectangle([
|
||
toMapLatLng(z.points[0].lat, z.points[0].lng),
|
||
toMapLatLng(z.points[1].lat, z.points[1].lng)
|
||
], { color: '#ff5b6a', weight: 2, fillOpacity: .15 }).addTo(map).bindPopup(popup, options);
|
||
}
|
||
return L.polygon(z.points.map(p => toMapLatLng(p.lat, p.lng)), { color: '#ff5b6a', weight: 2, fillOpacity: .15 }).addTo(map).bindPopup(popup, options);
|
||
}
|
||
function focusZoneByKey(id) {
|
||
const zone = zones.find(item => item.id === id);
|
||
if (!zone) return;
|
||
const points = zone.points.map(point => toMapLatLng(point.lat, point.lng));
|
||
const bounds = zoneLayers[id]?.getBounds() || (zone.type === 'circle'
|
||
? L.latLng(points[0]).toBounds(zone.points[0].radius * 2)
|
||
: L.latLngBounds(points));
|
||
takeManualMapControl();
|
||
map.fitBounds(bounds, {padding:[36,36], maxZoom:17, animate:false});
|
||
}
|
||
|
||
async function loadZones() {
|
||
const r = await window.ridWorkbenchApi.fetch('/api/zones');
|
||
const data = await r.json();
|
||
if (!r.ok || !Array.isArray(data)) throw new Error(data.error || '暂时无法读取防控区');
|
||
zones = data;
|
||
|
||
Object.values(zoneLayers).forEach(l => {
|
||
if (l) map.removeLayer(l);
|
||
});
|
||
zoneLayers = {};
|
||
|
||
zones.forEach(z => {
|
||
if (z.enabled) {
|
||
zoneLayers[z.id] = drawZoneLayer(z);
|
||
}
|
||
});
|
||
|
||
refreshSceneFences();
|
||
safeText('kpiZones', zones.length);
|
||
|
||
if (!zones.length) {
|
||
safeHtml('zoneList', '<li class="muted">暂无防控区</li>');
|
||
return;
|
||
}
|
||
|
||
const zoneListHtml = zones.map(z => {
|
||
const typeName = z.type === 'circle' ? '圆形' : (z.type === 'rectangle' ? '矩形' : '多边形');
|
||
const measureText = zoneMeasureText(z);
|
||
return `<li class="zoneListItem">
|
||
<button class="zoneFocus" type="button" data-rid-click="focusZoneByKey" data-rid-arg0="${escAttr(z.id)}" aria-label="定位防控区 ${escAttr(z.name)}">
|
||
<span class="zoneListHead"><b>${esc(z.name)}</b><span class="tag ${z.enabled ? 'green' : 'gray'}">${z.enabled ? '已启用' : '已停用'}</span></span>
|
||
<span class="zoneListMeta">${esc([typeName, measureText].filter(Boolean).join(' · '))}</span>
|
||
</button>
|
||
<div class="zoneActions">
|
||
<button class="smallBtn gray" data-rid-click="renameZone" data-rid-arg0="${escAttr(z.id)}">重命名</button>
|
||
<button class="smallBtn gray" data-rid-click="toggleZone" data-rid-arg0="${escAttr(z.id)}">${z.enabled ? '停用' : '启用'}</button>
|
||
<button class="smallBtn red" data-rid-click="deleteZone" data-rid-arg0="${escAttr(z.id)}">删除</button>
|
||
</div>
|
||
</li>`;
|
||
}).join('');
|
||
safeHtml('zoneList', zoneListHtml);
|
||
}
|
||
async function renameZone(id) {
|
||
const z = zones.find(item => item.id === id);
|
||
if (!z) return;
|
||
const name = prompt('请输入新的防控区名称', z.name);
|
||
if (!name) return;
|
||
const response = await window.ridWorkbenchApi.fetch('/api/zones/' + id, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, enabled: z.enabled }) });
|
||
if (!response.ok) throw new Error((await response.json()).error);
|
||
await loadZones();
|
||
}
|
||
async function toggleZone(id) {
|
||
const z = zones.find(item => item.id === id);
|
||
if (!z) return;
|
||
const response = await window.ridWorkbenchApi.fetch('/api/zones/' + id, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: z.name, enabled: !z.enabled }) });
|
||
if (!response.ok) throw new Error((await response.json()).error);
|
||
await loadZones();
|
||
}
|
||
async function deleteZone(id) {
|
||
if (!confirm('确定删除这个防控区吗?')) return;
|
||
const r = await window.ridWorkbenchApi.fetch('/api/zones/' + id, { method: 'DELETE' });
|
||
const d = await r.json().catch(() => ({ ok: false }));
|
||
if (r.ok && d.ok) {
|
||
if (zoneLayers[id]) {
|
||
map.removeLayer(zoneLayers[id]);
|
||
delete zoneLayers[id];
|
||
}
|
||
zones = zones.filter(z => z.id !== id);
|
||
await loadZones();
|
||
} else {
|
||
alert('删除失败:后端没有正确响应 DELETE /api/zones/' + id + ',HTTP状态:' + r.status);
|
||
}
|
||
}
|
||
|
||
function renderAlertList() {
|
||
safeText('kpiAlerts', alertCounts.read + alertCounts.unread);
|
||
safeHtml('alertBadge', `<span class="countWarning">未读 ${alertCounts.unread}</span><span class="countMuted">已读 ${alertCounts.read}</span>`);
|
||
const list = document.getElementById('alertList');
|
||
const liveModels = new Map(drones.filter(drone => drone.model && drone.model !== 'RID 目标')
|
||
.map(drone => [drone.uasId, drone.model]));
|
||
const markup = alerts.length
|
||
? [...alerts].sort((a,b)=>Number(a.handled)-Number(b.handled)||b.id-a.id).map(a => {
|
||
const serial = /^[a-z0-9]+$/i.test(a.uasId) ? a.uasId : undefined;
|
||
const model = liveModels.get(a.uasId)
|
||
|| window.ridWorkbenchApi.resolveModel(a.uasId, '', undefined, serial);
|
||
const located = validCoord(a.lat, a.lng);
|
||
const coordinates = located ? `${Number(a.lat).toFixed(6)}, ${Number(a.lng).toFixed(6)}` : '暂无坐标';
|
||
const locate = located
|
||
? `<button type="button" class="smallBtn gray" data-rid-click="focusAlertOnMap"
|
||
aria-label="定位告警目标 ${escAttr(a.uasId)}" data-rid-arg0="@n:${Number(a.lat)}" data-rid-arg1="@n:${Number(a.lng)}">定位</button>` : '';
|
||
const severity = window.ridFlightStatus.meta(a.kind).tone;
|
||
const unread = a.handled ? '' : '<span class="alert-unread-dot" role="img" aria-label="未读"></span>';
|
||
const acknowledge = !a.handled && canAcknowledgeAlert
|
||
? `<button type="button" class="smallBtn gray" data-rid-click="markAlarmHandled" data-rid-arg0="@n:${a.id}">标为已读</button>` : '';
|
||
const remove = `<button type="button" class="smallBtn red" aria-label="删除此条告警 ${escAttr(a.uasId)}" data-rid-click="deleteCenterAlarm" data-rid-arg0="@n:${a.id}">删除</button>`;
|
||
return `<article class="workbenchAlert ${severity}" data-alert-id="${a.id}">
|
||
<div class="workbenchAlertHead"><b>${esc(model || a.uasId)}</b><span class="workbenchAlertMeta"><time datetime="${new Date(a.timeMs).toISOString()}">${esc(a.time)}</time>${unread}</span></div>
|
||
<div class="alertClassification">${window.ridFlightStatus.tag(a.kind)}</div>
|
||
${model ? `<code class="workbenchAlertId">${esc(a.uasId)}</code>` : ''}
|
||
<div class="workbenchAlertTarget"><span class="workbenchAlertPosition">${coordinates}</span>${locate}${acknowledge}${remove}</div>
|
||
</article>`;
|
||
}).join('')
|
||
: '<div class="muted">暂无告警</div>';
|
||
if (list.dataset.renderedAlerts !== markup) {
|
||
list.innerHTML = markup;
|
||
list.dataset.renderedAlerts = markup;
|
||
}
|
||
renderAlarmEffect();
|
||
}
|
||
|
||
function focusAlertOnMap(lat, lng) {
|
||
takeManualMapControl();
|
||
mapSetViewWgs84(lat, lng, 18);
|
||
}
|
||
|
||
async function loadAlerts() {
|
||
if (!viewReady || apiPollState.alerts) return;
|
||
apiPollState.alerts = true;
|
||
const revision = alertReadRevision;
|
||
try {
|
||
const snapshot = await apiFetchJson('/api/alerts?after=' + clearedAlarmId, {}, 4500, 1);
|
||
if (revision !== alertReadRevision) return;
|
||
const newAlerts = snapshot.alerts;
|
||
alertCounts = { read: snapshot.read, unread: snapshot.unread };
|
||
const after = Math.max(latestAlarmId, clearedAlarmId);
|
||
pendingAlarmEffects.push(...newAlerts.filter(notice => !notice.handled && notice.id > after
|
||
&& notice.timeMs >= alarmPageOpenedAt));
|
||
latestAlarmId = Math.max(latestAlarmId, ...newAlerts.map(notice => notice.id));
|
||
alerts = newAlerts.filter(notice => notice.id > clearedAlarmId);
|
||
renderAlertList();
|
||
syncAlarmEffects();
|
||
} catch (e) {
|
||
console.warn('loadAlerts temporary failure', e);
|
||
} finally {
|
||
apiPollState.alerts = false;
|
||
}
|
||
}
|
||
function clearAllTrackLayers() {
|
||
|
||
flightTrails.clearLayers();
|
||
tracks = {};
|
||
droneTrackRaw = {};
|
||
trailSources.clear();
|
||
queue3DScene();
|
||
}
|
||
|
||
let activeModuleName = '';
|
||
|
||
const moduleNames = {
|
||
records: '轨迹记录',
|
||
'flight-plans': '飞行报备',
|
||
alarms: '报警查询',
|
||
drones: '黑白名单',
|
||
configs: '平台设置',
|
||
devices: '设备管理',
|
||
rankings: '统计分析',
|
||
models: '无人机型号库',
|
||
maps: '地图与离线下载',
|
||
users: '用户管理',
|
||
register: '设备登记',
|
||
archives: '本地档案',
|
||
history: '历史轨迹回放',
|
||
receivers: '接收器诊断'
|
||
};
|
||
const moduleGroups = {
|
||
alarms: 'records', rankings: 'records', history: 'records',
|
||
receivers: 'devices',
|
||
archives: 'register', drones: 'register', models: 'register', 'flight-plans':'register',
|
||
maps: 'configs', users: 'configs'
|
||
};
|
||
|
||
async function apiGet(url) {
|
||
const r = await window.ridWorkbenchApi.fetch(url);
|
||
const data = await r.json();
|
||
if (!r.ok) throw new Error(data.error || '接口请求失败');
|
||
return data;
|
||
}
|
||
|
||
async function apiSend(url, method, body) {
|
||
const r = await window.ridWorkbenchApi.fetch(url, {
|
||
method,
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(body || {})
|
||
});
|
||
return await r.json().catch(() => ({}));
|
||
}
|
||
|
||
async function loadCurrentUser() {
|
||
const data = await apiGet('/api/current_user').catch(() => ({}));
|
||
const user = data.user || {};
|
||
canAcknowledgeAlert = user.canAcknowledge === true;
|
||
renderAlertList();
|
||
const el = document.getElementById('currentUserName');
|
||
if (el) {
|
||
el.textContent = user.displayName ? `${user.displayName} · ${user.role || ''}` : '未登录';
|
||
el.title = el.textContent;
|
||
}
|
||
}
|
||
|
||
async function logout() {
|
||
await window.ridWorkbenchApi.fetch('/api/logout', { method: 'POST' });
|
||
location.href = '/workbench/';
|
||
}
|
||
|
||
let moduleTrigger;
|
||
const moduleSiblings = () => document.querySelectorAll('#app .main > :is(.left, .right, .mapWrap)');
|
||
|
||
function updateNavigation(name) {
|
||
const group = moduleGroups[name] || name;
|
||
const nav = document.getElementById('workbenchNav');
|
||
nav.querySelectorAll('[data-rid-click="openModule"], [data-rid-click="fitAll"]').forEach(button => {
|
||
const selected = (button.dataset.ridArg0 || '') === group;
|
||
if (selected) button.setAttribute('aria-current', 'page');
|
||
else button.removeAttribute('aria-current');
|
||
});
|
||
for (const section of document.querySelectorAll('.moduleNav')) {
|
||
section.hidden = section.dataset.moduleGroup !== group;
|
||
for (const button of section.querySelectorAll('button[data-rid-arg0]')) {
|
||
if (!section.hidden && button.dataset.ridArg0 === (name === 'history' ? 'records' : name)) {
|
||
button.setAttribute('aria-current', 'page');
|
||
} else {
|
||
button.removeAttribute('aria-current');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
function showModuleHeading(name) {
|
||
activeModuleName = name;
|
||
document.getElementById('moduleTitle').textContent = moduleNames[name];
|
||
updateNavigation(name);
|
||
}
|
||
|
||
function openModule(name, record) {
|
||
if (!Object.hasOwn(moduleNames, name)) return;
|
||
if (name !== 'history' && name === activeModuleName) return;
|
||
if (name === 'records' && activeModuleName === 'history' && window.ridModuleHost.returnToRecords()) return;
|
||
const workspace = document.getElementById('moduleWorkspace');
|
||
const opening = !activeModuleName;
|
||
if (opening) moduleTrigger = document.activeElement;
|
||
workspace.classList.add('active');
|
||
moduleSiblings().forEach(element => { element.inert = true; });
|
||
showModuleHeading(name);
|
||
if (opening) document.getElementById('moduleTitle').focus();
|
||
|
||
if (window.ridModuleHost.show(name, record)) return;
|
||
if (name === 'alarms') return renderAlarmQuery();
|
||
return window.ridWorkbenchModules.open(name,record);
|
||
}
|
||
|
||
function closeModule(restoreFocus = true) {
|
||
activeModuleName = '';
|
||
updateNavigation('');
|
||
document.getElementById('moduleWorkspace').classList.remove('active');
|
||
window.ridModuleHost.hide();
|
||
moduleSiblings().forEach(element => { element.inert = false; });
|
||
if (restoreFocus && moduleTrigger instanceof HTMLElement) moduleTrigger.focus();
|
||
moduleTrigger = null;
|
||
setTimeout(() => map.invalidateSize(), 120);
|
||
}
|
||
|
||
function fieldValue(id) {
|
||
return document.getElementById(id)?.value?.trim() || '';
|
||
}
|
||
|
||
function localDateTimeParam(id, suffix) {
|
||
const raw = fieldValue(id);
|
||
return raw ? raw.replace('T', ' ') + suffix : '';
|
||
}
|
||
|
||
function renderTable(columns, rows, emptyText = '暂无数据') {
|
||
if (!rows || !rows.length) return `<div class="moduleEmpty">${esc(emptyText)}</div>`;
|
||
return `<div class="dataTableWrap" tabindex="0" role="region" aria-label="数据表格"><table class="dataTable"><thead><tr>${columns.map(c => `<th scope="col">${esc(c.label)}</th>`).join('')}</tr></thead><tbody>${rows.map(row => `<tr>${columns.map(c => `<td>${c.render ? c.render(row) : esc(row[c.key] ?? '')}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`;
|
||
}
|
||
|
||
function lastPageOffset(total, pageSize) {
|
||
return Math.max(0, Math.ceil(total / pageSize) - 1) * pageSize;
|
||
}
|
||
|
||
function renderPager(label, offset, total, pageSize) {
|
||
const last = lastPageOffset(total, pageSize);
|
||
const page = Math.floor(offset / pageSize) + 1;
|
||
return `<nav class="rid-pager" aria-label="${escAttr(label)}">
|
||
<span class="rid-page-summary">${total ? '第 ' + (offset + 1) + '–' + Math.min(offset + pageSize, total) + ' 条' : '共 0 条'} <span>· 每页 ${pageSize} 条</span></span>
|
||
<div class="rid-pager-actions">
|
||
<button type="button" data-page-offset="${offset - pageSize}" data-page-direction="previous" ${!offset ? 'disabled' : ''}>上一页</button>
|
||
<span class="rid-page-number" tabindex="-1" aria-live="polite">第 ${page} / ${last / pageSize + 1} 页</span>
|
||
<button type="button" data-page-offset="${offset + pageSize}" data-page-direction="next" ${offset >= last ? 'disabled' : ''}>下一页</button>
|
||
</div>
|
||
</nav>`;
|
||
}
|
||
|
||
function bindPager(scope, load, focusDirection) {
|
||
const pager = scope.querySelector('.rid-pager');
|
||
if (!pager) return;
|
||
for (const button of pager.querySelectorAll('button[data-page-offset]')) {
|
||
button.addEventListener('click', async () => {
|
||
if (pager.getAttribute('aria-busy') === 'true') return;
|
||
pager.setAttribute('aria-busy', 'true');
|
||
try { await load(Number(button.dataset.pageOffset), button.dataset.pageDirection); }
|
||
finally { pager.removeAttribute('aria-busy'); }
|
||
});
|
||
}
|
||
if (focusDirection) {
|
||
(pager.querySelector(`[data-page-direction="${focusDirection}"]:enabled`) || pager.querySelector('.rid-page-number'))?.focus();
|
||
}
|
||
}
|
||
|
||
function setDefaultModuleDates(startId, endId) {
|
||
const now = new Date();
|
||
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
|
||
const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 0);
|
||
const s = document.getElementById(startId), e = document.getElementById(endId);
|
||
if (s && !s.value) s.value = toDatetimeLocalValue(start);
|
||
if (e && !e.value) e.value = toDatetimeLocalValue(end);
|
||
}
|
||
|
||
let refreshAlarmPage;
|
||
async function renderAlarmQuery() {
|
||
const body = document.getElementById('moduleBody');
|
||
body.innerHTML = `
|
||
<form id="alarmFilters" class="filterBar rid-period">
|
||
<label>关键字<input id="alarmKeyword" placeholder="UAS ID / 类型 / 内容"></label>
|
||
<label>告警类型<select id="alarmType"><option value="">全部类型</option><option value="unregistered">未登记告警</option><option value="unfiled">未报备告警</option><option value="geofence_enter">防控区告警</option><option value="blacklist">黑名单告警</option></select></label>
|
||
<label>处置状态<select id="alarmHandled"><option value="">全部状态</option><option value="0">未处置</option><option value="1">已处置</option></select></label>
|
||
<label>开始时间<input id="alarmStart" type="datetime-local"></label>
|
||
<label>结束时间<input id="alarmEnd" type="datetime-local"></label>
|
||
<button type="submit">查询</button>
|
||
</form>
|
||
<div id="alarmResult" class="moduleResult" aria-live="polite"></div>`;
|
||
const result = body.querySelector('#alarmResult');
|
||
const pageSize = 50;
|
||
let query, generation = 0, currentOffset = 0;
|
||
const cols = [
|
||
{ label: '时间', key: 'time' },
|
||
{ label: '目标', key: 'uasId' },
|
||
{ label: '类型', render:r=>window.ridFlightStatus.tag(r.kind) },
|
||
{ label: '内容', key: 'message' },
|
||
{ label: '坐标', render: r => r.lat == null || r.lng == null ? '—' : `${esc(r.lat)}, ${esc(r.lng)}` },
|
||
{ label: '状态', render: r => r.handled ? '<span class="stateTag ok">已处置</span>' : '<span class="stateTag danger">未处置</span>' },
|
||
{ label: '操作', render: r => r.handled ? '' : `<button class="smallBtn" data-rid-click="markAlarmHandled" data-rid-arg0="@n:${r.id}">标记处置</button>` }
|
||
];
|
||
async function load(offset, direction) {
|
||
if (!query || !result.isConnected || activeModuleName !== 'alarms') return;
|
||
const requestId = ++generation;
|
||
const params = new URLSearchParams(query);
|
||
params.set('offset', offset);
|
||
result.innerHTML = '<div class="moduleEmpty">正在查询告警…</div>';
|
||
try {
|
||
const data = await apiGet('/api/alerts_query?' + params);
|
||
if (!result.isConnected || requestId !== generation || activeModuleName !== 'alarms') return;
|
||
const last = lastPageOffset(data.count, pageSize);
|
||
if (offset > last) return load(last, direction);
|
||
if (!query.has('before') && data.alerts.length) query.set('before', data.alerts[0].id + 1);
|
||
currentOffset = offset;
|
||
result.innerHTML = `<div class="resultCount">共 ${data.count} 条告警</div>`
|
||
+ renderTable(cols, data.alerts, '没有匹配告警') + renderPager('报警分页', offset, data.count, pageSize);
|
||
bindPager(result, load, direction);
|
||
} catch (error) {
|
||
if (result.isConnected && requestId === generation) {
|
||
result.innerHTML = `<div class="moduleEmpty">${esc(error.message)},请重新查询。</div>`;
|
||
}
|
||
}
|
||
}
|
||
function submit() {
|
||
const start = localDateTimeParam('alarmStart', ':00');
|
||
const end = localDateTimeParam('alarmEnd', ':59');
|
||
if (start && end && start > end) {
|
||
generation++;
|
||
query = null;
|
||
result.innerHTML = '<div class="moduleEmpty">开始时间须早于结束时间</div>';
|
||
return;
|
||
}
|
||
query = new URLSearchParams({keyword:fieldValue('alarmKeyword'), type:fieldValue('alarmType'), handled:fieldValue('alarmHandled'), start, end});
|
||
return load(0);
|
||
}
|
||
body.querySelector('#alarmFilters').addEventListener('submit', event => {
|
||
event.preventDefault();
|
||
submit();
|
||
});
|
||
refreshAlarmPage = () => load(currentOffset);
|
||
setDefaultModuleDates('alarmStart', 'alarmEnd');
|
||
await submit();
|
||
}
|
||
|
||
async function markAlarmHandled(id) {
|
||
const feedback = document.getElementById('alertFeedback');
|
||
feedback.hidden = true;
|
||
try {
|
||
const result = await apiSend('/api/alerts_query', 'PUT', { id, handled: true });
|
||
if (!result.ok) throw new Error(result.error || '标记已读失败');
|
||
++alertReadRevision;
|
||
const item = alerts.find(notice => notice.id === id);
|
||
if (item && !item.handled) {
|
||
item.handled = true;
|
||
alertCounts.unread = Math.max(0, alertCounts.unread - 1);
|
||
alertCounts.read++;
|
||
}
|
||
pendingAlarmEffects = pendingAlarmEffects.filter(notice => notice.id !== id);
|
||
if (activeAlarm?.id === id) stopAlarmEffect();
|
||
renderAlertList();
|
||
await refreshAlarmPage?.();
|
||
await loadAlerts();
|
||
} catch (error) {
|
||
feedback.hidden = false;
|
||
feedback.textContent = error.message;
|
||
}
|
||
}
|
||
|
||
async function deleteCenterAlarm(id) {
|
||
const feedback = document.getElementById('alertFeedback');
|
||
feedback.hidden = true;
|
||
try {
|
||
await window.ridWorkbenchApi.request(`/api/monitoring/events/${id}/dismissal`, 'PUT', {});
|
||
++alertReadRevision;
|
||
const item = alerts.find(notice => notice.id === id);
|
||
if (item) {
|
||
const category = item.handled ? 'read' : 'unread';
|
||
alertCounts[category] = Math.max(0, alertCounts[category] - 1);
|
||
}
|
||
alerts = alerts.filter(notice => notice.id !== id);
|
||
pendingAlarmEffects = pendingAlarmEffects.filter(notice => notice.id !== id);
|
||
if (activeAlarm?.id === id) stopAlarmEffect();
|
||
renderAlertList();
|
||
await loadAlerts();
|
||
} catch (error) {
|
||
feedback.hidden = false;
|
||
feedback.textContent = error.message;
|
||
}
|
||
}
|
||
|
||
function applyPlatformName(name) {
|
||
const platformName = String(name || 'RID侦测平台').trim() || 'RID侦测平台';
|
||
const titleEl = document.getElementById('platformTitle');
|
||
if (titleEl) titleEl.textContent = platformName;
|
||
document.title = `${platformName} · 本地融合版`;
|
||
const input = document.getElementById('myPlatformName');
|
||
if (input && document.activeElement !== input) input.value = platformName;
|
||
return platformName;
|
||
}
|
||
|
||
function applyPlatformSettings(settings) {
|
||
applyPlatformName(settings.name);
|
||
document.getElementById('soundAlarmToggle').checked = settings.sound;
|
||
document.getElementById('flashAlarmToggle').checked = settings.flash;
|
||
alarmDurationMs = (settings.flashSeconds ?? 10) * 1000;
|
||
renderAlarmEffect();
|
||
}
|
||
|
||
async function loadPlatformName() {
|
||
const settings = await window.ridWorkbenchApi.request('/api/workbench/settings').catch(() => null);
|
||
if (settings) applyPlatformSettings(settings);
|
||
}
|
||
|
||
document.getElementById('flashAlarmToggle').addEventListener('change', renderAlarmEffect);
|
||
window.addEventListener('storage', event => {
|
||
if (event.key !== clearedAlarmKey) return;
|
||
clearedAlarmId = readClearedAlarmId();
|
||
++alertReadRevision;
|
||
alerts = alerts.filter(notice => notice.id > clearedAlarmId);
|
||
alertCounts = { read: alerts.filter(notice => notice.handled).length, unread: alerts.filter(notice => !notice.handled).length };
|
||
if (activeAlarm?.id <= clearedAlarmId) stopAlarmEffect();
|
||
renderAlertList();
|
||
loadAlerts();
|
||
});
|
||
initZoneCoordinates();
|
||
async function initializeView() {
|
||
try {
|
||
const saved = await window.ridWorkbenchApi.request('/api/workbench/view');
|
||
// Server state belongs to this account and data directory; a browser's old cursor may belong to another package.
|
||
clearedAlarmId = saved.clearedAlarmId ?? 0;
|
||
const prefs = await window.ridWorkbenchApi.preferences();
|
||
await refreshMapCacheQuickToggle().then(applySavedDefaultMap);
|
||
if (!restoreManualMapView(saved.camera)) mapSetViewWgs84(prefs.latitude, prefs.longitude, prefs.zoom);
|
||
if (wantMap3D && mapModeVersion === 0) await setMap3D(true);
|
||
viewReady = true;
|
||
const entry=new URLSearchParams(location.search);
|
||
if (entry.get('module')==='flight-plans') openModule('flight-plans',{recordId:entry.get('record')});
|
||
loadDrones(); loadLocalStations(); loadAlerts();
|
||
setInterval(loadDrones, 1500); setInterval(loadAlerts, 2000); setInterval(loadLocalStations, 2000);
|
||
} catch (error) {
|
||
viewSaveError(error);
|
||
setTimeout(initializeView, 3000);
|
||
}
|
||
}
|
||
window.addEventListener('pagehide', () => {
|
||
if (!viewReady || !savedCamera) return;
|
||
clearTimeout(viewSaveTimer);
|
||
// Dispatch directly while leaving the page; do not wait for a queued promise.
|
||
window.ridWorkbenchApi.request('/api/workbench/view', 'PUT', {camera:savedCamera}, {keepalive:true}).catch(() => {});
|
||
});
|
||
loadCurrentUser(); loadZones().catch(error => zoneFeedback(error.message, true));
|
||
loadPlatformName().finally(initializeView);
|