Files
xbcr/src-ts/nav/walk-route.ts
T
zzy 44efe5f4f4 feat(前端): 切换到 TypeScript 构建产物(dist/app.js),JS 版保留可回滚
切换
- templates/map.html:四个 script(navigation/share/subscribe/map.js)
  → 一行 /static/dist/app.js;geo.js 保留(bundle 内同一份实现,幂等)
- routes/map_api.py 的 MAP_ASSETS 同步换成 dist/app.js,缓存戳跟着产物走

随切换修的
- walk-route:onSearchComplete 里 res.getStatus() 加存在性判断
  (起点≈终点时上游返回空壳,原 JS 版与 TS 版都会抛未捕获 TypeError),两版同步修
- compat/globals.ts 末尾挂 window.S = S:原版 91 个顶层 let/var 是全局词法绑定,
  bundle 里收进 state 对象,至少把 state 暴露出来便于排障
- tests/test_map_assets.py 断言改为 dist/app.js
- tests/test_history_30d.py:子进程加 import os + XBCR_DISABLE_BACKGROUND=1
  (原来采集线程会往临时库写 bike_history,导致统计断言偶发失败)
- app.py 支持 XBCR_DISABLE_BACKGROUND=1:只初始化数据库、不起后台线程(测试/工具用)
- tests/test_rounds_and_preview.py:remaining_seconds 允许 2 秒误差(跨秒抖动)

回滚
- 把 map.html 那行换回四个 script、MAP_ASSETS 换回四个文件名即可;
  static/js/ 一字未改,dist 留着也不会被加载

验证:167 pytest(连跑 3 次)+ 32 node 全绿;浏览器实测(390px,真实数据)
车 498、卡片 #51143 / 步行 488 米、导航条「前方 170 米 右转」、共享/订阅面板可开、
JS 异常 0
2026-11-16 11:14:59 +08:00

123 lines
5.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
import { S } from "../core/state";
import { calcDistance, offsetCoord } from "../core/geo";
// static/js/navigation.js:6-8
const _walkRouteCache = new Map(); // `${code}|${我的坐标}` -> {d, t}
// 超过这个直线距离就不显示「距离/步行」——太远的车走过去没有意义,
// 而且会让百度步行规划白白消耗配额。直线估算与精算共用同一个阈值。
// static/js/navigation.js:9-9
export const MAX_WALK_DISTANCE_M = 20000;
// static/js/navigation.js:11-17
export function parseWalkDistance(text) {
const s = String(text || "");
const km = s.match(/([\d.]+)\s*公里/);
if (km) return Math.round(parseFloat(km[1]) * 1000);
const m = s.match(/([\d.]+)\s*米/);
return m ? Math.round(parseFloat(m[1])) : 0;
}
// static/js/navigation.js:19-27
export function parseWalkDuration(text) {
const s = String(text || "");
let sec = 0;
const h = s.match(/([\d.]+)\s*小时/);
const min = s.match(/([\d.]+)\s*分钟/);
if (h) sec += Math.round(parseFloat(h[1]) * 3600);
if (min) sec += Math.round(parseFloat(min[1]) * 60);
return sec;
}
// static/js/navigation.js:29-110
export async function refineWalkRoute(bike) {
const bikeCode = String((bike && bike.code) || "");
if (!bikeCode) return;
const me = (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker)
? S.autoLocationMarker.getPosition() : null;
if (!me || !bike.latitude || !bike.longitude) return;
// 太远就整块不显示(与直线估算口径一致,别让精算把隐藏的行又显示回来)
const c0 = offsetCoord(bike.latitude, bike.longitude);
if (calcDistance(me.lat, me.lng, c0.lat, c0.lng) > MAX_WALK_DISTANCE_M) return;
const key = bikeCode + "|" + me.lat.toFixed(4) + "," + me.lng.toFixed(4);
const apply = (distanceM, seconds) => {
if (!S.selectedBike || String(S.selectedBike.code) !== bikeCode) return; // 已换车
const distEl = document.getElementById("card-distance");
const walkEl = document.getElementById("card-walk");
const metaLeft = document.getElementById("card-meta-left");
if (!distEl || !walkEl || !metaLeft) return;
distEl.textContent = distanceM < 1000
? `步行 ${Math.round(distanceM)} 米`
: `步行 ${(distanceM / 1000).toFixed(1)} 公里`;
walkEl.textContent = `约 ${Math.max(1, Math.round(seconds / 60))} 分钟`;
metaLeft.hidden = false;
};
const cached = _walkRouteCache.get(key);
if (cached) { apply(cached.d, cached.t); return; }
// ① 后端(百度 Web 服务 API,需服务端 AK + SK,结果服务端缓存 7 天)
try {
const gcj = (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02)
? coordtransform.bd09togcj02(me.lng, me.lat) : null;
if (gcj) {
const url = "/api/walk_route?origin_lat=" + gcj[1] + "&origin_lng=" + gcj[0]
+ "&dest_lat=" + bike.latitude + "&dest_lng=" + bike.longitude;
const resp = await fetch(url, {
headers: { "Authorization": "Bearer " + S.authToken }
});
const data = await resp.json();
const d = data && data.data;
if (data.rtn_code === 0 && d && d.distance > 0 && d.duration > 0
&& (d.source === "baidu" || d.source === "cache")) {
_walkRouteCache.set(key, { d: d.distance, t: d.duration });
apply(d.distance, d.duration);
return;
}
}
} catch (e) { /* 忽略,走 SDK */ }
// ② 浏览器端 JS API 步行规划(现成浏览器 AK,返回 "1.6公里"/"23分钟" 字符串)
try {
if (typeof BMapGL !== "undefined" && BMapGL.WalkingRoute && S.map) {
const plan = await new Promise<any>(resolve => {
let done = false;
const finish = v => { if (!done) { done = true; resolve(v); } };
const walk = new BMapGL.WalkingRoute(S.map, {
renderOptions: { map: null, panel: null },
onSearchComplete: res => {
// 退化路线(起点≈终点)时 res 可能是空壳、没有 getStatus,
// 直接调用会抛未捕获 TypeError(与原 JS 版同步修复)
let status = -1;
try {
status = (res && typeof (res as any).getStatus === "function")
? (res as any).getStatus() : -1;
} catch (e) { status = -1; }
if (status !== 0) return finish(null);
try {
const p = res.getPlan(0);
const d = parseWalkDistance(p.getDistance());
const t = parseWalkDuration(p.getDuration());
finish(d > 0 && t > 0 ? { d: d, t: t } : null);
} catch (err) { finish(null); }
}
});
walk.search(me, new BMapGL.Point(bike.longitude, bike.latitude));
setTimeout(() => finish(null), 8000);
});
if (plan) {
_walkRouteCache.set(key, plan);
apply(plan.d, plan.t);
}
}
} catch (e) { /* 保留直线估算 */ }
}
// ========== 跟随式导航 ==========
// 状态:null = 未导航;对象存在 = 导航中
// { ptsGcj, ptsBD, idx, walking, follow, timer, watchId, destCode, distance, duration }