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
This commit is contained in:
@@ -0,0 +1,501 @@
|
||||
/* 由 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);
|
||||
}
|
||||
|
||||
// ========== 启动 ==========
|
||||
// 启动时检查登录状态,然后检查租车
|
||||
@@ -0,0 +1,280 @@
|
||||
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||
// static/js/map.js:30-30
|
||||
const iconCache = new Map();
|
||||
|
||||
// static/js/map.js:31-34
|
||||
const ICON_CACHE_MAX = 500; // 最多缓存500个不同图标
|
||||
|
||||
// ========== 预创建完整图标(首次加载优化)==========
|
||||
// 预创建各电量和颜色的完整图标(避免首次加载时大量 Canvas 绘制)
|
||||
|
||||
// static/js/map.js:35-43
|
||||
const BASE_ICON_COLORS = {
|
||||
available: "#34C759", // 绿色-可用
|
||||
inuse: "#FF2D55", // 红色-使用中
|
||||
locked: "#FF9F0A", // 橙色-欠压
|
||||
reserved: "#5856D6", // 紫色-损坏
|
||||
lowbattery: "#8E8E93" // 灰色-低电量
|
||||
};
|
||||
|
||||
// 预创建非高亮状态的完整图标(电量档位 0, 20, 40, 60, 80, 100)
|
||||
|
||||
// static/js/map.js:44-44
|
||||
const prebuiltIcons = new Map(); // key: "电量档位|颜色", value: BMapGL.Icon
|
||||
|
||||
// static/js/map.js:46-101
|
||||
export function createFullIcon(size, color, electric, isHighlighted, bikeCode) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size;
|
||||
canvas.height = size;
|
||||
const ctx = canvas.getContext("2d");
|
||||
const r = size / 2 - (isHighlighted ? 12 : 8);
|
||||
const lineWidth = isHighlighted ? 16 : 12;
|
||||
const centerX = size / 2;
|
||||
const centerY = size / 2;
|
||||
|
||||
// 高亮时加阴影
|
||||
if (isHighlighted) {
|
||||
ctx.shadowColor = color;
|
||||
ctx.shadowBlur = 48;
|
||||
}
|
||||
|
||||
// 白色背景
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||
ctx.fillStyle = "white";
|
||||
ctx.fill();
|
||||
|
||||
// 边框
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||
ctx.strokeStyle = isHighlighted ? color : "rgba(200,200,200,0.5)";
|
||||
ctx.lineWidth = isHighlighted ? 16 : lineWidth;
|
||||
ctx.stroke();
|
||||
ctx.shadowBlur = 0;
|
||||
|
||||
// 使用中:实心圆环
|
||||
if (isHighlighted) {
|
||||
// 高亮时只显示车牌号,没有进度环
|
||||
} else {
|
||||
// 非高亮:绘制电量进度环
|
||||
const startAngle = -Math.PI / 2;
|
||||
const endAngle = startAngle + (Math.PI * 2 * electric / 100);
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, r, startAngle, endAngle);
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = lineWidth;
|
||||
ctx.lineCap = "round";
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// 绘制数字
|
||||
ctx.fillStyle = "#333";
|
||||
ctx.font = isHighlighted ? "bold 60px Arial" : "bold 44px Arial";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(isHighlighted ? (bikeCode + "") : (Math.round(electric) + ""), centerX, centerY);
|
||||
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
// 预初始化完整图标(在地图加载前调用)
|
||||
|
||||
// static/js/map.js:102-121
|
||||
export function preloadBaseIcons() {
|
||||
const displaySize = 36;
|
||||
const imageSize = displaySize * 4; // 高清4倍
|
||||
const electricLevels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; // 21个电量档位(5%分度)
|
||||
|
||||
Object.values<any>(BASE_ICON_COLORS).forEach(color => {
|
||||
// 非高亮状态:每个电量档位创建一个
|
||||
electricLevels.forEach(electric => {
|
||||
const key = `${electric}|${color}`;
|
||||
if (!prebuiltIcons.has(key)) {
|
||||
// 存储 data URL 而不是 Icon 对象
|
||||
const dataUrl = createFullIcon(imageSize, color, electric, false, null);
|
||||
prebuiltIcons.set(key, dataUrl);
|
||||
}
|
||||
});
|
||||
});
|
||||
console.log("[预创建] 已预创建 " + prebuiltIcons.size + " 个图标");
|
||||
}
|
||||
|
||||
// ========== 用车计时 ==========
|
||||
|
||||
// static/js/map.js:141-158
|
||||
export function getBikeState(bike) {
|
||||
const state = bike.state;
|
||||
const status = bike.status;
|
||||
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||||
// 使用中:被占用
|
||||
if (state === 1 && status === 1) return 'inuse';
|
||||
// 低电量:state=10 或电量<20(与后端 _classify_bike_state 同序)
|
||||
if (state === 10 || electric < 20) return 'lowbattery';
|
||||
// 空闲可用
|
||||
if (state === 1) return 'available';
|
||||
// 欠压车辆
|
||||
if (state === 4) return 'locked';
|
||||
// 损坏车辆
|
||||
if (state === 2) return 'reserved';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
// ========== 电池绘制 ==========
|
||||
|
||||
// static/js/map.js:171-222
|
||||
export function makeIconDataURI(color, percent, isInUse, size = 36) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size;
|
||||
canvas.height = size;
|
||||
const ctx = canvas.getContext("2d");
|
||||
const r = size / 2 - 2;
|
||||
const lineWidth = 3;
|
||||
const centerX = size / 2;
|
||||
const centerY = size / 2;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, r - lineWidth, 0, Math.PI * 2);
|
||||
ctx.fillStyle = "rgba(255,255,255,0.9)";
|
||||
ctx.fill();
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||
ctx.strokeStyle = "rgba(200,200,200,0.5)";
|
||||
ctx.lineWidth = lineWidth;
|
||||
ctx.stroke();
|
||||
|
||||
if (isInUse) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = lineWidth;
|
||||
ctx.stroke();
|
||||
} else {
|
||||
const startAngle = -Math.PI / 2;
|
||||
const endAngle = startAngle + (Math.PI * 2 * percent / 100);
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, r, startAngle, endAngle);
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = lineWidth;
|
||||
ctx.lineCap = "round";
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
ctx.fillStyle = "#333";
|
||||
ctx.font = `bold ${size < 36 ? 10 : 11}px Arial`;
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(Math.round(percent) + "", centerX, centerY);
|
||||
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
// ========== 车辆类型(编号规则,按实车号段)==========
|
||||
// - 编号超过 5 位(如 30000193 / 30000033,共 8 位):新引进红色外观车 → 红车
|
||||
// - 5 位编号取「前三位号段」:511 及以上=大车,510 及以下=小车
|
||||
// (实测号段:503/504/505/510=小车,511/512/513=大车)
|
||||
// 红车电量球统一用柔和砖红(不用"使用中"那种血红 #FF2D55,避免视觉惊扰)
|
||||
|
||||
// static/js/map.js:223-223
|
||||
const RED_BIKE_COLOR = "#B4615A"; // 柔和砖红
|
||||
|
||||
// static/js/map.js:225-239
|
||||
export function getBikeKind(bike) {
|
||||
const digits = String((bike && bike.code) || "").replace(/\D/g, "");
|
||||
if (digits.length > 5) {
|
||||
return { key: "red", label: "红车", color: RED_BIKE_COLOR };
|
||||
}
|
||||
const num = parseInt(digits, 10);
|
||||
if (!isFinite(num)) {
|
||||
return { key: "small", label: "小车", color: null };
|
||||
}
|
||||
// 5 位取前三位号段;不足 5 位直接用编号本身比较
|
||||
const series = digits.length >= 5 ? Math.floor(num / Math.pow(10, digits.length - 3)) : num;
|
||||
return series >= 511
|
||||
? { key: "big", label: "大车", color: null }
|
||||
: { key: "small", label: "小车", color: null };
|
||||
}
|
||||
|
||||
// static/js/map.js:241-321
|
||||
export function getBikeIcon(bike, isHighlighted = false) {
|
||||
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||||
const bikeState = getBikeState(bike);
|
||||
// 车辆类型只影响弹起卡片上的标注,地图电量球保持原有「按状态配色」
|
||||
|
||||
let color = "#34C759"; // 默认绿色-可用
|
||||
if (bikeState === 'inuse') {
|
||||
color = "#FF2D55"; // 红色-使用中
|
||||
} else if (bikeState === 'locked') {
|
||||
color = "#FF9F0A"; // 橙色-欠压车辆
|
||||
} else if (bikeState === 'reserved') {
|
||||
color = "#5856D6"; // 紫色-损坏车辆
|
||||
} else if (bikeState === 'lowbattery' || electric < 20) {
|
||||
color = "#8E8E93"; // 灰色-低电量
|
||||
}
|
||||
|
||||
// 生成缓存 key
|
||||
const electricLevel = Math.floor(electric / 5) * 5;
|
||||
const cacheKey = isHighlighted
|
||||
? `${electricLevel}|${color}|1|${bike.code}`
|
||||
: `${electricLevel}|${color}|0`;
|
||||
|
||||
// 检查缓存
|
||||
if (iconCache.has(cacheKey)) {
|
||||
return iconCache.get(cacheKey);
|
||||
}
|
||||
|
||||
const renderSize = isHighlighted ? 192 : 144; // 内部渲染尺寸
|
||||
const displaySize = isHighlighted ? 48 : 36; // 显示尺寸不变
|
||||
|
||||
// 非高亮模式:尝试使用预创建的图标
|
||||
if (!isHighlighted && prebuiltIcons.size > 0) {
|
||||
// 找到最接近的电量档位
|
||||
const levels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
|
||||
let closestLevel = levels[0];
|
||||
let minDiff = Math.abs(electric - closestLevel);
|
||||
for (const lvl of levels) {
|
||||
const diff = Math.abs(electric - lvl);
|
||||
if (diff < minDiff) {
|
||||
minDiff = diff;
|
||||
closestLevel = lvl;
|
||||
}
|
||||
}
|
||||
const prebuiltKey = `${closestLevel}|${color}`;
|
||||
if (prebuiltIcons.has(prebuiltKey)) {
|
||||
// 找到预创建的 data URL,直接创建 Icon
|
||||
const dataUrl = prebuiltIcons.get(prebuiltKey);
|
||||
const icon = new BMapGL.Icon(
|
||||
dataUrl,
|
||||
new BMapGL.Size(displaySize, displaySize),
|
||||
new BMapGL.Size(displaySize / 2, displaySize / 2)
|
||||
);
|
||||
icon.__xbniuAppearance = { url: dataUrl, size: displaySize };
|
||||
iconCache.set(cacheKey, icon);
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有预创建的图标,或者需要高亮状态:直接创建完整图标
|
||||
// imageSize 用于渲染高清内容,displaySize 控制显示大小
|
||||
const imageSize = renderSize * 4; // 高清4倍
|
||||
const dataUrl = createFullIcon(imageSize, color, electric, isHighlighted, bike.code);
|
||||
const icon = new BMapGL.Icon(
|
||||
dataUrl,
|
||||
new BMapGL.Size(displaySize, displaySize),
|
||||
new BMapGL.Size(displaySize / 2, displaySize / 2)
|
||||
);
|
||||
icon.__xbniuAppearance = { url: dataUrl, size: displaySize };
|
||||
|
||||
// 缓存图标
|
||||
if (iconCache.size >= ICON_CACHE_MAX) {
|
||||
const keysToDelete = Array.from(iconCache.keys()).slice(0, Math.floor(ICON_CACHE_MAX * 0.2));
|
||||
keysToDelete.forEach(k => iconCache.delete(k));
|
||||
}
|
||||
iconCache.set(cacheKey, icon);
|
||||
|
||||
return icon;
|
||||
}
|
||||
|
||||
// ========== 高亮相关 ==========
|
||||
// 稳健查找 marker:优先用索引,索引 miss(如批量渲染未完成/刷新过程中)时按 __animId 或标题扫描 currentMarkers 兜底
|
||||
@@ -0,0 +1,333 @@
|
||||
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||
|
||||
import { S } from "../core/state";
|
||||
import { showBikeDetail } from "../card/bike-card";
|
||||
import { offsetCoord } from "../core/geo";
|
||||
import { createAutoLocationIcon } from "./core";
|
||||
import { getBikeIcon, getBikeState } from "./icons";
|
||||
// static/js/map.js:322-341
|
||||
export function findMarkerById(id) {
|
||||
const key = String(id);
|
||||
if (S.currentMarkersById && S.currentMarkersById[id]) return S.currentMarkersById[id];
|
||||
if (Array.isArray(S.currentMarkers)) {
|
||||
for (let i = S.currentMarkers.length - 1; i >= 0; i--) {
|
||||
const m = S.currentMarkers[i];
|
||||
if (m && m.__animId !== undefined && String(m.__animId) === key) return m;
|
||||
}
|
||||
for (let i = S.currentMarkers.length - 1; i >= 0; i--) {
|
||||
const m = S.currentMarkers[i];
|
||||
if (m && m.getTitle) {
|
||||
const t = String(m.getTitle()).replace(/^#/, "");
|
||||
if (t === key) return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 让指定 marker 显示在最上层(放大高亮图标避免被其它普通 marker 遮住)
|
||||
|
||||
// static/js/map.js:342-353
|
||||
export function bringMarkerToTop(marker) {
|
||||
if (marker && marker.bringToTop) { marker.bringToTop(); return; }
|
||||
if (marker && typeof S.map !== 'undefined' && S.map && typeof S.map.removeOverlay === 'function' && typeof S.map.addOverlay === 'function') {
|
||||
try {
|
||||
const markerId = marker.__animId;
|
||||
S.map.removeOverlay(marker);
|
||||
S.map.addOverlay(marker);
|
||||
// removeOverlay/addOverlay 可能重建 marker 的 DOM,重绑一次原生 touch 兜底,避免点按失效
|
||||
if (markerId !== undefined) bindMarkerDomTouch(marker);
|
||||
} catch (e) { /* 忽略:个别情况下不允许重排 */ }
|
||||
}
|
||||
}
|
||||
|
||||
// static/js/map.js:355-379
|
||||
export function setHighlight(id) {
|
||||
// 清除之前的高亮
|
||||
if (S.highlightedBikeId !== null) {
|
||||
const prevMarker = findMarkerById(S.highlightedBikeId);
|
||||
const prevBike = S.markersData[S.highlightedBikeId];
|
||||
if (prevMarker && prevBike) {
|
||||
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[setHighlight] 还原图标失败", e); }
|
||||
}
|
||||
}
|
||||
|
||||
// 设置新高亮
|
||||
S.highlightedBikeId = id;
|
||||
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(id);
|
||||
if (id === null || id === undefined) return;
|
||||
const marker = findMarkerById(id);
|
||||
const bike = S.markersData[id] || S.markersData[String(id)] || S.markersData[Number(id)];
|
||||
if (marker && bike) {
|
||||
try {
|
||||
marker.setIcon(getBikeIcon(bike, true));
|
||||
bringMarkerToTop(marker);
|
||||
} catch (e) { console.warn("[setHighlight] 放大高亮失败", e); }
|
||||
} else {
|
||||
console.warn("[setHighlight] 未找到 marker 或 bike, id=", id);
|
||||
}
|
||||
}
|
||||
|
||||
// static/js/map.js:381-399
|
||||
export function clearHighlight() {
|
||||
if (S.highlightedBikeId !== null) {
|
||||
const prevMarker = findMarkerById(S.highlightedBikeId);
|
||||
const prevBike = S.markersData[S.highlightedBikeId];
|
||||
if (prevMarker && prevBike) {
|
||||
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[clearHighlight] 还原图标失败", e); }
|
||||
}
|
||||
}
|
||||
S.highlightedBikeId = null;
|
||||
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(null);
|
||||
}
|
||||
|
||||
// ========== Marker 点按绑定(统一入口)==========
|
||||
// 背景:BMapGL 在拖动地图后会把紧接的一次对 marker 的 click 吞掉(当作拖拽延续),
|
||||
// 导致“点了点但模态框弹不出”。因此这里不用单一 click,而是额外用
|
||||
// mousedown/mouseup 与原生 touch 的“按下→抬起无位移”判定作为自控点击路径。
|
||||
|
||||
// 把原生 touch 兜底绑到 marker 的当前 DOM 元素上(幂等,可被重复调用,
|
||||
// 用于 domElement 延迟就绪或 removeOverlay/addOverlay 重建 DOM 之后补绑)。
|
||||
|
||||
// static/js/map.js:400-422
|
||||
export function bindMarkerDomTouch(marker) {
|
||||
const tap = marker && marker.__xbniuTap;
|
||||
if (!tap) return;
|
||||
const el = marker.domElement;
|
||||
if (!el) return;
|
||||
if (el.__xbniuTapBound) return;
|
||||
el.__xbniuTapBound = true;
|
||||
try {
|
||||
el.addEventListener('touchstart', (e) => {
|
||||
const t = e.touches && e.touches[0];
|
||||
if (t) tap._down(t.clientX, t.clientY);
|
||||
}, { passive: true });
|
||||
el.addEventListener('touchend', (e) => {
|
||||
const t = e.changedTouches && e.changedTouches[0];
|
||||
if (t) {
|
||||
try { e.preventDefault(); } catch (err) {}
|
||||
tap._up(t.clientX, t.clientY);
|
||||
}
|
||||
}, { passive: false });
|
||||
} catch (e) { /* 忽略绑定失败 */ }
|
||||
}
|
||||
|
||||
// 给单个 marker 绑定点按处理。marker 需已 __animId = id。
|
||||
|
||||
// static/js/map.js:423-472
|
||||
export function bindMarkerTap(marker, id) {
|
||||
const tap = {
|
||||
lastFire: 0, // 防重入:同一 marker 短时间内只触发一次
|
||||
downX: null, downY: null, downT: 0,
|
||||
_fire() {
|
||||
// 同一 marker 的 click / mouseup / touchend 都可能触发本路径,300ms 内只放行一次
|
||||
const now = Date.now();
|
||||
if (now - this.lastFire < 300) return;
|
||||
this.lastFire = now;
|
||||
clearHighlight();
|
||||
showBikeDetail(id);
|
||||
},
|
||||
_down(x, y) { this.downX = x; this.downY = y; this.downT = Date.now(); },
|
||||
_up(x, y) {
|
||||
if (this.downX === null) return;
|
||||
const dx = x - this.downX, dy = y - this.downY;
|
||||
const moved = Math.sqrt(dx * dx + dy * dy);
|
||||
const dt = Date.now() - this.downT;
|
||||
this.downX = this.downY = null;
|
||||
// 无位移(<10px)且按压短暂(<600ms) 判定为点按 → 即使 BMapGL 吞了 click 也能打开
|
||||
if (moved < 10 && dt < 600) this._fire();
|
||||
}
|
||||
};
|
||||
marker.__xbniuTap = tap;
|
||||
|
||||
// 1) BMapGL 对象级事件:click 为主路径,mousedown/mouseup 补偿“拖动后被吞的 click”
|
||||
try {
|
||||
marker.addEventListener('click', () => tap._fire());
|
||||
marker.addEventListener('mousedown', (e) => tap._down(e.clientX, e.clientY));
|
||||
marker.addEventListener('mouseup', (e) => tap._up(e.clientX, e.clientY));
|
||||
} catch (e) { /* 个别事件类型不支持时忽略 */ }
|
||||
|
||||
// 2) 原生 touch 兜底(移动端最可靠)。domElement 可能延迟生成,故稍后补绑。
|
||||
bindMarkerDomTouch(marker);
|
||||
if (!marker.domElement) {
|
||||
// domElement 尚未就绪:极轻量轮询补绑(最多约 1s),避免移动端兜底落空
|
||||
let tries = 0;
|
||||
const timer = setInterval(() => {
|
||||
tries++;
|
||||
if (marker.domElement) {
|
||||
bindMarkerDomTouch(marker);
|
||||
clearInterval(timer);
|
||||
} else if (tries > 10) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 初始化地图 ==========
|
||||
|
||||
// static/js/map.js:3106-3237
|
||||
export function renderMap(results, isRefresh = false) {
|
||||
if (typeof BikeClusters === "undefined") {
|
||||
throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用");
|
||||
}
|
||||
// 扫码补的临时点每次渲染都回收:它们不在快照数据里,
|
||||
// 不清理的话车早被骑走了地图上还留着一个能点开的旧点。
|
||||
Object.keys(S.scannedMarkers).forEach((key) => {
|
||||
try { S.map.removeOverlay(S.scannedMarkers[key]); } catch (e) {}
|
||||
delete S.scannedMarkers[key];
|
||||
delete S.currentMarkersById[key];
|
||||
});
|
||||
|
||||
// 刷新时不清除边界和停车区(首次加载才绘制)
|
||||
if (!isRefresh) {
|
||||
// 保存自动定位标记的位置
|
||||
const autoPoint = S.autoLocationMarker ? S.autoLocationMarker.getPosition() : null;
|
||||
|
||||
// 清除所有覆盖物
|
||||
S.map.clearOverlays();
|
||||
if (bikeBubbleLayer) {
|
||||
bikeBubbleLayer.destroy();
|
||||
bikeBubbleLayer = null;
|
||||
}
|
||||
|
||||
// 清理旧的标记变量引用
|
||||
S.autoLocationMarker = null;
|
||||
S.myLocationMarker = null;
|
||||
S.currentMarkers = [];
|
||||
|
||||
// 重新添加自动定位标记
|
||||
if (autoPoint) {
|
||||
const iconUrl = createAutoLocationIcon();
|
||||
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
|
||||
S.autoLocationMarker = new BMapGL.Marker(autoPoint, { icon });
|
||||
S.map.addOverlay(S.autoLocationMarker);
|
||||
}
|
||||
|
||||
S.currentPolygons = [];
|
||||
S.currentMarkersById = {};
|
||||
S.markersData = {};
|
||||
S.nearestBikeId = null;
|
||||
}
|
||||
|
||||
const nextBikes = [];
|
||||
let availableCount = 0;
|
||||
let usedCount = 0;
|
||||
let lockedCount = 0;
|
||||
let reservedCount = 0;
|
||||
let lowCount = 0;
|
||||
|
||||
results.forEach(result => {
|
||||
if (result.rtn_code !== 0 || !result.data) return;
|
||||
const data = result.data;
|
||||
|
||||
// 首次加载:绘制骑行区域边界
|
||||
if (!isRefresh && data.driverArea && data.driverArea.length > 0) {
|
||||
const boundaryPoints = data.driverArea.map(p => {
|
||||
const c = offsetCoord(p.latitude, p.longitude);
|
||||
return new BMapGL.Point(c.lng, c.lat);
|
||||
});
|
||||
const boundaryPolygon = new BMapGL.Polygon(boundaryPoints, {
|
||||
strokeColor: "#007AFF",
|
||||
strokeWeight: 2,
|
||||
strokeOpacity: 0.8,
|
||||
fillColor: "#007AFF",
|
||||
fillOpacity: 0.05,
|
||||
});
|
||||
S.map.addOverlay(boundaryPolygon);
|
||||
S.currentPolygons.push(boundaryPolygon);
|
||||
}
|
||||
|
||||
// 首次加载:绘制停车区(只画启用的:is_disable=2 是停用区,
|
||||
// 上游 /record/checkLocation 会直接拒绝,画出来只会误导人)
|
||||
if (!isRefresh && data.parkeArea && data.parkeArea.length > 0) {
|
||||
data.parkeArea.forEach(area => {
|
||||
if (!area.points || area.points.length < 3) return;
|
||||
if (String(area.is_disable) === "2") return;
|
||||
|
||||
const parkingPoints = area.points.map(p => {
|
||||
const c = offsetCoord(p.latitude, p.longitude);
|
||||
return new BMapGL.Point(c.lng, c.lat);
|
||||
});
|
||||
const parkingPolygon = new BMapGL.Polygon(parkingPoints, {
|
||||
strokeColor: "#34C759",
|
||||
strokeWeight: 2,
|
||||
strokeOpacity: 0.8,
|
||||
fillColor: "#34C759",
|
||||
fillOpacity: 0.1,
|
||||
});
|
||||
S.map.addOverlay(parkingPolygon);
|
||||
S.currentPolygons.push(parkingPolygon);
|
||||
});
|
||||
}
|
||||
|
||||
// 收集所有车辆数据用于批量处理
|
||||
const allBikes = BikeClusters.normalizeBikes(data.bicycleStation);
|
||||
|
||||
// 统计数量(所有车辆)
|
||||
// 分类顺序必须与后端 app.py::_classify_bike_state 一致:
|
||||
// state=10 或 电量<20 优先判低电量,其次欠压/损坏,最后 state=1 分使用中/可用。
|
||||
// 注意电量字段是 electric_quantity(上游字段名),不存在 bike.electric。
|
||||
allBikes.forEach(bike => {
|
||||
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||||
if (bike.state === 10 || electric < 20) {
|
||||
lowCount++;
|
||||
} else if (bike.state === 1 && bike.status === 1) {
|
||||
usedCount++;
|
||||
} else if (bike.state === 1) {
|
||||
availableCount++;
|
||||
} else if (bike.state === 4) {
|
||||
lockedCount++;
|
||||
} else if (bike.state === 2) {
|
||||
reservedCount++;
|
||||
}
|
||||
});
|
||||
|
||||
nextBikes.push(...allBikes);
|
||||
});
|
||||
|
||||
// A response is a complete snapshot: remove vanished cars and honour empty results.
|
||||
S.markersData = {};
|
||||
nextBikes.forEach(bike => { S.markersData[BikeClusters.bikeId(bike)] = bike; });
|
||||
document.getElementById("count-available").textContent = String(availableCount);
|
||||
document.getElementById("count-used").textContent = String(usedCount);
|
||||
document.getElementById("count-locked").textContent = String(lockedCount);
|
||||
document.getElementById("count-reserved").textContent = String(reservedCount);
|
||||
document.getElementById("count-low").textContent = String(lowCount);
|
||||
rebuildMarkersForZoom(nextBikes);
|
||||
}
|
||||
|
||||
// Native overlay coordinates keep markers aligned during reverse zooming.
|
||||
// Recomposition cross-fades at the real coordinates instead of moving centroids.
|
||||
|
||||
// static/js/map.js:3238-3238
|
||||
export let bikeBubbleLayer: any = null;
|
||||
|
||||
// static/js/map.js:3239-3255
|
||||
export function setupClusterListener() {
|
||||
if (!S.map || bikeBubbleLayer || typeof BikeClusters === "undefined") return;
|
||||
bikeBubbleLayer = BikeClusters.createLayer({
|
||||
map: S.map,
|
||||
enabled: S.bikeClusteringEnabled,
|
||||
getPoint: bike => offsetCoord(bike.latitude, bike.longitude),
|
||||
getState: getBikeState,
|
||||
getIcon: getBikeIcon,
|
||||
onBikeClick: id => { clearHighlight(); showBikeDetail(id); },
|
||||
onMarkersChanged: markers => {
|
||||
S.currentMarkers = markers;
|
||||
S.currentMarkersById = {};
|
||||
markers.forEach(marker => { S.currentMarkersById[marker.__animId] = marker; });
|
||||
}
|
||||
});
|
||||
bikeBubbleLayer.setSelected(S.highlightedBikeId);
|
||||
}
|
||||
|
||||
// static/js/map.js:3257-3264
|
||||
export function rebuildMarkersForZoom(bikes) {
|
||||
setupClusterListener();
|
||||
if (bikeBubbleLayer) bikeBubbleLayer.setData(bikes ?? Object.values<any>(S.markersData));
|
||||
}
|
||||
|
||||
// ========== 车辆详情 ==========
|
||||
// 卡片顶部按钮是否收成纯图标:不按屏宽猜,直接量车牌有没有被截断。
|
||||
// 车牌越长越早收;收起后再量一次,仍截断就保持(空间真不够了)。
|
||||
Reference in New Issue
Block a user