用户口径:还车/锁车这块不要打断人去选,按地图中心或找个停车点直接还就行。
改法
- getOrderOperationLocation() 改为自动兜底链,全程不问用户:
navigator.geolocation(WGS84,直接用)
→ 页面上的「我」标记(BD09 → GCJ02 → WGS84,位置最贴近用户)
→ 地图中心(BD09 → WGS84)
→ 校园中心(/api/config 的 center_lat/lng,GCJ02 → WGS84)
→ 都没有才返回 null 并中止(仍不伪造 36.67/116.98 这类魔数)
- 走兜底时只给一条 toast:「定位不可用,已用地图中心上报位置」,不阻塞操作
- 删除弹窗相关代码:askOperationLocation / settleOperationLocation /
chooseGeoRetry / chooseGeoMapCenter / cancelGeoChoice 及其状态与超时常量;
templates/map.html 的 #geo-choice-modal 整块、compat/globals.ts 的 3 个 window 挂载
- map/core.ts:校园中心同时镜像到 S.campusCenter(getCampusCenter 会回读 S),
让「地图没加载出来」这条兜底链可测、现场可在控制台看到
测试
- test_ux_p0_rental_return.cjs 的 UX-04 三条改写为新口径:
· 无定位 → 静默用地图中心(校验 BD09→WGS84 数值、source=map-center、toast 有提示)
· 地图没就绪 → 退校园中心(source=campus-center)
· 都没有 → 返回 null 且不发还车请求
- 全量 238 pytest + 43 node 全绿
- 浏览器实测(390px,禁用 geolocation):DOM 里没有 #geo-choice-modal,
window.chooseGeo* 已不存在;取坐标返回 {lat 36.53198, lng 116.77749, source map-center},
toast「定位不可用,已用地图中心上报位置」,JS 异常 0
615 lines
25 KiB
TypeScript
615 lines
25 KiB
TypeScript
/* 由 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;
|
||
|
||
// ========== 校园中心缓存(UX-04 的坐标链要用)==========
|
||
// /api/config 的 center_lat/center_lng 与 campus.CAMPUS_CENTER_* 一致,是 **GCJ02**。
|
||
// 缓存一份给「连地图实例都没有」时兜底,避免为了一个兜底再打一次配置接口。
|
||
let campusCenter: { lat: number; lng: number } | null = null;
|
||
|
||
export function setCampusCenter(lat: any, lng: any) {
|
||
const la = Number(lat), ln = Number(lng);
|
||
if (Number.isFinite(la) && Number.isFinite(ln) && la !== 0 && ln !== 0) {
|
||
campusCenter = { lat: la, lng: ln };
|
||
// 同时镜像到全局 state:迁到 TS 后所有可变状态都该能在 S 里看到,
|
||
// 也让"地图没加载出来时用校园中心兜底"这条链可测、可现场排查。
|
||
(S as any).campusCenter = campusCenter;
|
||
}
|
||
}
|
||
|
||
export function getCampusCenter() {
|
||
return campusCenter || ((S as any).campusCenter ?? null);
|
||
}
|
||
|
||
/** 拿校园中心(GCJ02);没有缓存就现取一次 /api/config。拿不到返回 null。 */
|
||
export async function loadCampusCenter() {
|
||
if (campusCenter) return campusCenter;
|
||
try {
|
||
const resp = await fetch("/api/config");
|
||
const cfg = await resp.json();
|
||
setCampusCenter(cfg && cfg.center_lat, cfg && cfg.center_lng);
|
||
} catch (err) {
|
||
console.error("[地图] 读取校园中心失败:", err);
|
||
}
|
||
return campusCenter;
|
||
}
|
||
|
||
// ========== 地图加载失败自救(UX-01)==========
|
||
// 原来的失败只有一条 2.5 秒就消失的 toast,遮罩还在、页面永久「正在加载车辆...」,
|
||
// 用户没有任何自救入口。这里把失败做成遮罩内的卡片:一句人话原因 + 44px 的重新加载按钮。
|
||
export type MapLoadFailureKind = "script" | "config" | "data";
|
||
|
||
let mapLoadFailed: MapLoadFailureKind | null = null;
|
||
// 初始化是否已经「落定」(config 请求成功或失败):用来区分「还在初始化」和「初始化失败」,
|
||
// 避免用户在地图还没建好时点刷新就被误判成失败。
|
||
let mapInitSettled = false;
|
||
|
||
export function getMapLoadFailure() {
|
||
return mapLoadFailed;
|
||
}
|
||
|
||
function isWeChatBrowser() {
|
||
try { return /MicroMessenger/i.test(navigator.userAgent || ""); } catch (e) { return false; }
|
||
}
|
||
|
||
function mapFailureReason(kind: MapLoadFailureKind) {
|
||
if (kind === "config") return "校园配置读取失败,服务暂时不可用。";
|
||
if (kind === "data") return "车辆数据没能取到,可能刚好在更新。";
|
||
return "地图组件没有加载成功,可能是网络不稳定,或微信拦下了地图脚本。";
|
||
}
|
||
|
||
/**
|
||
* 把「正在加载车辆...」遮罩换成可自救的失败卡片。
|
||
* 幂等:已经显示过就不再重绘(避免覆盖用户正在点的按钮)。
|
||
*/
|
||
export function showMapLoadFailure(kind: MapLoadFailureKind = "script", detail?: string) {
|
||
mapLoadFailed = kind;
|
||
mapInitSettled = true;
|
||
// 顶部时间徽标同步成失败态:数据是不是新的,一眼能看出来
|
||
const badge = document.getElementById("update-time");
|
||
if (badge) {
|
||
badge.textContent = "更新失败";
|
||
badge.classList.add("stale");
|
||
}
|
||
const overlay = document.getElementById("loading");
|
||
if (!overlay) return;
|
||
overlay.classList.remove("hidden");
|
||
if (overlay.classList.contains("error")) return; // 卡片已在:只确保它可见,不重绘
|
||
overlay.classList.add("error");
|
||
const safeDetail = String(detail || "").replace(/[<>&]/g, ch => ({ "<": "<", ">": ">", "&": "&" } as any)[ch]);
|
||
overlay.innerHTML =
|
||
'<div class="loading-failure">' +
|
||
'<div class="loading-failure-icon" aria-hidden="true">!</div>' +
|
||
'<div class="loading-failure-title">地图加载失败</div>' +
|
||
'<p class="loading-failure-text">' + mapFailureReason(kind) +
|
||
(safeDetail ? '<br><span class="loading-failure-detail">' + safeDetail + '</span>' : "") +
|
||
'</p>' +
|
||
'<button type="button" class="loading-retry-btn" id="loading-retry-btn">重新加载</button>' +
|
||
(isWeChatBrowser()
|
||
? '<p class="loading-failure-hint">微信里一直失败时,点右上角「…」→「在浏览器中打开」再试。</p>'
|
||
: '<p class="loading-failure-hint">也可以在手机浏览器里直接打开本页。</p>') +
|
||
'<p class="loading-failure-hint" id="loading-failure-hint">已经登录过的话,重新加载会自动恢复登录态。</p>' +
|
||
'</div>';
|
||
const retry = document.getElementById("loading-retry-btn");
|
||
if (retry) retry.addEventListener("click", () => { window.location.reload(); });
|
||
}
|
||
|
||
// 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 {
|
||
// 15 秒都等不到地图 SDK:遮罩必须变成可自救的失败卡片(只弹 toast 等于死局)
|
||
console.error("百度地图GL API加载失败");
|
||
showToast("地图API加载失败,请检查网络后刷新");
|
||
showMapLoadFailure("script");
|
||
}
|
||
}
|
||
waitForBMap();
|
||
}
|
||
|
||
// ========== 登录认证 ==========
|
||
|
||
// static/js/map.js:2965-3003
|
||
export function initMapCore() {
|
||
// 预加载基础图标(在请求地图数据之前就开始)
|
||
preloadBaseIcons();
|
||
|
||
fetch("/api/config")
|
||
.then(r => r.json())
|
||
.then(cfg => {
|
||
// 判空:这条 .then 后面紧接着就要建地图,缺一个标题节点不该让整张地图初始化中断(BUG-23)
|
||
const schoolNameEl = document.getElementById("school-name");
|
||
if (schoolNameEl) schoolNameEl.textContent = cfg.school_name || "山东管理学院";
|
||
// 校园中心(GCJ02)缓存一份:UX-04 的坐标兜底链要用
|
||
setCampusCenter(cfg.center_lat, cfg.center_lng);
|
||
// 初始位置:整体偏移 + 额外上移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");
|
||
mapInitSettled = true;
|
||
// 地图实例刚建好:立刻把导航模块的拖动监听绑上(浏览器里唯一可靠的时机,
|
||
// 之前 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 => {
|
||
// /api/config 拉不到 = 地图建不出来:必须落到同一个失败卡片,
|
||
// 否则遮罩永远停在那里转圈(原来只弹一个会自己消失的 toast)
|
||
console.error("初始化失败:", err);
|
||
showToast("地图初始化失败,请刷新重试");
|
||
showMapLoadFailure("config", friendlyError(err));
|
||
});
|
||
}
|
||
|
||
// ========== 深色模式适配 ==========
|
||
|
||
// 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) {
|
||
// 地图实例不存在:要么还在初始化(正常,遮罩本来就盖着、等它就是),
|
||
// 要么初始化已经失败(这时必须给失败卡片,否则遮罩永远撤不掉)
|
||
if (mapLoadFailed) showMapLoadFailure(mapLoadFailed);
|
||
else if (mapInitSettled) showMapLoadFailure("script");
|
||
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();
|
||
// 首屏就没数据:遮罩换成失败卡片(带重新加载),别只弹一个会消失的 toast
|
||
if (S.isFirstLoad) showMapLoadFailure("data", result.message || "");
|
||
if (!quiet) showToast(result.message || "车辆数据更新失败,正在自动重试");
|
||
return;
|
||
}
|
||
renderMap([result], !S.isFirstLoad);
|
||
S.isFirstLoad = false;
|
||
mapRefreshFailed = false;
|
||
mapLoadFailed = null;
|
||
loading.classList.remove("error"); // 拿到了数据:把失败卡片划掉
|
||
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 (S.isFirstLoad) showMapLoadFailure("data", friendlyError(err));
|
||
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);
|
||
}
|
||
|
||
// ========== 启动 ==========
|
||
// 启动时检查登录状态,然后检查租车
|