一、审计修复(另一侧完成,我复核通过) - 认证/限流:_client_ip 归一、限流统一走 rate_limit._SlidingTable(超限只淘汰最旧 key, 不再整表 clear 自毁)、每用户会话上限 10 + 过期清理 - 邮件验证码:锁内原子占位 → 锁外发信 → 成功落码,失败回滚冷却(并发不再双发) - 租赁:rentals 部分唯一索引(同 order_id 只允许一行 expired=0,迁移前先查重)、 开锁幂等落库、Timer 代号机制(取消/重排同临界区)、minutes=null 兜底、 自动还车 30s×6 → 1m/2m/5m/10m 退避 - 安全:ring 四接口登录 + 任务归属校验(Bearer 或 ?token=,校验 sessions 表)、 共享还车坐标不再伪造、代开锁 IntegrityError 兜底、token 配置原子写(fsync + 0600) - 入口鉴权:8 个历史/分析接口未登录 401(HTTP 与 rtn_code 同时给)、 analysis.html 带 Bearer + 未登录门 + 截断提示、历史查询 LIMIT 60000 并回传 truncated - UX 四个 P0:计时条出现、真实单走 /api/order/return 而 reminder 走 /api/rental/return、 定位失败不伪造坐标(三选一弹窗)、地图/配置/脚本失败统一落到可自救失败卡片 - 测试:新增 6 个文件 62 例;既有 test_history_30d 只补登录前置 二、我复核时发现并修掉的 7 处 ① email_verify.record_cooldown 的 expires 写成 now,会被 send_code 开头的 _cleanup_locked 整条删掉 —— 任何人发一次验证码就废掉「未注册邮箱」的冷却, 找回密码又能枚举邮箱是否注册。改为活过冷却窗口,并补 3 例测试 ② timer.py 两处落库(自动续租 INSERT、sync 复活 UPDATE)没防新唯一索引: 撞索引抛 IntegrityError 会让巡检线程退出,该单从此没有计时器/自动还车(上游还在计费)。 新增 _active_rental_id_for_order(),捕获后复用存活行 ③ (0,0) 当合法坐标会先发给上游:/record/return 不校验范围,宽松后端会把车"还"在海里。 新增 _coords_usable(),不可用就跳过原始点;候选列表永远丢掉第 0 项 ④ boot_smoke.py 按旧契约要求 200,加鉴权后永远失败 → HTTPError 401 视为「未登录,预期」 ⑤ 自动还车「不放弃」缺绝对上限:加 AUTO_RETURN_GIVE_UP_SECONDS=6h,到点只告警一次并停手 ⑥ 索引谓词 aligned 到查重口径:COALESCE(expired,0)=0,旧定义自动重建 ⑦ 访问日志脱敏:?token= / ?ticket= / ?access_token= 的值替换为 ***(werkzeug + root logger) 否则容器日志里就是明文会话令牌 配套改写 tests/test_rental_dedup.py::test_return_accepts_zero_coordinates → test_return_treats_zero_coordinates_as_missing(原断言把 (0,0) 当合法值发上游) 三、验证 - python -m pytest -q → 234 passed(基线 231,净增 3) - node 5 套 → 44 pass / 0 fail - 14 个 .py ast.parse、node --check dist/app.js → 全部通过 - boot_smoke.py → exit=0;未登录 /api/history/stats、/api/analysis/overview、 /api/ring_progress/* 实测 401,/api/config 200 - 行为级:传 (0,0) 时上游只收到候选点;合法坐标仍先发上报值;唯一索引拦住重复插入
1528 lines
65 KiB
HTML
1528 lines
65 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||
<title>数据分析 - 小白超人</title>
|
||
<style>
|
||
:root {
|
||
--bg-primary: #ffffff;
|
||
--bg-secondary: #f5f5f7;
|
||
--bg-card: #ffffff;
|
||
--text-primary: #1d1d1f;
|
||
--text-secondary: #6e6e73;
|
||
--text-tertiary: #86868b;
|
||
--border-color: #e5e5ea;
|
||
--accent-color: #0071e3;
|
||
--accent-hover: #0077ed;
|
||
--success: #34c759;
|
||
--warning: #ff9500;
|
||
--danger: #ff3b30;
|
||
--shadow-sm: 0 2px 8px rgba(0,0,0,0.08);
|
||
--shadow-md: 0 4px 20px rgba(0,0,0,0.12);
|
||
--radius-sm: 8px;
|
||
--radius-md: 12px;
|
||
--radius-lg: 16px;
|
||
}
|
||
|
||
@media (prefers-color-scheme: dark) {
|
||
:root {
|
||
--bg-primary: #000000;
|
||
--bg-secondary: #1c1c1e;
|
||
--bg-card: #2c2c2e;
|
||
--text-primary: #f5f5f7;
|
||
--text-secondary: #98989d;
|
||
--text-tertiary: #636366;
|
||
--border-color: #38383a;
|
||
--accent-color: #0a84ff;
|
||
--accent-hover: #409cff;
|
||
--success: #30d158;
|
||
--warning: #ff9f0a;
|
||
--danger: #ff453a;
|
||
--shadow-sm: 0 2px 8px rgba(0,0,0,0.3);
|
||
--shadow-md: 0 4px 20px rgba(0,0,0,0.4);
|
||
}
|
||
}
|
||
|
||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||
|
||
body {
|
||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||
background: var(--bg-primary);
|
||
color: var(--text-primary);
|
||
min-height: 100vh;
|
||
}
|
||
|
||
.header {
|
||
background: var(--bg-secondary);
|
||
padding: 14px 20px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 1px solid var(--border-color);
|
||
position: sticky;
|
||
top: 0;
|
||
z-index: 100;
|
||
}
|
||
.header-title { font-size: 17px; font-weight: 600; }
|
||
.header-back {
|
||
width: 34px;
|
||
height: 34px;
|
||
border-radius: 50%;
|
||
background: var(--bg-card);
|
||
border: 1px solid var(--border-color);
|
||
color: var(--accent-color);
|
||
cursor: pointer;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 18px;
|
||
}
|
||
|
||
.container { padding: 16px; max-width: 800px; margin: 0 auto; }
|
||
|
||
/* 统计卡片 */
|
||
.stats-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(2, 1fr);
|
||
gap: 12px;
|
||
margin-bottom: 20px;
|
||
}
|
||
.stat-card {
|
||
background: var(--bg-card);
|
||
border-radius: var(--radius-md);
|
||
padding: 16px;
|
||
box-shadow: var(--shadow-sm);
|
||
border: 1px solid var(--border-color);
|
||
}
|
||
.stat-label { font-size: 12px; color: var(--text-secondary); margin-bottom: 4px; }
|
||
.stat-value { font-size: 24px; font-weight: 700; color: var(--accent-color); }
|
||
.stat-sub { font-size: 11px; color: var(--text-tertiary); margin-top: 4px; }
|
||
|
||
/* Tab导航 */
|
||
.tab-nav {
|
||
display: flex;
|
||
background: var(--bg-secondary);
|
||
border-radius: var(--radius-md);
|
||
padding: 4px;
|
||
margin-bottom: 16px;
|
||
gap: 4px;
|
||
}
|
||
.tab-btn {
|
||
flex: 1;
|
||
padding: 10px 12px;
|
||
border: none;
|
||
background: transparent;
|
||
border-radius: var(--radius-sm);
|
||
font-size: 14px;
|
||
font-weight: 500;
|
||
color: var(--text-secondary);
|
||
cursor: pointer;
|
||
transition: all 0.2s;
|
||
}
|
||
.tab-btn.active {
|
||
background: var(--bg-card);
|
||
color: var(--accent-color);
|
||
box-shadow: var(--shadow-sm);
|
||
}
|
||
|
||
/* 面板 */
|
||
.panel {
|
||
background: var(--bg-card);
|
||
border-radius: var(--radius-lg);
|
||
padding: 16px;
|
||
margin-bottom: 16px;
|
||
box-shadow: var(--shadow-sm);
|
||
border: 1px solid var(--border-color);
|
||
}
|
||
.panel-title {
|
||
font-size: 15px;
|
||
font-weight: 600;
|
||
margin-bottom: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
}
|
||
.panel-title::before {
|
||
content: "";
|
||
width: 4px;
|
||
height: 16px;
|
||
background: var(--accent-color);
|
||
border-radius: 2px;
|
||
}
|
||
|
||
/* 表单控件 */
|
||
.form-row {
|
||
display: flex;
|
||
gap: 10px;
|
||
margin-bottom: 12px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.form-group {
|
||
flex: 1;
|
||
min-width: 120px;
|
||
}
|
||
.form-label {
|
||
font-size: 12px;
|
||
color: var(--text-secondary);
|
||
margin-bottom: 4px;
|
||
display: block;
|
||
}
|
||
select, input {
|
||
width: 100%;
|
||
padding: 10px 12px;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: var(--radius-sm);
|
||
background: var(--bg-primary);
|
||
color: var(--text-primary);
|
||
font-size: 14px;
|
||
outline: none;
|
||
}
|
||
select:focus, input:focus {
|
||
border-color: var(--accent-color);
|
||
}
|
||
|
||
/* 按钮 */
|
||
.btn {
|
||
padding: 10px 20px;
|
||
border: none;
|
||
border-radius: var(--radius-sm);
|
||
font-size: 14px;
|
||
font-weight: 500;
|
||
cursor: pointer;
|
||
transition: all 0.2s;
|
||
}
|
||
.btn-primary {
|
||
background: var(--accent-color);
|
||
color: white;
|
||
}
|
||
.btn-primary:hover { background: var(--accent-hover); }
|
||
.btn-secondary {
|
||
background: var(--bg-secondary);
|
||
color: var(--text-primary);
|
||
border: 1px solid var(--border-color);
|
||
}
|
||
.btn-secondary:hover { background: var(--border-color); }
|
||
|
||
/* 地图容器 */
|
||
.map-container {
|
||
width: 100%;
|
||
height: 350px;
|
||
background: var(--bg-secondary);
|
||
border-radius: var(--radius-md);
|
||
margin: 12px 0;
|
||
overflow: hidden;
|
||
position: relative;
|
||
}
|
||
.map-placeholder {
|
||
width: 100%;
|
||
height: 100%;
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
justify-content: center;
|
||
color: var(--text-tertiary);
|
||
}
|
||
.map-placeholder svg { width: 48px; height: 48px; margin-bottom: 8px; opacity: 0.5; }
|
||
|
||
/* 图表 */
|
||
.chart-container {
|
||
height: 200px;
|
||
background: var(--bg-secondary);
|
||
border-radius: var(--radius-md);
|
||
padding: 16px;
|
||
margin: 12px 0;
|
||
}
|
||
|
||
/* 时间轴 */
|
||
.timeline-slider {
|
||
width: 100%;
|
||
margin: 12px 0;
|
||
}
|
||
input[type="range"] {
|
||
width: 100%;
|
||
height: 8px;
|
||
-webkit-appearance: none;
|
||
background: var(--bg-secondary);
|
||
border-radius: 4px;
|
||
outline: none;
|
||
}
|
||
input[type="range"]::-webkit-slider-thumb {
|
||
-webkit-appearance: none;
|
||
width: 20px;
|
||
height: 20px;
|
||
background: var(--accent-color);
|
||
border-radius: 50%;
|
||
cursor: pointer;
|
||
}
|
||
|
||
/* 车辆列表 */
|
||
.bike-list {
|
||
max-height: 200px;
|
||
overflow-y: auto;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: var(--radius-sm);
|
||
}
|
||
.bike-item {
|
||
padding: 10px 12px;
|
||
border-bottom: 1px solid var(--border-color);
|
||
cursor: pointer;
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
transition: background 0.2s;
|
||
}
|
||
.bike-item:last-child { border-bottom: none; }
|
||
.bike-item:hover { background: var(--bg-secondary); }
|
||
.bike-item.selected { background: rgba(0, 113, 227, 0.1); }
|
||
.bike-code { font-weight: 600; font-size: 14px; }
|
||
.bike-meta { font-size: 11px; color: var(--text-tertiary); }
|
||
|
||
/* 状态标签(与 map.html 图例一致) */
|
||
.status-badge {
|
||
display: inline-block;
|
||
padding: 2px 8px;
|
||
border-radius: 10px;
|
||
font-size: 11px;
|
||
font-weight: 500;
|
||
}
|
||
/* available: state=1 && status!=1,绿色 */
|
||
.state-available { background: rgba(52, 199, 89, 0.15); color: #34c759; }
|
||
/* used: state=1 && status=1,红色 */
|
||
.state-used { background: rgba(255, 45, 85, 0.15); color: #ff2d55; }
|
||
/* locked: state=4 欠压,橙色 */
|
||
.state-locked { background: rgba(255, 159, 10, 0.15); color: #ff9f0a; }
|
||
/* reserved: state=2 损坏,紫色 */
|
||
.state-reserved { background: rgba(88, 86, 214, 0.15); color: #5856D6; }
|
||
/* low: state=10 或 electric<20,灰色 */
|
||
.state-low { background: rgba(142, 142, 147, 0.15); color: #8e8e93; }
|
||
/* 保留旧类,兼容 Top10 "查看轨迹" 按钮 */
|
||
.status-1 { background: rgba(52, 199, 89, 0.15); color: #34c759; }
|
||
|
||
/* 加载状态 */
|
||
.loading {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
padding: 40px;
|
||
color: var(--text-tertiary);
|
||
}
|
||
.spinner {
|
||
width: 24px;
|
||
height: 24px;
|
||
border: 3px solid var(--border-color);
|
||
border-top-color: var(--accent-color);
|
||
border-radius: 50%;
|
||
animation: spin 1s linear infinite;
|
||
margin-right: 8px;
|
||
}
|
||
@keyframes spin { to { transform: rotate(360deg); } }
|
||
|
||
/* 提示信息 */
|
||
.tip {
|
||
font-size: 12px;
|
||
color: var(--text-tertiary);
|
||
padding: 8px 12px;
|
||
background: var(--bg-secondary);
|
||
border-radius: var(--radius-sm);
|
||
margin-top: 8px;
|
||
}
|
||
|
||
/* 热度指示 */
|
||
.heat-legend {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
gap: 8px;
|
||
font-size: 11px;
|
||
color: var(--text-tertiary);
|
||
margin-top: 8px;
|
||
}
|
||
.heat-gradient {
|
||
width: 120px;
|
||
height: 12px;
|
||
background: linear-gradient(to right, #4CAF50, #FFEB3B, #FF9800, #F44336);
|
||
border-radius: 6px;
|
||
}
|
||
/* 轨迹高亮点平滑过渡 */
|
||
.traj-marker-container {
|
||
transition: transform 0.15s ease-out;
|
||
}
|
||
/* 标注点悬浮 Label 样式 */
|
||
.traj-label {
|
||
background: rgba(0,0,0,0.75);
|
||
color: #fff;
|
||
padding: 4px 8px;
|
||
border-radius: 4px;
|
||
font-size: 12px;
|
||
font-weight: 500;
|
||
white-space: nowrap;
|
||
pointer-events: none;
|
||
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
|
||
}
|
||
.traj-label::after {
|
||
content: '';
|
||
position: absolute;
|
||
left: 50%;
|
||
bottom: -6px;
|
||
transform: translateX(-50%);
|
||
border: 6px solid transparent;
|
||
border-top-color: rgba(0,0,0,0.75);
|
||
}
|
||
</style>
|
||
<link rel="stylesheet" href="/static/css/ui-system.css">
|
||
<script defer src="/static/js/ui-motion.js"></script>
|
||
</head>
|
||
<body>
|
||
<header class="header">
|
||
<button class="header-back" onclick="uiNavigate('/')" aria-label="返回地图">←</button>
|
||
<div class="header-title">数据分析</div>
|
||
<div style="width: 34px;"></div>
|
||
</header>
|
||
|
||
<div class="container">
|
||
<!-- 加载失败提示(429/网络/上游失败时显示,点击重试) -->
|
||
<div id="stats-error" style="display:none;margin:10px 0;padding:10px 14px;border-radius:10px;
|
||
background:#fef2f2;color:#b91c1c;font-size:13px;cursor:pointer;border:1px solid #fecaca;"></div>
|
||
<!-- 统计概览 -->
|
||
<div class="stats-grid">
|
||
<div class="stat-card">
|
||
<div class="stat-label">采集车辆</div>
|
||
<div class="stat-value" id="stat-bikes">-</div>
|
||
<div class="stat-sub" id="stat-points">等待加载...</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-label">数据时间范围</div>
|
||
<div class="stat-value" id="stat-range">-</div>
|
||
<div class="stat-sub" id="stat-sub-range">最近24小时</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-label">数据采集时间</div>
|
||
<div class="stat-value" id="stat-latest">-</div>
|
||
<div class="stat-sub">最近更新</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-label">可用车辆</div>
|
||
<div class="stat-value" id="stat-avail">-</div>
|
||
<div class="stat-sub" id="stat-status">状态分布</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Tab切换 -->
|
||
<div class="tab-nav">
|
||
<button class="tab-btn active" onclick="switchTab('trajectory')">轨迹回放</button>
|
||
<button class="tab-btn" onclick="switchTab('heatmap')">分布云图</button>
|
||
<button class="tab-btn" onclick="switchTab('stats')">统计报表</button>
|
||
</div>
|
||
|
||
<!-- 轨迹回放面板 -->
|
||
<div id="panel-trajectory" class="panel">
|
||
<div class="panel-title">车辆轨迹回放</div>
|
||
|
||
<div class="form-row">
|
||
<div class="form-group">
|
||
<label class="form-label">时间范围</label>
|
||
<select id="traj-days">
|
||
<option value="1">最近 1 天</option>
|
||
<option value="2">最近 2 天</option>
|
||
<option value="3" selected>最近 3 天</option>
|
||
<option value="7">最近 7 天</option>
|
||
<option value="14">最近 14 天</option>
|
||
<option value="30">最近 30 天</option>
|
||
</select>
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">选择车辆</label>
|
||
<select id="traj-bike">
|
||
<option value="">全部车辆</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
|
||
<button class="btn btn-primary" onclick="loadTrajectory()" style="width:100%;">
|
||
加载轨迹
|
||
</button>
|
||
|
||
<div id="traj-map" class="map-container">
|
||
<div class="map-placeholder">
|
||
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>
|
||
<span>点击"加载轨迹"查看</span>
|
||
</div>
|
||
</div>
|
||
<div id="traj-hint" style="display:block;font-size:12px;color:#b45309;margin-top:6px;"></div>
|
||
|
||
<div id="traj-time" class="timeline-slider" style="display:none;">
|
||
<input type="range" id="traj-slider" min="0" max="100" value="0" step="1" oninput="onTimelineChange()">
|
||
<div style="display:flex;justify-content:space-between;font-size:11px;color:var(--text-tertiary);margin-top:4px;">
|
||
<span id="traj-time-start">-</span>
|
||
<span id="traj-time-current">-</span>
|
||
<span id="traj-time-end">-</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="tip">
|
||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18h6M10 22h4M12 2a7 7 0 0 1 7 7c0 2.38-1.19 4.47-3 5.74V17a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1v-2.26C6.19 13.47 5 11.38 5 9a7 7 0 0 1 7-7z"/></svg>
|
||
提示:轨迹点按智能间隔采集(白天5-10分钟,深夜30-60分钟)。
|
||
🟢 绿色=可用 🔴 红色=使用中 🟠 橙色=欠压车辆 🟣 紫色=损坏车辆 ⚫ 灰色=低电量
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 分布云图面板 -->
|
||
<div id="panel-heatmap" class="panel" style="display:none;">
|
||
<div class="panel-title">24小时分布云图</div>
|
||
|
||
<button class="btn btn-primary" onclick="loadHeatmap()" style="width:100%;">
|
||
生成云图
|
||
</button>
|
||
|
||
<div id="heat-map" class="map-container" style="height:400px;">
|
||
<div class="map-placeholder">
|
||
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z"/></svg>
|
||
<span>点击"生成云图"查看</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="heat-info" class="stat-value" style="text-align:center;color:var(--text-secondary);font-size:12px;padding:4px 0;"></div>
|
||
|
||
<div class="heat-legend">
|
||
<span>稀疏</span>
|
||
<div class="heat-gradient"></div>
|
||
<span>密集</span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 统计报表面板 -->
|
||
<div id="panel-stats" class="panel" style="display:none;">
|
||
<div class="panel-title">各状态分布</div>
|
||
<div style="display:flex;align-items:center;gap:10px;margin-bottom:6px;">
|
||
<label style="font-size:12px;color:var(--text-tertiary);">统计范围</label>
|
||
<select id="stats-days" onchange="loadStats()" style="font-size:12px;padding:4px 8px;">
|
||
<option value="1" selected>最近 24 小时</option>
|
||
<option value="3">最近 3 天</option>
|
||
<option value="7">最近 7 天</option>
|
||
<option value="14">最近 14 天</option>
|
||
<option value="30">最近 30 天</option>
|
||
</select>
|
||
</div>
|
||
|
||
<!-- 图例 -->
|
||
<div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:8px;font-size:12px;">
|
||
<span style="display:flex;align-items:center;gap:4px;">
|
||
<span style="width:10px;height:10px;border-radius:2px;background:#34c759;"></span>可用
|
||
</span>
|
||
<span style="display:flex;align-items:center;gap:4px;">
|
||
<span style="width:10px;height:10px;border-radius:2px;background:#ff2d55;"></span>使用中
|
||
</span>
|
||
<span style="display:flex;align-items:center;gap:4px;">
|
||
<span style="width:10px;height:10px;border-radius:2px;background:#ff9f0a;"></span>欠压
|
||
</span>
|
||
<span style="display:flex;align-items:center;gap:4px;">
|
||
<span style="width:10px;height:10px;border-radius:2px;background:#5856D6;"></span>损坏
|
||
</span>
|
||
<span style="display:flex;align-items:center;gap:4px;">
|
||
<span style="width:10px;height:10px;border-radius:2px;background:#8e8e93;"></span>低电量
|
||
</span>
|
||
</div>
|
||
|
||
<div id="hourly-chart" class="chart-container" style="height:260px;"></div>
|
||
|
||
<!-- 状态汇总卡片 -->
|
||
<div style="display:grid;grid-template-columns:repeat(5,1fr);gap:8px;margin-top:12px;" id="hourly-summary">
|
||
</div>
|
||
|
||
<div style="margin-top:16px;">
|
||
<div class="panel-title" style="font-size:14px;">使用中排行 Top 10</div>
|
||
<div id="top-bikes" class="bike-list"></div>
|
||
</div>
|
||
|
||
<div style="display:flex;gap:8px;margin-top:16px;">
|
||
<button class="btn btn-primary" onclick="exportHistoryCsv()" style="flex:1;display:inline-flex;align-items:center;justify-content:center;gap:5px;">
|
||
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3v12"/><path d="M7 11l5 5 5-5"/><path d="M4 19h16"/></svg>
|
||
导出轨迹 CSV
|
||
</button>
|
||
<button class="btn btn-secondary" onclick="refreshStats()" style="flex:1;">
|
||
刷新数据
|
||
</button>
|
||
</div>
|
||
<div class="tip" style="margin-top:8px;">导出内容为最近 3 天全部车辆点位;生成的直链 1 小时内有效、免登录,换浏览器也可使用。</div>
|
||
</div>
|
||
|
||
<div class="tip">
|
||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 20V10M12 20V4M6 20v-6"/></svg>
|
||
分析功能会采集并存储车辆位置数据,用于轨迹回放和分布分析。数据按智能间隔自动采集。
|
||
</div>
|
||
</div>
|
||
|
||
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
|
||
<script src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=GzzqszczKmI7RNTclpLtOXZDTT4mq8a6"></script>
|
||
<script src="https://unpkg.com/mapvgl/dist/mapvgl.min.js"></script>
|
||
<!-- 坐标转换库(本地内置,车辆数据 GCJ02 -> 百度 BD09) -->
|
||
<script src="/static/js/coordtransform.js"></script>
|
||
<script>
|
||
// 全局状态
|
||
let map = null;
|
||
let trajMarkers = [];
|
||
let trajPolyline = null;
|
||
let heatmapOverlay = null; // MapVGL heatmapLayer 实例
|
||
let heatmapView = null; // MapVGL View
|
||
let currentTrajData = null;
|
||
let hourlyChart = null;
|
||
let trajMapReady = false; // 轨迹地图是否已初始化
|
||
let heatMapReady = false; // 热力图地图是否已初始化
|
||
let multiBikeFirstPan = true; // 多车模式是否已首次定位
|
||
let bikeMarkerMap = {}; // 多车模式:bike_code -> marker 映射
|
||
let prevPointCoord = null; // 上一个有效的坐标点(用于距离过滤)
|
||
|
||
// 计算两个坐标点之间的距离(米)
|
||
function getDistance(lat1, lng1, lat2, lng2) {
|
||
const R = 6371000; // 地球半径(米)
|
||
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||
Math.sin(dLng/2) * Math.sin(dLng/2);
|
||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
||
return R * c;
|
||
}
|
||
|
||
|
||
|
||
// 手动坐标偏移(仅作为 coordtransform 未加载时的降级常量,与主页面一致)
|
||
const COORD_OFFSET = {
|
||
lat: 0.00603,
|
||
lng: 0.00650,
|
||
};
|
||
|
||
// 坐标转换:车辆/地图数据为 GCJ02,逐点精确转百度 BD09(coordtransform)。
|
||
// coordtransform.gcj02tobd09(lng, lat) -> [bd09_lng, bd09_lat]
|
||
function offsetCoord(lat, lng) {
|
||
lat = parseFloat(lat);
|
||
lng = parseFloat(lng);
|
||
if (typeof coordtransform !== "undefined" && coordtransform.gcj02tobd09) {
|
||
try {
|
||
const bd = coordtransform.gcj02tobd09(lng, lat); // [lng, lat]
|
||
return { lat: bd[1], lng: bd[0] };
|
||
} catch (e) {
|
||
console.warn("[坐标转换] gcj02tobd09 失败,回退手动偏移:", e);
|
||
}
|
||
}
|
||
// 降级:coordtransform 未加载/出错时,沿用旧的手动常量偏移
|
||
return {
|
||
lat: lat + COORD_OFFSET.lat,
|
||
lng: lng + COORD_OFFSET.lng,
|
||
};
|
||
}
|
||
|
||
// API基础URL
|
||
const API_BASE = '';
|
||
|
||
// 轻量 toast(样式与 ui-system.css 对齐)
|
||
let _toastTimer = null;
|
||
function showToast(msg) {
|
||
let el = document.getElementById('toast');
|
||
if (!el) {
|
||
el = document.createElement('div');
|
||
el.id = 'toast';
|
||
el.className = 'toast';
|
||
el.style.cssText = 'position:fixed;left:50%;bottom:32px;transform:translateX(-50%);padding:10px 18px;background:rgba(28,28,30,.92);color:#fff;font-size:13.5px;border-radius:10px;z-index:9999;display:none;box-shadow:0 4px 16px rgba(0,0,0,.2);';
|
||
document.body.appendChild(el);
|
||
}
|
||
el.textContent = msg;
|
||
el.style.display = 'block';
|
||
if (_toastTimer) clearTimeout(_toastTimer);
|
||
_toastTimer = setTimeout(() => { el.style.display = 'none'; }, 2600);
|
||
}
|
||
|
||
// ===== 登录态(BUG-02)=====
|
||
// 本页的 8 个数据分析接口已改成「登录用户才可访问」,所以这里所有请求都必须带
|
||
// Authorization;未登录 / token 失效时给一句确定的话并回主页面登录,而不是让
|
||
// 面板一直停在"加载中"。
|
||
const AUTH_STORAGE_KEY = "auth_token";
|
||
let _authRedirectTimer = null;
|
||
let _statsRefreshTimer = null;
|
||
|
||
function getAuthToken() {
|
||
try { return localStorage.getItem(AUTH_STORAGE_KEY) || ""; } catch (e) { return ""; }
|
||
}
|
||
function authHeaders(extra) {
|
||
const headers = Object.assign({}, extra || {});
|
||
const token = getAuthToken();
|
||
if (token) headers["Authorization"] = "Bearer " + token;
|
||
return headers;
|
||
}
|
||
// 401 判定:HTTP 状态与 body 里的 rtn_code 任一命中都算(后端两者都给)
|
||
function isAuthError(resp, json) {
|
||
return (resp && resp.status === 401) || (json && json.rtn_code === 401);
|
||
}
|
||
function handleAuthRequired(message) {
|
||
if (_authRedirectTimer) return; // 并发请求只跳一次
|
||
if (_statsRefreshTimer) { clearTimeout(_statsRefreshTimer); _statsRefreshTimer = null; }
|
||
showToast(message || "请先在主页面登录");
|
||
_authRedirectTimer = setTimeout(() => { window.location.replace("/"); }, 1800);
|
||
}
|
||
// 未登录时页面不该是空白:一句结论 + 一个回主页的出口,同时自动跳回
|
||
function showLoginGateCard(message) {
|
||
handleAuthRequired(message);
|
||
if (document.getElementById("analysis-auth-gate")) return;
|
||
const gate = document.createElement("div");
|
||
gate.id = "analysis-auth-gate";
|
||
gate.style.cssText = "position:fixed;inset:0;z-index:9998;display:flex;align-items:center;" +
|
||
"justify-content:center;background:rgba(247,247,248,.97);padding:24px;text-align:center;";
|
||
gate.innerHTML = '<div style="max-width:320px">' +
|
||
'<div style="font-size:17px;font-weight:700;margin-bottom:8px">请先在主页面登录</div>' +
|
||
'<div style="font-size:13px;color:#666;line-height:1.7;margin-bottom:18px">' +
|
||
'车辆历史轨迹能还原到具体车辆与时间,只对已登录账号开放。</div>' +
|
||
'<a href="/" style="display:inline-block;padding:12px 22px;border-radius:10px;' +
|
||
'background:#1c1c1f;color:#f8f8f6;font-size:15px;font-weight:600;text-decoration:none">' +
|
||
'去主页面登录</a></div>';
|
||
document.body.appendChild(gate);
|
||
}
|
||
|
||
// 数据导出:生成直链 → UA 检测(与主页面 detectInAppBrowser 同规则)→
|
||
// 内嵌浏览器弹复制提示,普通浏览器直接下载
|
||
function detectInAppBrowserName() {
|
||
const ua = navigator.userAgent || "";
|
||
if (/xbniu-native/i.test(ua)) return "APP";
|
||
if (/MicroMessenger/i.test(ua)) return /OpenHarmony|HarmonyOS|ArkWeb/i.test(ua) ? "鸿蒙微信" : "微信";
|
||
if (/\bQQ\/|QQBrowser/i.test(ua)) return "QQ";
|
||
if (/AlipayClient/i.test(ua)) return "支付宝";
|
||
if (/DingTalk/i.test(ua)) return "钉钉";
|
||
if (/Weibo/i.test(ua)) return "微博";
|
||
if (/aweme|ByteDance/i.test(ua)) return "抖音";
|
||
return null;
|
||
}
|
||
async function exportHistoryCsv() {
|
||
const authToken = getAuthToken();
|
||
if (!authToken) { showLoginGateCard(); return; }
|
||
showToast("正在生成导出链接...");
|
||
try {
|
||
const resp = await fetch(API_BASE + '/api/export/create', {
|
||
method: 'POST',
|
||
headers: authHeaders({ 'Content-Type': 'application/json' }),
|
||
body: JSON.stringify({ type: 'history_csv' })
|
||
});
|
||
const data = await resp.json();
|
||
if (isAuthError(resp, data)) { showLoginGateCard(data.message); return; }
|
||
if (data.rtn_code !== 0) { showToast(data.message || "生成导出链接失败"); return; }
|
||
const url = new URL(data.data.url, window.location.href).href;
|
||
const app = detectInAppBrowserName();
|
||
if (app) {
|
||
await copyToClipboard(url);
|
||
showToast(`${app}内无法直接下载,链接已复制,请到系统浏览器打开(1 小时内有效)`);
|
||
return;
|
||
}
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = '';
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
a.remove();
|
||
showToast('已开始下载(直链 1 小时内有效)');
|
||
} catch (err) {
|
||
showToast('导出失败,请重试');
|
||
}
|
||
}
|
||
async function copyToClipboard(text) {
|
||
try {
|
||
if (navigator.clipboard && window.isSecureContext) {
|
||
await navigator.clipboard.writeText(text);
|
||
return;
|
||
}
|
||
} catch (e) {}
|
||
const input = document.createElement('textarea');
|
||
input.value = text;
|
||
input.style.position = 'fixed';
|
||
input.style.opacity = '0';
|
||
document.body.appendChild(input);
|
||
input.select();
|
||
try { document.execCommand('copy'); } catch (e) {}
|
||
input.remove();
|
||
}
|
||
|
||
// 初始化
|
||
async function init() {
|
||
// 未登录直接给登录门,不发请求(发了也是 401)
|
||
if (!getAuthToken()) { showLoginGateCard(); return; }
|
||
await loadStats();
|
||
await loadBikeList();
|
||
_statsRefreshTimer = setTimeout(loadStats, 5000); // 5秒后刷新一次
|
||
}
|
||
|
||
// 加载统计
|
||
async function loadStats() {
|
||
const errEl = document.getElementById('stats-error');
|
||
if (errEl) { errEl.style.display = 'none'; }
|
||
try {
|
||
const statsDays = (document.getElementById('stats-days') || {}).value || 1;
|
||
const resp = await fetch(API_BASE + '/api/history/stats?days=' + statsDays,
|
||
{ headers: authHeaders() });
|
||
const json = await resp.json();
|
||
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
|
||
if (json.rtn_code === 0) {
|
||
const d = json.data;
|
||
|
||
document.getElementById('stat-bikes').textContent = d.total.bike_count || 0;
|
||
document.getElementById('stat-points').textContent = `共 ${d.total.total_points || 0} 个数据点`;
|
||
|
||
if (d.total.earliest) {
|
||
document.getElementById('stat-range').textContent = '已采集';
|
||
document.getElementById('stat-sub-range').textContent =
|
||
new Date(d.total.earliest).toLocaleDateString() + ' 起';
|
||
}
|
||
|
||
if (d.total.latest) {
|
||
const latest = new Date(d.total.latest);
|
||
document.getElementById('stat-latest').textContent =
|
||
latest.toLocaleTimeString('zh-CN', {hour:'2-digit', minute:'2-digit'});
|
||
}
|
||
|
||
// 状态分布(与 map.html 图例对齐)
|
||
const stateMap = {
|
||
available: '可用',
|
||
used: '使用中',
|
||
locked: '欠压',
|
||
reserved: '损坏',
|
||
low: '低电量'
|
||
};
|
||
const statusEl = document.getElementById('stat-avail');
|
||
const statusSub = document.getElementById('stat-status');
|
||
const availCount = d.status_distribution['available'] || 0;
|
||
statusEl.textContent = availCount;
|
||
statusSub.innerHTML = Object.entries(d.status_distribution)
|
||
.map(([k, v]) => `<span class="status-badge state-${k}">${stateMap[k]||k}:${v}</span>`)
|
||
.join(' ');
|
||
|
||
// 时段分布图(days>1 时按天分桶)
|
||
renderHourlyChart(d.hourly_distribution, d.hourly_avg, d.days || 1);
|
||
|
||
// Top车辆
|
||
renderTopBikes(d.top_bikes);
|
||
} else {
|
||
// 非 0 返回(含限速/上游失败):明确告知,不再静默停在"等待加载..."
|
||
if (errEl) {
|
||
errEl.textContent = json.message
|
||
? `加载失败:${json.message}(点击重试)`
|
||
: '加载失败,请稍后重试(点击重试)';
|
||
errEl.style.display = 'block';
|
||
errEl.onclick = loadStats;
|
||
}
|
||
console.error('加载统计失败:', json);
|
||
}
|
||
} catch (e) {
|
||
console.error('加载统计失败:', e);
|
||
if (errEl) {
|
||
errEl.textContent = '网络错误,请检查连接后点击重试';
|
||
errEl.style.display = 'block';
|
||
errEl.onclick = loadStats;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 加载车辆列表
|
||
async function loadBikeList() {
|
||
try {
|
||
const resp = await fetch(API_BASE + '/api/history/bikes', { headers: authHeaders() });
|
||
const json = await resp.json();
|
||
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
|
||
if (json.rtn_code === 0) {
|
||
const bikes = (json.data && json.data.bikes) || [];
|
||
const options = ['<option value="">全部车辆</option>'];
|
||
bikes.forEach(b => {
|
||
options.push(`<option value="${b.bike_code}">${b.bike_code} (${b.point_count}点)</option>`);
|
||
});
|
||
document.getElementById('traj-bike').innerHTML = options.join('');
|
||
}
|
||
} catch (e) {
|
||
console.error('加载车辆列表失败:', e);
|
||
}
|
||
}
|
||
|
||
// 渲染小时图表(堆叠柱状图)
|
||
function renderHourlyChart(data, avgData, days = 1) {
|
||
if (!hourlyChart) {
|
||
hourlyChart = echarts.init(document.getElementById('hourly-chart'));
|
||
}
|
||
|
||
// days<=1:按小时 24 桶("08:00");days>1:按天 days 桶("今天/昨天/N天前")
|
||
const multiDay = Number(days) > 1;
|
||
const n = multiDay ? Number(days) : 24;
|
||
const buckets = [];
|
||
for (let i = 0; i < n; i++) {
|
||
if (multiDay) {
|
||
buckets.push(i === 0 ? "今天" : (i === 1 ? "昨天" : `${i}天前`));
|
||
} else {
|
||
buckets.push(`${String(i).padStart(2, '0')}:00`);
|
||
}
|
||
}
|
||
const keyOf = multiDay
|
||
? (i) => String(i)
|
||
: (i) => `${String(i).padStart(2, '0')}`;
|
||
|
||
// 提取各状态数据
|
||
const states = ['available', 'used', 'locked', 'reserved', 'low'];
|
||
const stateData = {};
|
||
const stateColors = {
|
||
available: '#34c759',
|
||
used: '#ff2d55',
|
||
locked: '#ff9f0a',
|
||
reserved: '#5856D6',
|
||
low: '#8e8e93'
|
||
};
|
||
|
||
states.forEach(state => {
|
||
stateData[state] = [];
|
||
for (let i = 0; i < n; i++) {
|
||
stateData[state].push(data[keyOf(i)]?.[state] || 0);
|
||
}
|
||
});
|
||
|
||
// 更新状态汇总(使用24小时平均数据)
|
||
const summaryEl = document.getElementById('hourly-summary');
|
||
const stateNames = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量' };
|
||
summaryEl.innerHTML = states.map(state => {
|
||
const avg = avgData?.[state] || 0;
|
||
return `
|
||
<div style="background:var(--bg-secondary);border-radius:8px;padding:8px;text-align:center;">
|
||
<div style="font-size:16px;font-weight:700;color:${stateColors[state]};">${avg}</div>
|
||
<div style="font-size:10px;color:var(--text-tertiary);">${stateNames[state]}</div>
|
||
</div>
|
||
`;
|
||
}).join('');
|
||
|
||
const option = {
|
||
tooltip: {
|
||
trigger: 'axis',
|
||
axisPointer: { type: 'shadow' },
|
||
formatter: function(params) {
|
||
let result = params[0].name + '<br/>';
|
||
let total = 0;
|
||
params.forEach(p => {
|
||
if (p.value > 0) {
|
||
const names = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量' };
|
||
result += `<span style="display:inline-block;margin-right:4px;border-radius:2px;width:10px;height:10px;background:${p.color};"></span>${names[p.seriesName]}: ${p.value}<br/>`;
|
||
total += p.value;
|
||
}
|
||
});
|
||
result += `<b>合计: ${total}</b>`;
|
||
return result;
|
||
}
|
||
},
|
||
legend: {
|
||
show: false // 图例已在HTML中显示
|
||
},
|
||
grid: {
|
||
left: '3%',
|
||
right: '4%',
|
||
bottom: '3%',
|
||
top: '8%',
|
||
containLabel: true
|
||
},
|
||
xAxis: {
|
||
type: 'category',
|
||
data: buckets,
|
||
axisLabel: {
|
||
fontSize: 9,
|
||
interval: 2,
|
||
color: getComputedStyle(document.documentElement).getPropertyValue('--text-tertiary') || '#86868b'
|
||
},
|
||
axisLine: { lineStyle: { color: '#e5e5ea' } },
|
||
axisTick: { show: false }
|
||
},
|
||
yAxis: {
|
||
type: 'value',
|
||
axisLabel: { fontSize: 10, color: '#86868b' },
|
||
axisLine: { show: false },
|
||
axisTick: { show: false },
|
||
splitLine: { lineStyle: { color: '#f5f5f7', type: 'dashed' } }
|
||
},
|
||
series: states.map(state => ({
|
||
name: state,
|
||
type: 'bar',
|
||
stack: 'total',
|
||
data: stateData[state],
|
||
itemStyle: {
|
||
color: stateColors[state],
|
||
borderRadius: state === 'available' ? [4, 4, 0, 0] : [0, 0, 0, 0]
|
||
},
|
||
emphasis: {
|
||
itemStyle: {
|
||
opacity: 0.8
|
||
}
|
||
},
|
||
barWidth: '35%'
|
||
}))
|
||
};
|
||
|
||
hourlyChart.setOption(option);
|
||
|
||
// 响应窗口变化
|
||
window.addEventListener('resize', () => {
|
||
if (hourlyChart) hourlyChart.resize();
|
||
});
|
||
}
|
||
|
||
// 渲染Top车辆
|
||
function renderTopBikes(bikes) {
|
||
const container = document.getElementById('top-bikes');
|
||
if (!bikes || bikes.length === 0) {
|
||
container.innerHTML = '<div class="tip">暂无数据</div>';
|
||
return;
|
||
}
|
||
container.innerHTML = bikes.map(b => `
|
||
<div class="bike-item" onclick="selectTopBike('${b.bike_code}')">
|
||
<div>
|
||
<div class="bike-code">#${b.bike_code}</div>
|
||
<div class="bike-meta">使用中 ${b.point_count} 次</div>
|
||
</div>
|
||
<span class="status-badge status-1">查看轨迹</span>
|
||
</div>
|
||
`).join('');
|
||
}
|
||
|
||
function selectTopBike(code) {
|
||
document.getElementById('traj-bike').value = code;
|
||
switchTab('trajectory');
|
||
loadTrajectory();
|
||
}
|
||
|
||
// Tab切换
|
||
function switchTab(tab) {
|
||
document.querySelectorAll('.tab-btn').forEach((btn, i) => {
|
||
btn.classList.toggle('active',
|
||
(tab === 'trajectory' && i === 0) ||
|
||
(tab === 'heatmap' && i === 1) ||
|
||
(tab === 'stats' && i === 2)
|
||
);
|
||
});
|
||
document.getElementById('panel-trajectory').style.display = tab === 'trajectory' ? 'block' : 'none';
|
||
document.getElementById('panel-heatmap').style.display = tab === 'heatmap' ? 'block' : 'none';
|
||
document.getElementById('panel-stats').style.display = tab === 'stats' ? 'block' : 'none';
|
||
|
||
if (tab === 'stats') {
|
||
refreshStats();
|
||
// 图表容器显示后需要手动触发 resize
|
||
setTimeout(() => { if (hourlyChart) hourlyChart.resize(); }, 100);
|
||
}
|
||
// 轨迹和热力图只在地图未初始化时加载,已初始化则直接显示已有地图
|
||
if (tab === 'trajectory' && !trajMapReady) {
|
||
loadTrajectory();
|
||
}
|
||
if (tab === 'heatmap' && !heatMapReady) {
|
||
loadHeatmap();
|
||
}
|
||
}
|
||
|
||
// 刷新统计
|
||
async function refreshStats() {
|
||
await loadStats();
|
||
}
|
||
|
||
// 加载轨迹
|
||
async function loadTrajectory() {
|
||
const days = document.getElementById('traj-days').value;
|
||
const bikeCode = document.getElementById('traj-bike').value;
|
||
|
||
const mapEl = document.getElementById('traj-map');
|
||
// 只在地图从未初始化时清容器并显示loading,后续只清覆盖物不重建地图
|
||
if (!trajMapReady) {
|
||
mapEl.innerHTML = '<div class="loading"><div class="spinner"></div>加载中...</div>';
|
||
}
|
||
|
||
try {
|
||
const url = bikeCode
|
||
? `${API_BASE}/api/history/trajectory?bike_code=${bikeCode}&days=${days}`
|
||
: `${API_BASE}/api/history/all_trajectory?days=${days}`;
|
||
const resp = await fetch(url, { headers: authHeaders() });
|
||
const json = await resp.json();
|
||
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
|
||
|
||
if (json.rtn_code === 0) {
|
||
currentTrajData = json.data;
|
||
renderTrajectory(json.data);
|
||
// 截断提示:窗口内点位超上限被截断时明确告知,不静默少画
|
||
// (上限由后端 HISTORY_ALL_TRAJECTORY_LIMIT 给出,前端不再硬编码数字)
|
||
const hint = document.getElementById('traj-hint');
|
||
if (hint) {
|
||
const cap = bikeCode ? '3000' : String(json.data.limit || 60000);
|
||
hint.textContent = json.data.truncated
|
||
? `⚠ 点位较多,仅绘制了前 ${cap} 条,其余已省略(可缩小时间范围查看完整轨迹)`
|
||
: '';
|
||
}
|
||
} else {
|
||
if (!trajMapReady) {
|
||
mapEl.innerHTML = '<div class="map-placeholder"><span>加载失败: ' + json.message + '</span></div>';
|
||
}
|
||
}
|
||
} catch (e) {
|
||
if (!trajMapReady) {
|
||
mapEl.innerHTML = '<div class="map-placeholder"><span>网络错误</span></div>';
|
||
}
|
||
}
|
||
}
|
||
|
||
// 渲染轨迹(地图只初始化一次,快速加载)
|
||
function renderTrajectory(data) {
|
||
if (!trajMapReady) {
|
||
// 首次初始化地图(延迟确保容器渲染完成)
|
||
setTimeout(() => {
|
||
initBaiduMap('traj-map');
|
||
// 等地图创建完成后再渲染数据
|
||
setTimeout(() => {
|
||
trajMapReady = true;
|
||
doRenderTrajectoryData(data);
|
||
}, 300);
|
||
}, 50);
|
||
return;
|
||
}
|
||
// 地图已就绪,直接渲染数据
|
||
doRenderTrajectoryData(data);
|
||
}
|
||
|
||
// 实际渲染轨迹数据(地图已就绪后调用)
|
||
// 保存轨迹数据供时间条使用
|
||
let trajectoryData = null;
|
||
let currentTrajMarkers = []; // 当前显示的高亮点
|
||
let cachedAllPts = []; // 多车模式:预排序的合并点数组(只排一次)
|
||
let cachedBikePts = {}; // 多车模式:每辆车的排序后点数组(只排一次)
|
||
let prevIdx = -1; // 上一次时间轴索引(用于差量更新)
|
||
|
||
// 根据 state + electric 决定颜色,与 map.html 完全一致
|
||
function getBikeColor(p) {
|
||
const state = p.state != null ? p.state : (p.status ?? 1);
|
||
const electric = p.electric != null ? p.electric : 100;
|
||
if (state === 10 || electric < 20) return '#8e8e93'; // 低电量 灰
|
||
if (state === 4) return '#ff9f0a'; // 欠压 橙
|
||
if (state === 2) return '#5856D6'; // 损坏 紫
|
||
if (state === 1 && p.status === 1) return '#ff2d55'; // 使用中 红
|
||
return '#34c759'; // 可用 绿
|
||
}
|
||
|
||
function doRenderTrajectoryData(data) {
|
||
// 清除旧数据
|
||
currentTrajMarkers.forEach(m => map.removeOverlay(m));
|
||
currentTrajMarkers = [];
|
||
bikeMarkerMap = {}; // 清除多车 marker 映射
|
||
prevPointCoord = null; // 重置上一个坐标
|
||
if (trajPolyline) map.removeOverlay(trajPolyline);
|
||
trajPolyline = null;
|
||
prevIdx = -1; // 重置帧索引
|
||
cachedAllPts = []; // 清缓存
|
||
cachedBikePts = {}; // 清缓存
|
||
|
||
const allPoints = []; // 用于调整视野
|
||
trajectoryData = data; // 保存数据
|
||
|
||
if (data.trajectories) {
|
||
// 多辆车模式:预排序所有点(只排一次,后续复用)
|
||
const bikeCodes = Object.keys(data.trajectories);
|
||
|
||
// 对每辆车单独排序并缓存
|
||
bikeCodes.forEach(code => {
|
||
const pts = [...data.trajectories[code]].sort((a, b) =>
|
||
new Date(a.time) - new Date(b.time)
|
||
);
|
||
cachedBikePts[code] = pts;
|
||
});
|
||
|
||
// 合并所有点用于时间轴滑动
|
||
bikeCodes.forEach(code => {
|
||
cachedBikePts[code].forEach(p => {
|
||
const c = offsetCoord(p.lat, p.lng);
|
||
cachedAllPts.push({...p, bike_code: code, c});
|
||
});
|
||
});
|
||
cachedAllPts.sort((a, b) => new Date(a.time) - new Date(b.time));
|
||
|
||
// 添加所有点到视野
|
||
cachedAllPts.forEach(p => {
|
||
allPoints.push(new BMapGL.Point(p.c.lng, p.c.lat));
|
||
});
|
||
|
||
// 显示时间条
|
||
document.getElementById('traj-time').style.display = 'block';
|
||
document.getElementById('traj-slider').max = cachedAllPts.length - 1;
|
||
document.getElementById('traj-slider').value = 0;
|
||
document.getElementById('traj-time-start').textContent = cachedAllPts[0]?.time || '-';
|
||
document.getElementById('traj-time-end').textContent = cachedAllPts[cachedAllPts.length - 1]?.time || '-';
|
||
|
||
} else if (data.points) {
|
||
// 单辆车模式:只显示线
|
||
const points = [];
|
||
let lastCoord = null;
|
||
data.points.forEach(p => {
|
||
const c = offsetCoord(p.latitude, p.longitude);
|
||
// 跳过位置没变化的点
|
||
if (lastCoord && c.lat === lastCoord.lat && c.lng === lastCoord.lng) return;
|
||
lastCoord = c;
|
||
|
||
points.push(new BMapGL.Point(c.lng, c.lat));
|
||
allPoints.push(points[points.length - 1]);
|
||
});
|
||
|
||
if (points.length > 1) {
|
||
trajPolyline = new BMapGL.Polyline(points, {
|
||
strokeColor: '#0071e3',
|
||
strokeWeight: 2,
|
||
strokeOpacity: 0.8
|
||
});
|
||
map.addOverlay(trajPolyline);
|
||
}
|
||
|
||
// 显示时间轴
|
||
document.getElementById('traj-time').style.display = 'block';
|
||
document.getElementById('traj-slider').max = points.length - 1;
|
||
document.getElementById('traj-slider').value = 0;
|
||
document.getElementById('traj-time-start').textContent = data.points?.[0]?.recorded_at || '-';
|
||
document.getElementById('traj-time-end').textContent = data.points?.[data.points.length - 1]?.recorded_at || '-';
|
||
}
|
||
|
||
// 单辆车模式调整视野;多辆车模式只在首次加载时定位中心点
|
||
if (allPoints.length > 0) {
|
||
if (!data.trajectories) {
|
||
// 单辆车:调整到全部点
|
||
map.setViewport(allPoints, {margins: [50, 50, 50, 50]});
|
||
} else if (multiBikeFirstPan) {
|
||
// 多车首次:定位到中心点
|
||
map.setViewport(allPoints, {margins: [50, 50, 50, 50]});
|
||
multiBikeFirstPan = false;
|
||
}
|
||
}
|
||
|
||
onTimelineChange();
|
||
}
|
||
|
||
// 时间轴变化 - 多车模式用差量更新,只动位置变化 >5m 的车
|
||
function onTimelineChange() {
|
||
const idx = parseInt(document.getElementById('traj-slider').value);
|
||
|
||
// 必须等数据和缓存都就绪
|
||
if (!trajectoryData) return;
|
||
if (trajectoryData.trajectories && cachedAllPts.length === 0) return;
|
||
|
||
if (trajectoryData.points) {
|
||
// 单辆车模式:距离过滤 + 复用 marker
|
||
const filteredPoints = [];
|
||
let lastCoord = null;
|
||
trajectoryData.points.forEach(p => {
|
||
const c = offsetCoord(p.latitude, p.longitude);
|
||
// 跳过位置完全相同的点
|
||
if (lastCoord && c.lat === lastCoord.lat && c.lng === lastCoord.lng) return;
|
||
// 跳过距离 <5m 的点
|
||
if (lastCoord) {
|
||
const dist = getDistance(lastCoord.lat, lastCoord.lng, c.lat, c.lng);
|
||
if (dist < 5) return;
|
||
}
|
||
lastCoord = c;
|
||
filteredPoints.push({...p, c});
|
||
});
|
||
|
||
const point = filteredPoints[idx];
|
||
if (!point) return;
|
||
|
||
const c = point.c;
|
||
const color = getBikeColor(point);
|
||
const bikeCode = trajectoryData.bike_code || point.bike_code || '';
|
||
|
||
if (currentTrajMarkers.length === 0) {
|
||
// 首次:创建带标签的 marker
|
||
const marker = createTrajMarker(c.lat, c.lng, color, bikeCode);
|
||
map.addOverlay(marker);
|
||
currentTrajMarkers.push(marker);
|
||
map.panTo(marker.getPosition());
|
||
} else {
|
||
// 后续:检查距离,距离 <5m 不移动
|
||
const marker = currentTrajMarkers[0];
|
||
if (prevPointCoord) {
|
||
const dist = getDistance(prevPointCoord.lat, prevPointCoord.lng, c.lat, c.lng);
|
||
if (dist >= 5) {
|
||
marker.setPosition(new BMapGL.Point(c.lng, c.lat));
|
||
updateMarkerLabel(marker, bikeCode);
|
||
}
|
||
}
|
||
prevPointCoord = c;
|
||
marker.setIcon(createTrajIcon(color));
|
||
marker.setTop(true);
|
||
}
|
||
|
||
document.getElementById('traj-time-current').textContent = point.recorded_at || '-';
|
||
|
||
} else if (trajectoryData.trajectories) {
|
||
const bikeCodes = Object.keys(cachedBikePts);
|
||
const colors = ['#0071e3', '#34c759', '#ff9500', '#ff3b30', '#5856d6', '#af52de'];
|
||
|
||
if (prevIdx < 0) {
|
||
// 首次加载:创建所有 marker,对齐到当前滑块时间
|
||
const currentTime = cachedAllPts[Math.min(idx, cachedAllPts.length - 1)]?.time || '';
|
||
bikeCodes.forEach((code, bikeIdx) => {
|
||
const pts = cachedBikePts[code];
|
||
if (!pts || pts.length === 0) return;
|
||
let targetPt = null;
|
||
for (let i = pts.length - 1; i >= 0; i--) {
|
||
if (pts[i].time <= currentTime) {
|
||
targetPt = pts[i];
|
||
break;
|
||
}
|
||
}
|
||
if (!targetPt) return;
|
||
const c = offsetCoord(targetPt.lat, targetPt.lng);
|
||
const color = colors[bikeIdx % colors.length];
|
||
const marker = createTrajMarker(c.lat, c.lng, color, code);
|
||
map.addOverlay(marker);
|
||
bikeMarkerMap[code] = marker;
|
||
marker._lastCoord = c;
|
||
marker._lastColor = color;
|
||
currentTrajMarkers.push(marker);
|
||
});
|
||
prevIdx = idx;
|
||
} else {
|
||
// 后续:与单车模式一致的手感,直接取当前索引的点
|
||
const pt = cachedAllPts[Math.min(idx, cachedAllPts.length - 1)];
|
||
if (!pt) return;
|
||
const currentTime = pt.time;
|
||
const bikeCode = pt.bike_code;
|
||
|
||
const marker = bikeMarkerMap[bikeCode];
|
||
if (!marker) return;
|
||
|
||
const c = offsetCoord(pt.lat, pt.lng);
|
||
|
||
// <5m 不移动
|
||
const prevC = marker._lastCoord;
|
||
if (prevC) {
|
||
const dist = getDistance(prevC.lat, prevC.lng, c.lat, c.lng);
|
||
if (dist >= 5) {
|
||
marker.setPosition(new BMapGL.Point(c.lng, c.lat));
|
||
updateMarkerLabel(marker, bikeCode);
|
||
}
|
||
}
|
||
marker._lastCoord = c;
|
||
|
||
// 只在颜色变化时更新图标
|
||
const color = getBikeColor(pt);
|
||
if (marker._lastColor !== color) {
|
||
marker.setIcon(createTrajIcon(color));
|
||
marker._lastColor = color;
|
||
}
|
||
marker.setTop(true);
|
||
|
||
document.getElementById('traj-time-current').textContent = currentTime || '-';
|
||
}
|
||
}
|
||
}
|
||
|
||
// 加载热力图(服务端聚合网格数据,客户端直接渲染,地图只初始化一次)
|
||
async function loadHeatmap() {
|
||
const mapEl = document.getElementById('heat-map');
|
||
// 只在地图从未初始化时显示loading
|
||
if (!heatMapReady) {
|
||
mapEl.innerHTML = '<div class="loading"><div class="spinner"></div>聚合数据中...</div>';
|
||
}
|
||
|
||
try {
|
||
const resp = await fetch(`${API_BASE}/api/history/heatmap`, { headers: authHeaders() });
|
||
const json = await resp.json();
|
||
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
|
||
|
||
if (json.rtn_code === 0) {
|
||
if (!heatMapReady) {
|
||
const b = json.data.bounds;
|
||
if (b) {
|
||
// 传原始 GCJ02 中心,由 initBaiduMap 内部统一转 BD09。
|
||
// 此处在传入前先转了一次 → doInitMap 里再转一次,中心偏出约600m。
|
||
initBaiduMap('heat-map', true,
|
||
(b.min_lng + b.max_lng) / 2,
|
||
(b.min_lat + b.max_lat) / 2);
|
||
} else {
|
||
initBaiduMap('heat-map', true);
|
||
}
|
||
heatMapReady = true;
|
||
renderServerHeatmap(json.data);
|
||
} else {
|
||
renderServerHeatmap(json.data);
|
||
}
|
||
} else {
|
||
if (!heatMapReady) {
|
||
mapEl.innerHTML = '<div class="map-placeholder"><span>加载失败</span></div>';
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.error('[热力图] 请求失败:', e);
|
||
if (!heatMapReady) {
|
||
mapEl.innerHTML = '<div class="map-placeholder"><span>网络错误</span></div>';
|
||
}
|
||
}
|
||
}
|
||
|
||
// 渲染服务端聚合后的热力图数据
|
||
function renderServerHeatmap(data) {
|
||
if (!window.heatMap || !heatmapView) return;
|
||
|
||
const points = data.points || [];
|
||
const maxCount = data.max_count || 1;
|
||
|
||
// 清除旧热力图层
|
||
if (heatmapOverlay) {
|
||
heatmapView.removeLayer(heatmapOverlay);
|
||
heatmapOverlay = null;
|
||
}
|
||
|
||
if (points.length === 0) {
|
||
return;
|
||
}
|
||
|
||
// 转换为 MapVGL 格式(带 count 作为强度权重,加 GPS 偏移)
|
||
const mapvData = points.map(p => {
|
||
const c = offsetCoord(p.lat, p.lng);
|
||
return {
|
||
geometry: { type: 'Point', coordinates: [c.lng, c.lat] },
|
||
count: p.count // 网格内落点数量作为热力强度
|
||
};
|
||
});
|
||
|
||
// 创建热力图层
|
||
const layer = new mapvgl.HeatmapLayer({
|
||
size: 40, // 网格半径(米)
|
||
max: maxCount, // 最大强度(来自服务端)
|
||
height: 0, // 平面热力图
|
||
unit: 'm',
|
||
gradient: {
|
||
0.0: 'rgba(0, 78, 255, 0)',
|
||
0.2: 'rgba(0, 156, 255, 0.5)',
|
||
0.4: 'rgba(0, 255, 255, 0.7)',
|
||
0.6: 'rgba(0, 255, 0, 0.85)',
|
||
0.8: 'rgba(255, 255, 0, 1)',
|
||
1.0: 'rgba(255, 50, 0, 1)'
|
||
}
|
||
});
|
||
layer.setData(mapvData);
|
||
heatmapView.addLayer(layer);
|
||
heatmapOverlay = layer;
|
||
|
||
// 更新信息
|
||
document.getElementById('heat-info').textContent =
|
||
`共 ${data.grid_count} 个网格, ${data.total_points} 个历史位置`;
|
||
}
|
||
|
||
// 启动
|
||
init();
|
||
|
||
// ========== 百度地图相关 ==========
|
||
function initBaiduMap(containerId, isHeatmap = false, initLng, initLat) {
|
||
function waitForBMap(retries = 30) {
|
||
if (typeof BMapGL !== 'undefined') {
|
||
doInitMap(containerId, isHeatmap, initLng, initLat);
|
||
} else if (retries > 0) {
|
||
console.log(`等待百度地图GL API... (${retries})`);
|
||
setTimeout(() => waitForBMap(retries - 1), 500);
|
||
} else {
|
||
console.error("百度地图GL API加载失败");
|
||
}
|
||
}
|
||
waitForBMap();
|
||
}
|
||
|
||
function doInitMap(containerId, isHeatmap, initLng, initLat) {
|
||
// 初始化前清掉 loading overlay,避免遮挡地图
|
||
const el = document.getElementById(containerId);
|
||
const loading = el ? el.querySelector('.loading') : null;
|
||
if (loading) loading.remove();
|
||
|
||
const mapInstance = new BMapGL.Map(containerId);
|
||
// 默认中心点(山东管理学院,与后端 /api/config 的 center_lat/lng 一致;
|
||
// 此前的 36.67,117.12 不是本校区坐标,无数据时会落到错误城市的空白区)
|
||
const c = initLng !== undefined && initLat !== undefined
|
||
? offsetCoord(initLat, initLng)
|
||
: offsetCoord(36.531820, 116.780180);
|
||
mapInstance.centerAndZoom(new BMapGL.Point(c.lng, c.lat), 17);
|
||
mapInstance.enableScrollWheelZoom(true);
|
||
mapInstance.addControl(new BMapGL.NavigationControl());
|
||
mapInstance.addControl(new BMapGL.ScaleControl());
|
||
// 显式开启拖动(避免某些情况下被覆盖)
|
||
mapInstance.enableDragging();
|
||
|
||
if (isHeatmap) {
|
||
window.heatMap = mapInstance;
|
||
// 初始化 MapVGL View
|
||
heatmapView = new mapvgl.View({ map: mapInstance });
|
||
} else {
|
||
map = mapInstance;
|
||
}
|
||
}
|
||
|
||
// 创建轨迹点标记图标(可复用)
|
||
function createTrajIcon(color) {
|
||
const size = 24;
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = size;
|
||
canvas.height = size;
|
||
const ctx = canvas.getContext("2d");
|
||
const r = size / 2 - 2;
|
||
|
||
ctx.beginPath();
|
||
ctx.arc(size/2, size/2, r, 0, Math.PI * 2);
|
||
ctx.fillStyle = color;
|
||
ctx.fill();
|
||
ctx.beginPath();
|
||
ctx.arc(size/2, size/2, r * 0.5, 0, Math.PI * 2);
|
||
ctx.fillStyle = '#fff';
|
||
ctx.fill();
|
||
|
||
return new BMapGL.Icon(
|
||
canvas.toDataURL(),
|
||
new BMapGL.Size(size, size),
|
||
new BMapGL.Size(size/2, size/2)
|
||
);
|
||
}
|
||
|
||
// 创建带标签的轨迹点标记
|
||
function createTrajMarker(lat, lng, color, bikeCode) {
|
||
const icon = createTrajIcon(color);
|
||
const marker = new BMapGL.Marker(new BMapGL.Point(lng, lat), { icon });
|
||
marker.setTop(true);
|
||
|
||
// 创建 Label
|
||
const label = new BMapGL.Label(bikeCode || '', {
|
||
offset: new BMapGL.Size(-30, -35),
|
||
enableMassClear: false
|
||
});
|
||
label.setStyle({
|
||
background: 'rgba(0,0,0,0.75)',
|
||
color: '#fff',
|
||
padding: '4px 8px',
|
||
borderRadius: '4px',
|
||
fontSize: '12px',
|
||
fontWeight: '500',
|
||
whiteSpace: 'nowrap',
|
||
border: 'none',
|
||
boxShadow: '0 2px 8px rgba(0,0,0,0.3)'
|
||
});
|
||
marker.setLabel(label);
|
||
label.hide(); // 默认隐藏,点击时显示
|
||
|
||
// 用自定义属性跟踪 label 显示状态
|
||
marker._labelVisible = false;
|
||
|
||
// 点击显示/隐藏标签
|
||
marker.addEventListener('click', () => {
|
||
marker._labelVisible = !marker._labelVisible;
|
||
if (marker._labelVisible) {
|
||
label.show();
|
||
} else {
|
||
label.hide();
|
||
}
|
||
});
|
||
|
||
return marker;
|
||
}
|
||
|
||
// 更新 marker 标签文字
|
||
function updateMarkerLabel(marker, bikeCode) {
|
||
const label = marker.getLabel();
|
||
if (label) {
|
||
label.setContent(bikeCode || '');
|
||
}
|
||
}
|
||
</script>
|
||
</body>
|
||
</html>
|