Files
xbcr/src-ts/map/core.ts
T
zzy 8ece55983a feat(前端): TypeScript 重写版(esbuild IIFE 产物,暂不接管线上)
- 新增 src-ts/(22 个 .ts / 7792 行):按 core / map / card / order / nav / share /
  subscribe / ui / compat 分层,types 里有 BMapGL 与 API 响应声明
- compat/globals.ts 是唯一挂 window 的地方(292 个),覆盖模板 139 处内联事件
- esbuild 产出 static/dist/app.js(226.6 KiB,IIFE,es2019)+ README(构建/切换/回滚)
- 构建可复现:node esbuild.config.mjs、node --check、npx tsc --noEmit 均通过
- .gitignore 增加 node_modules/ 与 static/dist/*.map(sourcemap 可重生成,不入库)
- 暂不改 templates/map.html 与 MAP_ASSETS:等独立核对通过再切换,回滚=换回四个 script
2026-11-16 10:44:11 +08:00

502 lines
19 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 { showBikeDetail } from "../card/bike-card";
import { friendlyError } from "../core/format";
import { calcDistance, offsetCoord } from "../core/geo";
import { getBikeState, preloadBaseIcons } from "./icons";
import { renderMap, setupClusterListener } from "./markers";
import { bindNavMapEvents } from "../nav/navigation";
import { showToast } from "../ui/modals";
import { showLoginGate } from "../ui/settings";
// static/js/map.js:26-29
const BAIDU_AK = "GzzqszczKmI7RNTclpLtOXZDTT4mq8a6";
// ========== 图标缓存(性能优化)==========
// 缓存: key = "电量|颜色|是否高亮" → BMapGL.Icon
// static/js/map.js:129-129
const INIT_OFFSET_EXTRA = 0.00027; // 约30米(向北)
// static/js/map.js:130-140
const INIT_OFFSET_EAST = 0.003; // 约300米(向东)
// 坐标转换:车辆/地图数据为 GCJ02,逐点精确转百度 BD09(coordtransform,无在线转换上限)。
// coordtransform.gcj02tobd09(lng, lat) -> [bd09_lng, bd09_lat]
// 状态判断函数 - 基于 state + status 组合判断
// state=1 + status=0: 空闲可用
// state=1 + status=1: 使用中(被占用)
// state=10: 低电量车辆
// state=4: 欠压车辆
// state=2: 损坏车辆
// static/js/map.js:473-473
let mapInitializationStarted: any = false;
// static/js/map.js:474-492
export function initMap() {
// 等待 BMapGL 对象加载完成
function waitForBMap(retries = 30) {
if (mapInitializationStarted) return;
if (typeof BMapGL !== 'undefined' && typeof BMapGL.Map === 'function') {
mapInitializationStarted = true;
initMapCore();
} else if (retries > 0) {
console.log(`等待百度地图GL API加载... (${retries})`);
setTimeout(() => waitForBMap(retries - 1), 500);
} else {
console.error("百度地图GL API加载失败");
showToast("地图API加载失败,请检查网络后刷新");
}
}
waitForBMap();
}
// ========== 登录认证 ==========
// static/js/map.js:2965-3003
export function initMapCore() {
// 预加载基础图标(在请求地图数据之前就开始)
preloadBaseIcons();
fetch("/api/config")
.then(r => r.json())
.then(cfg => {
document.getElementById("school-name").textContent = cfg.school_name || "山东管理学院";
// 初始位置:整体偏移 + 额外上移30米 + 东移200米
const c = offsetCoord(cfg.center_lat, cfg.center_lng);
c.lat += INIT_OFFSET_EXTRA;
c.lng += INIT_OFFSET_EAST;
// 初始化百度地图 GL
S.map = new BMapGL.Map("baidu_map");
// 地图实例刚建好:立刻把导航模块的拖动监听绑上(浏览器里唯一可靠的时机,
// 之前 navigation.js 只靠 setTimeout(0),那时 map 还是 null,监听从未生效)
try { if (typeof bindNavMapEvents === "function") bindNavMapEvents(); } catch (e) {}
S.map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17);
S.map.enableScrollWheelZoom(true);
S.map.enableDragging(true);
S.map.enableInertialDragging(true);
// 不加 NavigationControl:它带出的左上角方向键/缩放滑杆(以及其中的“定位失败”钮)
// 业务里用不到,双指缩放与拖拽手势不依赖该控件。
S.map.addControl(new BMapGL.ScaleControl());
updateMapStyle();
loadMapData(S.currentType);
// 启动自动持续定位(地图加载后立即开始)
startAutoLocation();
})
.catch(err => {
console.error("初始化失败:", err);
showToast("地图初始化失败,请刷新重试");
});
}
// ========== 深色模式适配 ==========
// static/js/map.js:3004-3021
export function updateMapStyle() {
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (isDark) {
// Only filter the basemap canvas; native DOM overlays retain their colours.
const mapEl = document.getElementById("baidu_map");
mapEl.style.filter = "";
mapEl.style.setProperty("--basemap-filter", "invert(90%) hue-rotate(180deg) brightness(95%) contrast(90%)");
mapEl.style.background = "#1c1c1e";
} else {
// 浅色模式 - 移除滤镜
const mapEl = document.getElementById("baidu_map");
mapEl.style.filter = "";
mapEl.style.setProperty("--basemap-filter", "none");
mapEl.style.background = "";
}
}
// 监听系统颜色变化
// static/js/map.js:3027-3027
let mapRequest: any = null;
// static/js/map.js:3028-3028
export let mapRefreshTimer: any = null;
// static/js/map.js:3029-3029
let renderedMapSnapshot: any = null;
// static/js/map.js:3030-3030
let mapRefreshFailed: any = false;
// static/js/map.js:3032-3043
export function scheduleMapRefresh(snapshot, serverTime, retrySeconds = 5) {
clearTimeout(mapRefreshTimer);
const expires = Number(snapshot?.expires_at);
const delay = Number.isFinite(expires) && Number.isFinite(serverTime)
? Math.max(500, (expires - serverTime) * 1000 + 150)
: Math.max(1000, retrySeconds * 1000);
mapRefreshTimer = setTimeout(() => {
if (S.authToken && S.map && document.visibilityState === "visible") {
loadMapData(S.currentType, false, true);
}
}, Math.min(delay, 60000));
}
// static/js/map.js:3045-3096
export function loadMapData(type, showLoading = true, quiet = false) {
if (!S.authToken) { showLoginGate(); return Promise.resolve(); }
if (!S.map) return Promise.resolve();
if (mapRequest && mapRequest.type === String(type)) return mapRequest.promise;
const requestToken = S.authToken;
const loading = document.getElementById("loading");
if (S.isFirstLoad && showLoading) loading.classList.remove("hidden");
const pending = { type: String(type), promise: null };
mapRequest = pending;
pending.promise = fetch(`/api/map?type=${encodeURIComponent(type)}`, {
headers: { "Authorization": `Bearer ${requestToken}` },
cache: "no-store"
})
.then(async response => {
const result = await response.json();
const stamp = response.headers.get("X-Map-Server-Time");
const serverTime = stamp !== null ? Number(stamp) : Date.now() / 1000;
return { result, serverTime };
})
.then(({ result, serverTime }) => {
if (S.authToken !== requestToken || String(type) !== String(S.currentType)) return;
loading.classList.add("hidden");
if (result.rtn_code === 401) { showLoginGate(); return; }
scheduleMapRefresh(result.map_snapshot, serverTime, result.retry_after || 5);
if (result.rtn_code !== 0) {
mapRefreshFailed = true;
updateMapFreshnessBadge();
if (!quiet) showToast(result.message || "车辆数据更新失败,正在自动重试");
return;
}
renderMap([result], !S.isFirstLoad);
S.isFirstLoad = false;
mapRefreshFailed = false;
if (result.map_snapshot) {
renderedMapSnapshot = { ...result.map_snapshot, serverTime, receivedAt: performance.now() };
updateMapFreshnessBadge();
} else updateTime();
if (S.map) setupClusterListener();
})
.catch(err => {
if (S.authToken !== requestToken || String(type) !== String(S.currentType)) return;
loading.classList.add("hidden");
mapRefreshFailed = true;
updateMapFreshnessBadge();
scheduleMapRefresh(null, null);
if (!quiet) showToast("加载失败: " + friendlyError(err));
})
.finally(() => { if (mapRequest === pending) mapRequest = null; });
return pending.promise;
}
// ========== 手动刷新 ==========
// static/js/map.js:3097-3104
export function refreshMap() {
const btn = document.getElementById("refresh-btn");
btn.classList.add("spinning");
loadMapData(S.currentType, false);
setTimeout(() => btn.classList.remove("spinning"), 1000);
}
// ========== 渲染地图(坐标归一化 + 增量气泡图层)==========
// static/js/map.js:4305-4309
export function mapSnapshotNow() {
return renderedMapSnapshot
? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1000
: Date.now() / 1000;
}
// static/js/map.js:4311-4327
export function updateMapFreshnessBadge() {
const el = document.getElementById("update-time");
if (!el) return;
const stamp = Number(renderedMapSnapshot?.fetched_at);
if (renderedMapSnapshot && Number.isFinite(stamp) && renderedMapSnapshot.fetched_at !== null) {
el.textContent = new Date(stamp * 1000).toLocaleTimeString('zh-CN', {
timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit'
});
const expired = mapSnapshotNow() >= Number(renderedMapSnapshot.expires_at);
el.classList.toggle("stale", expired || mapRefreshFailed);
} else if (mapRefreshFailed) {
el.textContent = "更新失败";
el.classList.add("stale");
}
el.onclick = showFreshnessDetail;
el.style.cursor = "pointer";
}
// static/js/map.js:4329-4344
export function updateTime() {
if (renderedMapSnapshot) { updateMapFreshnessBadge(); return; }
// Compatibility for a server without snapshot metadata; never show client time.
fetch(`/api/map/freshness?type=${encodeURIComponent(S.currentType)}`, { cache: "no-store" })
.then(r => r.json())
.then(result => {
if (result.rtn_code !== 0 || !result.data?.latest) return;
const el = document.getElementById("update-time");
if (!el) return;
el.textContent = String(result.data.latest).slice(11, 16);
el.classList.toggle("stale", result.data.status === "stale" || result.data.stale_seconds >= 60);
el.onclick = showFreshnessDetail;
el.style.cursor = "pointer";
})
.catch(() => {});
}
// static/js/map.js:4346-4355
export function showFreshnessDetail() {
if (renderedMapSnapshot && renderedMapSnapshot.fetched_at !== null) {
const seconds = Math.max(0, Math.floor(mapSnapshotNow() - renderedMapSnapshot.fetched_at));
const when = new Date(renderedMapSnapshot.fetched_at * 1000).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai' });
const age = seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`;
showToast(`车辆数据更新于 ${when}(${age})${mapRefreshFailed ? ',更新暂时失败,正在自动重试' : ''}`);
return;
}
showToast(mapRefreshFailed ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据");
}
// static/js/map.js:4630-4640
export function locateMe() {
if (!navigator.geolocation) {
showToast("您的浏览器不支持定位");
return;
}
// 启动自动持续定位(页面启动时调用一次即可)
startAutoLocation();
}
// 手动找最近的车(基于当前自动定位的位置)
// static/js/map.js:4641-4651
export function findNearestBikeManual() {
if (!S.autoLocationMarker) {
showToast("请先开启定位");
return;
}
const point = S.autoLocationMarker.getPosition();
findNearestBike(point);
}
// 显示我的位置(手动定位模式,带 panTo)
// static/js/map.js:4652-4677
export function showMyLocation(point) {
if (S.myLocationMarker) {
S.map.removeOverlay(S.myLocationMarker);
}
// 蓝色脉冲点
const size = 24;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2);
ctx.fillStyle = "#007AFF";
ctx.fill();
ctx.beginPath();
ctx.arc(size/2, size/2, 6, 0, Math.PI * 2);
ctx.fillStyle = "white";
ctx.fill();
const icon = new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(size, size), new BMapGL.Size(size/2, size/2));
S.myLocationMarker = new BMapGL.Marker(point, { icon });
S.map.addOverlay(S.myLocationMarker);
S.map.panTo(point);
}
// 绘制自动定位标记(带外圈脉冲效果,灰色调)
// static/js/map.js:4678-4708
export function createAutoLocationIcon() {
const size = 28;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
// 外圈(浅蓝色,脉冲感)
ctx.beginPath();
ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2);
ctx.strokeStyle = "rgba(0, 122, 255, 0.3)";
ctx.lineWidth = 3;
ctx.stroke();
// 中圈
ctx.beginPath();
ctx.arc(size/2, size/2, 8, 0, Math.PI * 2);
ctx.strokeStyle = "rgba(0, 122, 255, 0.6)";
ctx.lineWidth = 2;
ctx.stroke();
// 中心点
ctx.beginPath();
ctx.arc(size/2, size/2, 4, 0, Math.PI * 2);
ctx.fillStyle = "#007AFF";
ctx.fill();
return canvas.toDataURL("image/png");
}
// 更新自动定位标记位置(不 panTo)
// static/js/map.js:4709-4722
export function updateAutoLocation(point) {
if (!S.autoLocationMarker) {
// 首次创建
const iconUrl = createAutoLocationIcon();
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
S.autoLocationMarker = new BMapGL.Marker(point, { icon });
S.map.addOverlay(S.autoLocationMarker);
} else {
// 更新位置
S.autoLocationMarker.setPosition(point);
}
}
// 启动自动持续定位
// static/js/map.js:4723-4776
export function startAutoLocation() {
if (!navigator.geolocation) {
console.log("[自动定位] 浏览器不支持定位");
return;
}
// 如果已经在监听,先停止
if (S.autoLocationWatchId !== null) {
navigator.geolocation.clearWatch(S.autoLocationWatchId);
}
showToast("正在获取您的位置...");
S.autoLocationWatchId = navigator.geolocation.watchPosition(
(pos) => {
const gpsLat = pos.coords.latitude;
const gpsLng = pos.coords.longitude;
// GPS(WGS84) -> 百度 BD09,本地用 coordtransform 同步转换,
// 替代原 BMapGL.Convertor 在线接口(无网络/异步依赖)。
// coordtransform.wgs84tobd09(lng, lat) 返回 [bd09_lng, bd09_lat]
let myPoint = null;
if (typeof coordtransform !== "undefined" && coordtransform.wgs84tobd09) {
try {
const bd09 = coordtransform.wgs84tobd09(gpsLng, gpsLat);
myPoint = new BMapGL.Point(bd09[0], bd09[1]);
} catch (e) {
console.warn("[自动定位] 坐标转换失败,使用原始坐标:", e);
myPoint = null;
}
}
// 库未加载或转换失败时,直接使用原始坐标兜底
if (!myPoint) {
myPoint = new BMapGL.Point(gpsLng, gpsLat);
}
updateAutoLocation(myPoint);
S.hasLocationPermission = true;
// 用户授权定位时:本页首次拿到位置后,把地图居中到用户位置(仅一次)
if (!S.initialLocationCentered) {
S.initialLocationCentered = true;
if (S.map) {
S.map.setCenter(myPoint);
}
}
},
(err) => {
console.log("[自动定位] 定位失败:", err.message);
S.hasLocationPermission = false;
},
{ enableHighAccuracy: false, maximumAge: 5000, timeout: 10000 }
);
}
// 停止自动定位
// static/js/map.js:4777-4788
export function stopAutoLocation() {
if (S.autoLocationWatchId !== null) {
navigator.geolocation.clearWatch(S.autoLocationWatchId);
S.autoLocationWatchId = null;
}
if (S.autoLocationMarker) {
S.map.removeOverlay(S.autoLocationMarker);
S.autoLocationMarker = null;
}
}
// 计算距离并找最近可用车辆(智能电量匹配)
// static/js/map.js:4789-4851
export function findNearestBike(myPoint) {
// Haversine公式计算两点距离(米)
const myLat = myPoint.lat;
const myLng = myPoint.lng;
const NEARBY_THRESHOLD = 200; // 附近范围(米)
const LOW_BATTERY = 20; // 低电量阈值
// 收集所有可用车(电量>20%,非使用中)
const available = [];
for (const id in S.markersData) {
const bike = S.markersData[id];
if (!bike.latitude || !bike.longitude) continue;
// 只把「空闲可用」的车推荐给用户:分类规则与 getBikeState / 后端一致
// (使用中 state=1&status=1 / 低电量 state=10 或 电量<20 / 欠压 4 / 损坏 2)
const bs = getBikeState(bike);
if (bs !== 'available') continue;
const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0);
if (electric <= LOW_BATTERY) continue; // 过滤低电量
const c = offsetCoord(bike.latitude, bike.longitude);
const dist = calcDistance(myLat, myLng, c.lat, c.lng);
available.push({ id, bike, dist, electric });
}
// 过滤:只选电量 > 40% 的车
const enoughElec = available.filter(v => v.electric > 40);
if (enoughElec.length === 0) {
showToast("附近没有电量足够的车辆(需要>40%)");
return;
}
// 直接选距离最近的
enoughElec.sort((a, b) => a.dist - b.dist);
const selected = enoughElec[0];
const matchType = "最近可用";
S.nearestBikeId = selected.id;
const bike = selected.bike;
const c = offsetCoord(bike.latitude, bike.longitude);
const bikePoint = new BMapGL.Point(c.lng, c.lat);
// 飞到这个车并放大一级
S.map.panTo(bikePoint);
setTimeout(() => {
S.map.setZoom(S.map.getZoom() + 1);
}, 300);
// 文案与 getBikeState 的分类一一对应(推荐出来的车一定是 available,正常走「空闲」)
const stateLabel = {
inuse: "使用中", available: "空闲", lowbattery: "低电量",
locked: "欠压车辆", reserved: "损坏车辆", unknown: "未知",
}[getBikeState(bike)] || "未知";
const distText = selected.dist < 1000 ? `${Math.round(selected.dist)}米` : `${(selected.dist/1000).toFixed(1)}公里`;
showToast(`${matchType}:#${bike.code}(${stateLabel} ${selected.electric}%),${distText}`);
setTimeout(() => showBikeDetail(selected.id), 500);
}
// ========== 启动 ==========
// 启动时检查登录状态,然后检查租车