Files
xbcr/static/js/map.js
T

1334 lines
56 KiB
JavaScript
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.
function apiFetch(url, options) { return typeof AppAPI !== "undefined" ? AppAPI.fetch(url, options) : fetch(url, options); }
// ========== 全局变量 ==========
let map = null;
let currentType = "3";
let currentUser = null; // 当前登录用户
let authKickToastShown = false; // 防重复提示“登录已失效”
let authMode = "login"; // login 或 register
let authToken = localStorage.getItem("auth_token") || null;
let currentMarkers = [];
let currentPolygons = [];
let selectedBike = null;
let markersData = {};
let currentMarkersById = {}; // 用于刷新时快速定位
let myLocationMarker = null;
let autoLocationMarker = null; // 自动持续定位的标记
let autoLocationWatchId = null; // watchPosition 的 ID
let hasLocationPermission = false; // 是否已获取位置权限
let initialLocationCentered = false; // 是否已按用户位置完成首次居中(每页仅一次)
let nearestBikeId = null;
let isFirstLoad = true; // 标记首次加载
let highlightedBikeId = null; // 高亮的车辆ID
// A failed optional map asset must not abort order/return initialization.
let bikeClusteringEnabled = typeof BikeClusters !== "undefined"
? BikeClusters.readClusteringPreference(localStorage) : true;
// 百度地图 API Key(用于坐标转换)
const BAIDU_AK = "GzzqszczKmI7RNTclpLtOXZDTT4mq8a6";
// ========== 图标缓存(性能优化)==========
// 缓存: key = "电量|颜色|是否高亮" → BMapGL.Icon
const iconCache = new Map();
const ICON_CACHE_MAX = 500; // 最多缓存500个不同图标
// ========== 预创建完整图标(首次加载优化)==========
// 预创建各电量和颜色的完整图标(避免首次加载时大量 Canvas 绘制)
const BASE_ICON_COLORS = {
available: "#34C759", // 绿色-可用
inuse: "#FF2D55", // 红色-使用中
locked: "#FF9F0A", // 橙色-欠压
reserved: "#5856D6", // 紫色-损坏
lowbattery: "#8E8E93" // 灰色-低电量
};
// 预创建非高亮状态的完整图标(电量档位 0, 20, 40, 60, 80, 100)
const prebuiltIcons = new Map(); // key: "电量档位|颜色", value: BMapGL.Icon
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 + "") : (electric === null ? "?" : Math.round(electric) + ""), centerX, centerY);
return canvas.toDataURL("image/png");
}
// 预初始化完整图标(在地图加载前调用)
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(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 + " 个图标");
}
// ========== 用车计时 ==========
let activeRental = null; // 当前活跃租车信息
let rentalCountdownTimer = null; // 倒计时定时器
const RENTAL_KEY = "xbniu_rental_key"; // localStorage key
// 手动坐标偏移(仅作为 coordtransform 未加载时的降级常量;正常走 gcj02tobd09 自动转换)
const COORD_OFFSET = {
lat: 0.00603, // 约610米(纬度)
lng: 0.00650, // 约600米-20米(经度,往西20米)
};
// 初始位置额外偏移(再往上30米)
const INIT_OFFSET_EXTRA = 0.00027; // 约30米(向北)
const INIT_OFFSET_EAST = 0.003; // 约300米(向东)
// 坐标转换:车辆/地图数据为 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,
};
}
// 状态判断函数 - 基于 state + status 组合判断
// state=1 + status=0: 空闲可用
// state=1 + status=1: 使用中(被占用)
// state=10: 低电量车辆
// state=4: 欠压车辆
// state=2: 损坏车辆
function getBikeState(bike) { return BikeData.state(bike); }
// ========== 电池绘制 ==========
function updateRingProgress(percent, color) {
const fill = document.getElementById("battery-fill");
if (fill) {
// 电量填充区域最大宽度 39px(外框内宽 = 43-4 left offset-2border=39)
const maxW = 39;
const w = Math.round((percent / 100) * maxW);
fill.setAttribute("width", w);
fill.setAttribute("fill", color);
}
}
// ========== Canvas 电量圆环图标 ==========
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,避免视觉惊扰)
const RED_BIKE_COLOR = "#B4615A"; // 柔和砖红
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 };
}
function getBikeIcon(bike, isHighlighted = false) {
const electric = BikeData.electric(bike);
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' || bikeState === 'unknown' || electric === null) {
color = "#8E8E93"; // 灰色-低电量
}
// 生成缓存 key
const electricLevel = electric === null ? "unknown" : 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 (electric !== null && !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 兜底
function findMarkerById(id) {
const key = String(id);
if (currentMarkersById && currentMarkersById[id]) return currentMarkersById[id];
if (Array.isArray(currentMarkers)) {
for (let i = currentMarkers.length - 1; i >= 0; i--) {
const m = currentMarkers[i];
if (m && m.__animId !== undefined && String(m.__animId) === key) return m;
}
for (let i = currentMarkers.length - 1; i >= 0; i--) {
const m = currentMarkers[i];
if (m && m.getTitle) {
const t = String(m.getTitle()).replace(/^#/, "");
if (t === key) return m;
}
}
}
return null;
}
// 让指定 marker 显示在最上层(放大高亮图标避免被其它普通 marker 遮住)
function bringMarkerToTop(marker) {
if (marker && marker.bringToTop) { marker.bringToTop(); return; }
if (marker && typeof map !== 'undefined' && map && typeof map.removeOverlay === 'function' && typeof map.addOverlay === 'function') {
try {
const markerId = marker.__animId;
map.removeOverlay(marker);
map.addOverlay(marker);
// removeOverlay/addOverlay 可能重建 marker 的 DOM,重绑一次原生 touch 兜底,避免点按失效
if (markerId !== undefined) bindMarkerDomTouch(marker);
} catch (e) { /* 忽略:个别情况下不允许重排 */ }
}
}
function setHighlight(id) {
// 清除之前的高亮
if (highlightedBikeId !== null) {
const prevMarker = findMarkerById(highlightedBikeId);
const prevBike = markersData[highlightedBikeId];
if (prevMarker && prevBike) {
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[setHighlight] 还原图标失败", e); }
}
}
// 设置新高亮
highlightedBikeId = id;
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(id);
if (id === null || id === undefined) return;
const marker = findMarkerById(id);
const bike = markersData[id] || markersData[String(id)] || 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);
}
}
function clearHighlight() {
if (highlightedBikeId !== null) {
const prevMarker = findMarkerById(highlightedBikeId);
const prevBike = markersData[highlightedBikeId];
if (prevMarker && prevBike) {
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[clearHighlight] 还原图标失败", e); }
}
}
highlightedBikeId = null;
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(null);
}
// ========== Marker 点按绑定(统一入口)==========
// 背景:BMapGL 在拖动地图后会把紧接的一次对 marker 的 click 吞掉(当作拖拽延续),
// 导致“点了点但模态框弹不出”。因此这里不用单一 click,而是额外用
// mousedown/mouseup 与原生 touch 的“按下→抬起无位移”判定作为自控点击路径。
// 把原生 touch 兜底绑到 marker 的当前 DOM 元素上(幂等,可被重复调用,
// 用于 domElement 延迟就绪或 removeOverlay/addOverlay 重建 DOM 之后补绑)。
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。
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);
}
}
// ========== 初始化地图 ==========
let mapInitializationStarted = false;
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();
}
function initMapCore() {
// 预加载基础图标(在请求地图数据之前就开始)
preloadBaseIcons();
apiFetch("/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
map = new BMapGL.Map("baidu_map");
map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17);
map.enableScrollWheelZoom(true);
map.enableDragging(true);
map.enableInertialDragging(true);
// 不加 NavigationControl:它带出的左上角方向键/缩放滑杆(以及其中的“定位失败”钮)
// 业务里用不到,双指缩放与拖拽手势不依赖该控件。
map.addControl(new BMapGL.ScaleControl());
updateMapStyle();
loadMapData(currentType);
// 启动自动持续定位(地图加载后立即开始)
if (typeof BikeDiscovery !== "undefined") BikeDiscovery.init();
if (authToken) startAutoLocation();
})
.catch(err => {
console.error("初始化失败:", err);
showToast("地图初始化失败,请刷新重试");
});
}
// ========== 深色模式适配 ==========
function updateMapStyle() {
const isDark = UIPreferences.isDark();
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 = "";
}
}
// 监听系统颜色变化
window.addEventListener('xbniu-theme-change', e => {
updateMapStyle();
});
// ========== 加载地图数据 ==========
let mapRequest = null;
let mapRefreshTimer = null;
let renderedMapSnapshot = null;
let mapRefreshFailed = false;
function resetMapForAccount() {
clearTimeout(mapRefreshTimer);
mapRequest = null; renderedMapSnapshot = null; mapRefreshFailed = false; isFirstLoad = true;
markersData = {}; selectedBike = null; highlightedBikeId = null;
if (bikeBubbleLayer) bikeBubbleLayer.setData([]);
['available','used','locked','reserved','low'].forEach(name => {
const count = document.getElementById('count-' + name); if (count) count.textContent = '0';
});
const stamp = document.getElementById('update-time'); if (stamp) stamp.textContent = '--:--';
if (typeof BikeDiscovery !== 'undefined') BikeDiscovery.render();
}
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 (authToken && map && document.visibilityState === "visible") {
loadMapData(currentType, false, true);
}
}, Math.min(delay, 60000));
}
function loadMapData(type, showLoading = true, quiet = false) {
if (!authToken) { showLoginGate(); return Promise.resolve(); }
if (!map) return Promise.resolve();
if (mapRequest && mapRequest.type === String(type)) return mapRequest.promise;
const requestToken = authToken;
const loading = document.getElementById("loading");
if (isFirstLoad && showLoading) loading.classList.remove("hidden");
const pending = { type: String(type), promise: null };
mapRequest = pending;
pending.promise = apiFetch(`/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 (authToken !== requestToken || String(type) !== String(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], !isFirstLoad);
isFirstLoad = false;
mapRefreshFailed = false;
if (result.map_snapshot) {
renderedMapSnapshot = { ...result.map_snapshot, serverTime, receivedAt: performance.now() };
updateMapFreshnessBadge();
} else updateTime();
if (map) setupClusterListener();
})
.catch(err => {
if (authToken !== requestToken || String(type) !== String(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;
}
// ========== 手动刷新 ==========
function refreshMap() {
const btn = document.getElementById("refresh-btn");
btn.classList.add("spinning");
loadMapData(currentType, false);
setTimeout(() => btn.classList.remove("spinning"), 1000);
}
// ========== 渲染地图(坐标归一化 + 增量气泡图层)==========
function renderMap(results, isRefresh = false) {
if (typeof BikeClusters === "undefined") {
throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用");
}
// 刷新时不清除边界和停车区(首次加载才绘制)
if (!isRefresh) {
// 保存自动定位标记的位置
const autoPoint = autoLocationMarker ? autoLocationMarker.getPosition() : null;
// 清除所有覆盖物
map.clearOverlays();
if (bikeBubbleLayer) {
bikeBubbleLayer.destroy();
bikeBubbleLayer = null;
}
// 清理旧的标记变量引用
autoLocationMarker = null;
myLocationMarker = null;
currentMarkers = [];
// 重新添加自动定位标记
if (autoPoint) {
const iconUrl = createAutoLocationIcon();
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
autoLocationMarker = new BMapGL.Marker(autoPoint, { icon });
map.addOverlay(autoLocationMarker);
}
currentPolygons = [];
currentMarkersById = {};
markersData = {};
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,
});
map.addOverlay(boundaryPolygon);
currentPolygons.push(boundaryPolygon);
}
// 首次加载:绘制停车区
if (!isRefresh && data.parkeArea && data.parkeArea.length > 0) {
data.parkeArea.forEach(area => {
if (!area.points || area.points.length < 3) return;
const parkingPoints = area.points.map(p => {
const c = offsetCoord(p.latitude, p.longitude);
return new BMapGL.Point(c.lng, c.lat);
});
const isActive = area.is_disable !== 1;
const parkingPolygon = new BMapGL.Polygon(parkingPoints, {
strokeColor: isActive ? "#34C759" : "#8E8E93",
strokeWeight: 2,
strokeOpacity: 0.8,
fillColor: isActive ? "#34C759" : "#8E8E93",
fillOpacity: 0.1,
});
map.addOverlay(parkingPolygon);
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 state = getBikeState(bike);
if (state === 'available') availableCount++;
else if (state === 'inuse') usedCount++;
else if (state === 'locked') lockedCount++;
else if (state === 'reserved') reservedCount++;
else if (state === 'lowbattery') lowCount++;
});
nextBikes.push(...allBikes);
});
// A response is a complete snapshot: remove vanished cars and honour empty results.
markersData = {};
nextBikes.forEach(bike => { markersData[BikeClusters.bikeId(bike)] = bike; });
document.getElementById("count-available").textContent = availableCount;
document.getElementById("count-used").textContent = usedCount;
document.getElementById("count-locked").textContent = lockedCount;
document.getElementById("count-reserved").textContent = reservedCount;
document.getElementById("count-low").textContent = lowCount;
rebuildMarkersForZoom(nextBikes);
if (typeof BikeDiscovery !== "undefined") BikeDiscovery.render();
}
// Native overlay coordinates keep markers aligned during reverse zooming.
// Recomposition cross-fades at the real coordinates instead of moving centroids.
let bikeBubbleLayer = null;
function setupClusterListener() {
if (!map || bikeBubbleLayer || typeof BikeClusters === "undefined") return;
bikeBubbleLayer = BikeClusters.createLayer({
map,
enabled: bikeClusteringEnabled,
getPoint: bike => offsetCoord(bike.latitude, bike.longitude),
getState: getBikeState,
getIcon: getBikeIcon,
onBikeClick: id => { clearHighlight(); showBikeDetail(id); },
onMarkersChanged: markers => {
currentMarkers = markers;
currentMarkersById = {};
markers.forEach(marker => { currentMarkersById[marker.__animId] = marker; });
}
});
bikeBubbleLayer.setSelected(highlightedBikeId);
}
function rebuildMarkersForZoom(bikes) {
setupClusterListener();
if (bikeBubbleLayer) { const rows = bikes ?? Object.values(markersData); bikeBubbleLayer.setData(typeof BikeDiscovery !== "undefined" ? BikeDiscovery.visibleBikes(rows) : rows); }
}
// ========== 车辆详情 ==========
function showBikeDetail(id) {
let bike = markersData[id];
// 多格式尝试查找
if (!bike) bike = markersData[String(id)];
if (!bike) bike = markersData[Number(id)];
// 按 code 遍历查找
if (!bike) {
for (const key in markersData) {
if (markersData[key] && String(markersData[key].code) === String(id)) {
bike = markersData[key];
break;
}
}
}
if (!bike) {
console.error("[showBikeDetail] 找不到车辆数据, id=", id, "markersData keys样本=", Object.keys(markersData).slice(0, 5));
return;
}
selectedBike = bike;
// 设置高亮
setHighlight(id);
document.getElementById("card-code").textContent = `#${bike.code || id}`;
// 车辆类型角标(红车 / 大车 / 小车)
const kind = getBikeKind(bike);
const kindEl = document.getElementById("card-kind");
if (kindEl) {
kindEl.textContent = kind.label;
kindEl.classList.remove("kind-red", "kind-big", "kind-small");
kindEl.classList.add("kind-" + kind.key);
}
const electric = BikeData.electric(bike);
document.getElementById("card-electric").textContent = electric === null ? "未知" : Math.round(electric);
document.getElementById("card-electric").parentElement.classList.toggle("battery-unknown", electric === null);
let ringColor = "#34c759";
const bikeState = getBikeState(bike);
if (bikeState === 'inuse') {
ringColor = "#ff2d55";
} else if (bikeState === 'locked') {
ringColor = "#ff9f0a";
} else if (bikeState === 'reserved') {
ringColor = "#5856D6";
} else if (bikeState === 'lowbattery' || bikeState === 'unknown' || electric === null) {
ringColor = "#8e8e93";
}
try {
updateRingProgress(electric, ringColor);
} catch (e) {
console.error("[showBikeDetail] updateRingProgress 错误:", e);
}
// 状态文本:结合 state 和 status 判断
const stateText = BikeData.labels[getBikeState(bike)];
document.getElementById("card-state").textContent = stateText;
document.getElementById("card-state").className = "bike-status-value" +
(stateText === "使用中" ? " warning" : stateText === "可用" ? " highlight" : "");
document.getElementById("bike-card").classList.add("show");
const overlay = document.getElementById("card-overlay");
if (overlay) overlay.classList.add("show");
if (bike.latitude && bike.longitude) {
const c = offsetCoord(bike.latitude, bike.longitude);
const bikePoint = new BMapGL.Point(c.lng, c.lat);
map.panTo(bikePoint);
setTimeout(() => {
map.setZoom(map.getZoom() + 1);
}, 300);
}
}
function closeCard() {
const card = document.getElementById("bike-card");
const overlay = document.getElementById("card-overlay");
card.classList.remove("show");
card.style.transform = "";
if (overlay) overlay.classList.remove("show");
selectedBike = null;
// 关闭卡片时清除高亮,让车辆图标还原为普通大小(不再保持放大带车牌)
clearHighlight();
// 关闭卡片时同步停止丢失模式
if (typeof disableLostMode === "function") disableLostMode();
}
// ========== 下滑关闭手势 ==========
(function initSwipeClose() {
const card = document.getElementById("bike-card");
let startY = 0, startTime = 0, dragging = false;
card.addEventListener("touchstart", (e) => {
// 只响应从 card-handle 或卡片顶部区域发起的手势
startY = e.touches[0].clientY;
startTime = Date.now();
dragging = true;
card.style.transition = "none";
}, { passive: true });
card.addEventListener("touchmove", (e) => {
if (!dragging) return;
const dy = e.touches[0].clientY - startY;
if (dy > 0) {
card.style.transform = `translateY(${dy}px)`;
}
}, { passive: true });
card.addEventListener("touchend", (e) => {
if (!dragging) return;
dragging = false;
card.style.transition = "";
const dy = e.changedTouches[0].clientY - startY;
const dt = Date.now() - startTime;
// 快速下划(速度 > 0.5px/ms)或位移超过120px则关闭
if (dy > 120 || (dy > 40 && dt < 250)) {
closeCard();
} else {
card.style.transform = "";
}
}, { passive: true });
})();
// ========== 扫码查询 ==========
function scanCode() {
const code = document.getElementById("scan-input").value.trim();
if (!BikeData.validCode(code)) { showToast("请输入5位普通车牌或8位红车车牌,只能包含数字"); document.getElementById("scan-input").focus(); return; }
showToast("正在查询...");
apiFetch("/api/bicycle", {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${authToken}` },
body: JSON.stringify({ code })
})
.then(r => r.json())
.then(data => {
const codeNum = parseInt(code);
if (data.rtn_code === 401) { showLoginGate(); return; }
// 成功查询:正常处理
if (data.rtn_code === 0 && data.data) {
const bike = data.data;
bike.code = code;
// 优先用 markersData 的实时位置,其次用 API 返回的位置
const mapBike = markersData[codeNum] || markersData[code];
let hasLocation = false;
if (mapBike && mapBike.latitude && mapBike.longitude) {
bike.latitude = mapBike.latitude;
bike.longitude = mapBike.longitude;
bike.state = mapBike.state;
bike.electric_quantity = mapBike.electric_quantity;
hasLocation = true;
} else if (bike.latitude && bike.longitude) {
hasLocation = true;
}
if (hasLocation) {
const c = offsetCoord(bike.latitude, bike.longitude);
map.panTo(new BMapGL.Point(c.lng, c.lat));
setTimeout(() => map.setZoom(map.getZoom() + 1), 300);
} else {
showToast("该车暂无实时位置,请在地图上查看");
}
// 如果车辆在使用中,额外提示
if (bike.state === 1 && bike.status === 1) {
showToast("该车正在使用中");
}
markersData[codeNum] = bike;
showBikeDetail(codeNum);
}
// success=false 时,也尝试用 markersData 显示详情和定位
else if (data.success === false) {
const mapBike = markersData[codeNum] || markersData[code];
if (mapBike && mapBike.latitude && mapBike.longitude) {
// 跳转并放大
const c = offsetCoord(mapBike.latitude, mapBike.longitude);
map.panTo(new BMapGL.Point(c.lng, c.lat));
setTimeout(() => map.setZoom(map.getZoom() + 1), 300);
// 弹详情窗口
mapBike.code = code;
markersData[codeNum] = mapBike;
showBikeDetail(codeNum);
// toast 提示
showToast(data.message || "该车辆已被使用");
} else {
showToast(data.message || "查询失败");
}
}
else {
showToast(data.message || "查询失败");
}
})
.catch(err => showToast("请求失败: " + friendlyError(err)));
}
// ========== 寻车功能 ==========
// ----- 丢失模式状态 -----
let _lostModeActive = false; // 是否处于丢失模式
let _lostModeTimer = null; // setInterval 句柄
let _findClickCount = 0; // 连续点击次数计数
let _findClickTimer = null; // 连续点击重置计时器
let _findLongPressTimer = null; // 长按计时器
const LOST_TRIGGER_CLICKS = 3; // 连续点击 N 次触发
const LOST_TRIGGER_LONG = 700; // 长按毫秒数触发
const LOST_INTERVAL = 3000; // 丢失模式下每次寻车间隔(ms)
/** 发送单次寻车请求(内部使用,不操作按钮状态) */
function _doFindBikeRequest(code) {
return apiFetch("/api/find_bike", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authToken}`
},
body: JSON.stringify({ code: code, school_id: 10 })
}).then(r => r.json()).catch(() => null);
}
/** 打开丢失模式确认弹窗 */
function showLostModal() {
document.getElementById("lost-modal").classList.add("show");
}
/** 关闭丢失模式确认弹窗(不启用) */
function closeLostModal() {
document.getElementById("lost-modal").classList.remove("show");
}
/** 启用丢失模式(弹窗确认后调用) */
function enableLostMode() {
closeLostModal();
if (!selectedBike) return;
_lostModeActive = true;
const btn = document.getElementById("bike-find-btn-header");
const span = btn.querySelector("span");
btn.classList.add("lost-mode");
btn.title = "丢失模式(点击退出)";
if (span) span.textContent = "丢失模式";
showToast("丢失模式已开启,持续帮你寻车");
// 立即发一次
_doFindBikeRequest(selectedBike.code);
// 持续循环
_lostModeTimer = setInterval(() => {
if (!_lostModeActive || !selectedBike) {
disableLostMode();
return;
}
_doFindBikeRequest(selectedBike.code);
}, LOST_INTERVAL);
// 页面隐藏或关闭时自动停止
window.addEventListener("beforeunload", _onPageUnload);
document.addEventListener("visibilitychange", _onVisibilityChange);
}
/** 停止丢失模式 */
function disableLostMode() {
if (!_lostModeActive) return;
_lostModeActive = false;
clearInterval(_lostModeTimer);
_lostModeTimer = null;
_findClickCount = 0;
const btn = document.getElementById("bike-find-btn-header");
const span = btn.querySelector("span");
if (btn) {
btn.classList.remove("lost-mode");
btn.disabled = false;
btn.title = "寻车";
}
if (span) span.textContent = "寻车";
window.removeEventListener("beforeunload", _onPageUnload);
document.removeEventListener("visibilitychange", _onVisibilityChange);
showToast("丢失模式已关闭");
}
function _onPageUnload() { disableLostMode(); }
function _onVisibilityChange() {
if (document.visibilityState === "hidden") disableLostMode();
}
/**
* 主寻车入口(绑定到按钮 onclick)
* - 丢失模式激活时:点击直接关闭丢失模式
* - 连续点击 LOST_TRIGGER_CLICKS 次:触发丢失模式弹窗
* - 否则:正常寻车
*/
function findBike() {
if (!selectedBike) return;
// 如果已是丢失模式,点击退出
if (_lostModeActive) {
disableLostMode();
return;
}
// 连续点击计数
_findClickCount++;
clearTimeout(_findClickTimer);
_findClickTimer = setTimeout(() => { _findClickCount = 0; }, 1200);
if (_findClickCount >= LOST_TRIGGER_CLICKS) {
_findClickCount = 0;
clearTimeout(_findClickTimer);
showLostModal();
return;
}
// 正常寻车
const code = selectedBike.code;
const btn = document.getElementById("bike-find-btn-header");
const span = btn.querySelector("span");
btn.disabled = true;
btn.title = "发送中...";
if (span) span.textContent = "发送中...";
_doFindBikeRequest(code)
.then(data => {
if (data && (data.rtn_code === 0 || data.success)) {
showToast("寻车指令已发送,请听声音");
} else {
showToast((data && data.message) || "寻车失败");
}
})
.catch(err => {
showToast("请求失败: " + friendlyError(err));
})
.finally(() => {
if (!_lostModeActive) {
btn.disabled = false;
btn.title = "寻车";
if (span) span.textContent = "寻车";
}
});
}
// ===== 长按触发丢失模式 =====
(function initFindBtnLongPress() {
const btn = document.getElementById("bike-find-btn-header");
if (!btn) return;
function startLongPress(e) {
// 丢失模式下不需要长按(单击退出即可)
if (_lostModeActive) return;
clearTimeout(_findLongPressTimer);
_findLongPressTimer = setTimeout(() => {
// 长按成功,阻止后续 click 事件触发普通寻车
_findClickCount = 0;
clearTimeout(_findClickTimer);
showLostModal();
}, LOST_TRIGGER_LONG);
}
function cancelLongPress() {
clearTimeout(_findLongPressTimer);
}
btn.addEventListener("mousedown", startLongPress);
btn.addEventListener("touchstart", startLongPress, { passive: true });
btn.addEventListener("mouseup", cancelLongPress);
btn.addEventListener("mouseleave", cancelLongPress);
btn.addEventListener("touchend", cancelLongPress);
btn.addEventListener("touchcancel", cancelLongPress);
})();
// ========== 定位最近车辆(手动找车)==========
function locateMe() {
if (!navigator.geolocation) {
showToast("您的浏览器不支持定位");
return;
}
// 启动自动持续定位(页面启动时调用一次即可)
startAutoLocation();
}
// 手动找最近的车(基于当前自动定位的位置)
function findNearestBikeManual() {
if (!authToken) { showLoginGate(); return; }
if (!autoLocationMarker) {
BikeDiscovery.locationStatus("尚未获取位置。可重新定位,或按地图中心找车。", true);
BikeDiscovery.showList(); return;
}
findNearestBike(autoLocationMarker.getPosition());
}
// 显示我的位置(手动定位模式,带 panTo)
function showMyLocation(point) {
if (myLocationMarker) {
map.removeOverlay(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));
myLocationMarker = new BMapGL.Marker(point, { icon });
map.addOverlay(myLocationMarker);
map.panTo(point);
}
// 绘制自动定位标记(带外圈脉冲效果,灰色调)
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)
function updateAutoLocation(point) {
if (!autoLocationMarker) {
// 首次创建
const iconUrl = createAutoLocationIcon();
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
autoLocationMarker = new BMapGL.Marker(point, { icon });
map.addOverlay(autoLocationMarker);
} else {
// 更新位置
autoLocationMarker.setPosition(point);
}
}
// 启动自动持续定位
function startAutoLocation() {
if (!navigator.geolocation) {
BikeDiscovery.locationStatus("浏览器不支持定位,可以按地图中心或校园地点找车。", false);
return;
}
// 如果已经在监听,先停止
if (autoLocationWatchId !== null) {
navigator.geolocation.clearWatch(autoLocationWatchId);
}
BikeDiscovery.locationStatus("正在获取位置,可先按地图中心查找车辆。", false);
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);
hasLocationPermission = true;
BikeDiscovery.locationStatus("定位已更新,可以找最近的车。");
BikeDiscovery.render();
// 用户授权定位时:本页首次拿到位置后,把地图居中到用户位置(仅一次)
if (!initialLocationCentered) {
initialLocationCentered = true;
if (map) {
map.setCenter(myPoint);
}
}
},
(err) => {
console.log("[自动定位] 定位失败:", err.message);
hasLocationPermission = false;
const reason = err.code === 1 ? "定位权限未开启,请在浏览器的网站权限中允许定位。" : err.code === 3 ? "定位超时,请重试或按地图中心找车。" : "暂时无法获取位置,可重试或按地图中心找车。";
BikeDiscovery.locationStatus(reason, true);
},
{ enableHighAccuracy: false, maximumAge: 5000, timeout: 10000 }
);
}
// 停止自动定位
function stopAutoLocation() {
if (autoLocationWatchId !== null) {
navigator.geolocation.clearWatch(autoLocationWatchId);
autoLocationWatchId = null;
}
if (autoLocationMarker) {
map.removeOverlay(autoLocationMarker);
autoLocationMarker = null;
}
}
// 计算距离并找最近可用车辆(智能电量匹配)
function findNearestBike(myPoint) { return BikeDiscovery.nearest(myPoint); }