diff --git a/static/css/map.css b/static/css/map.css index 15bf5e9..223a32a 100644 --- a/static/css/map.css +++ b/static/css/map.css @@ -2790,3 +2790,25 @@ font-size: 12.5px; font-weight: 600; } + +/* 拖动地图后的「返回导航」胶囊 */ +.nav-resume { + position: fixed; + left: 50%; + transform: translateX(-50%); + bottom: calc(150px + env(safe-area-inset-bottom, 0px)); + z-index: 270; + display: inline-flex; + align-items: center; + gap: 6px; + padding: 9px 16px; + border: none; + border-radius: 999px; + background: #0A84FF; + color: #fff; + font-size: 13px; + font-weight: 600; + box-shadow: 0 6px 20px rgba(10, 132, 255, 0.45); +} +.nav-resume[hidden] { display: none; } +.nav-banner-icon { display: inline-flex; align-items: center; color: #0A84FF; } diff --git a/static/js/map.js b/static/js/map.js index 6f9d237..9515997 100644 --- a/static/js/map.js +++ b/static/js/map.js @@ -1378,121 +1378,356 @@ } catch (e) { /* 保留直线估算 */ } } - // ========== 导航:画「我 -> 车」的路线 ========== - let _navOverlays = []; - let _navBikeCode = null; + // ========== 跟随式导航 ========== + // 状态:null = 未导航;对象存在 = 导航中 + // { ptsGcj, ptsBD, idx, walking, follow, timer, watchId, destCode, distance, duration } + let _nav = null; let _navLoading = false; - function _clearNavOverlays() { - _navOverlays.forEach(ov => { try { map.removeOverlay(ov); } catch (e) {} }); - _navOverlays = []; - _navBikeCode = null; - const banner = document.getElementById("nav-banner"); - if (banner) banner.hidden = true; - const btnText = document.getElementById("bike-nav-btn-text"); - if (btnText) btnText.textContent = "导航"; + // 偏航阈值:百度会把起点吸附到最近道路,和真实 GPS 天然差 20~50 米, + // 所以阈值不能太小,且重算要有冷却,否则会陷入"重算->又偏->再重算"。 + const NAV_DEVIATE_M = 60; + const NAV_RECOMPUTE_COOLDOWN_MS = 12000; + const NAV_BOTTOM_RATIO = 0.26; // 当前位置压在屏幕下方约 74% 高度处 + const NAV_FREE_TIMEOUT = 8000; // 拖动后多久自动回正 + + function _haversineM(lat1, lng1, lat2, lng2) { + const R = 6371000; + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLng = (lng2 - lng1) * Math.PI / 180; + const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLng / 2) * Math.sin(dLng / 2); + return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + } + + // 浏览器定位给的是 WGS84,转成 GCJ02 才能和百度/上游坐标对齐 + function _gpsToGcj(coords) { + const lat = coords.latitude, lng = coords.longitude; + if (typeof coordtransform !== "undefined" && coordtransform.wgs84togcj02) { + try { + const g = coordtransform.wgs84togcj02(lng, lat); // -> [lng, lat] + return { lat: g[1], lng: g[0] }; + } catch (e) { /* 落到下面原值兜底 */ } + } + return { lat: lat, lng: lng }; + } + + // 航向角:0=正北,90=正东 + function _bearing(from, to) { + const p1 = from.lat * Math.PI / 180, p2 = to.lat * Math.PI / 180; + const dl = (to.lng - from.lng) * Math.PI / 180; + const y = Math.sin(dl) * Math.cos(p2); + const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl); + return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360; + } + + // 当前位置在折线上的最近点(返回下标 + 偏差米数) + function _projectOnRoute(ptsBD, point) { + let best = 0, bestM = Infinity; + for (let i = 0; i < ptsBD.length; i++) { + const d = _haversineM(point.lat, point.lng, ptsBD[i].lat, ptsBD[i].lng); + if (d < bestM) { bestM = d; best = i; } + } + return { index: best, meters: bestM }; + } + + function _navBanner(show) { + const el = document.getElementById("nav-banner"); + if (el) el.hidden = !show; + } + + function _navPill(show) { + const el = document.getElementById("nav-resume"); + if (el) el.hidden = !show; + } + + function _navBtnText(text) { + const el = document.getElementById("bike-nav-btn-text"); + if (el) el.textContent = text; + } + + function _clearNavLayers() { + if (!_nav) return; + (_nav.walking || []).forEach(ov => { try { map.removeOverlay(ov); } catch (e) {} }); + (_nav.remaining || []).forEach(ov => { try { map.removeOverlay(ov); } catch (e) {} }); + if (_nav.endMarker) { try { map.removeOverlay(_nav.endMarker); } catch (e) {} } + _nav.walking = []; _nav.remaining = []; _nav.endMarker = null; + } + + // 按进度把折线切成「已走(灰)」与「剩余(蓝)」 + function _redrawRoute(fromIndex) { + if (!_nav || !_nav.ptsBD || !_nav.ptsBD.length) return; + _clearNavLayers(); + const pts = _nav.ptsBD; + const cut = Math.max(0, Math.min(fromIndex, pts.length - 1)); + + if (cut > 0) { + const walked = new BMapGL.Polyline(pts.slice(0, cut + 1), { + strokeColor: "#9E9E9E", strokeWeight: 6, strokeOpacity: 0.85, + strokeStyle: "solid" + }); + map.addOverlay(walked); + _nav.walking.push(walked); + } + if (cut < pts.length - 1) { + const rest = pts.slice(cut); + const casing = new BMapGL.Polyline(rest, { + strokeColor: "#FFFFFF", strokeWeight: 11, strokeOpacity: 0.95, + strokeStyle: "solid" + }); + const line = new BMapGL.Polyline(rest, { + strokeColor: "#0A84FF", strokeWeight: 6, strokeOpacity: 1, + strokeStyle: "solid" + }); + map.addOverlay(casing); + map.addOverlay(line); + _nav.remaining.push(casing, line); + } + if (!_nav.endMarker) { + _nav.endMarker = new BMapGL.Marker(pts[pts.length - 1]); + map.addOverlay(_nav.endMarker); + } + } + + // 跟随:把当前位置压到屏幕下方,并让行进方向朝上 + // 部分环境(例如 WebGL 软件渲染)setHeading 不生效,探测一次后退化为「正北朝上」 + let _headingSupported = null; + function _applyHeading(deg) { + if (_headingSupported === false) return; + try { + if (typeof map.setHeading !== "function") { _headingSupported = false; return; } + map.setHeading(deg); + if (_headingSupported === null) { + const got = typeof map.getHeading === "function" ? map.getHeading() : undefined; + // 调了 45 度结果还是 0,说明这个环境不支持地图旋转 + _headingSupported = (typeof got === "number" && Math.abs(got) > 0.5); + if (!_headingSupported) { + console.info("[导航] 当前环境不支持地图旋转,改为正北朝上"); + try { map.setHeading(0); } catch (e) {} + } + } + } catch (e) { _headingSupported = false; } + } + + function _centerOnUser(point, headingDeg) { + try { + if (typeof headingDeg === "number") _applyHeading(headingDeg); + map.setCenter(point); + const h = window.innerHeight || 800; + if (map.panBy) map.panBy(0, Math.round(h * NAV_BOTTOM_RATIO)); + } catch (e) { /* 忽略:个别机型不允许旋转/平移 */ } + } + + function _navTick(position) { + if (!_nav || _nav.follow === false) return; // 拖动查看时不抢镜头 + const gcj = _gpsToGcj(position); // WGS84 -> GCJ02 + const c = offsetCoord(gcj.lat, gcj.lng); // GCJ02 -> BD09 + const me = new BMapGL.Point(c.lng, c.lat); + + const proj = _projectOnRoute(_nav.ptsBD, me); + const now = Date.now(); + if (proj.meters > NAV_DEVIATE_M && !_nav.recomputing + && now - (_nav.lastRecomputeAt || 0) > NAV_RECOMPUTE_COOLDOWN_MS) { + _nav.recomputing = true; + _nav.lastRecomputeAt = now; + _recomputeRoute(gcj).finally(() => { if (_nav) _nav.recomputing = false; }); + return; // 本帧不更新进度,等新路线 + } + if (proj.index !== _nav.idx) { + _nav.idx = proj.index; + _redrawRoute(_nav.idx); + } + const next = _nav.ptsBD[Math.min(_nav.idx + 1, _nav.ptsBD.length - 1)]; + const heading = _bearing(me, next); + _centerOnUser(me, heading); + + // 剩余距离/时间(按进度线性折算,仅用于展示) + const total = _nav.ptsBD.length - 1; + const ratio = total > 0 ? Math.max(0, 1 - _nav.idx / total) : 0; + const leftM = Math.round((_nav.distance || 0) * ratio); + const leftS = Math.round((_nav.duration || 0) * ratio); + // 到达判定用「到终点的真实距离」,避免 GPS 抖动跳点就结束导航 + const dest = _nav.ptsBD[_nav.ptsBD.length - 1]; + const toDest = _haversineM(me.lat, me.lng, dest.lat, dest.lng); + const bannerText = document.getElementById("nav-banner-text"); + if (bannerText) { + bannerText.textContent = leftM < 1000 + ? "剩余 " + leftM + " 米 · 约 " + Math.max(1, Math.round(leftS / 60)) + " 分钟" + : "剩余 " + (leftM / 1000).toFixed(1) + " 公里 · 约 " + + Math.max(1, Math.round(leftS / 60)) + " 分钟"; + } + if (toDest < 25) { + showToast("已到达车辆附近"); + stopNavigation(); + } + } + + async function _recomputeRoute(gcj) { // gcj = {lat, lng}(GCJ02) + const bike = selectedBike; + if (!bike || !bike.latitude) return; + try { + const data = await _requestNavRoute(gcj.lat, gcj.lng, + bike.latitude, bike.longitude); + if (!data) return; + _applyRoute(data); + showToast("已重新规划路线"); + } catch (e) { + console.warn("[导航] 重算失败", e); + } + } + + async function _requestNavRoute(originLat, originLng, destLat, destLng) { + const url = "/api/nav_route?mode=walking" + + "&origin_lat=" + originLat + "&origin_lng=" + originLng + + "&dest_lat=" + destLat + "&dest_lng=" + destLng; + const resp = await fetch(url, { headers: { "Authorization": "Bearer " + authToken } }); + const json = await resp.json(); + const d = json && json.data; + if (json.rtn_code !== 0 || !d || !d.points || !d.points.length) { + throw new Error((json && json.message) || "没有拿到路线"); + } + return d; + } + + // 用接口结果重建导航状态(首次与重算共用) + function _applyRoute(d) { + _nav.ptsGcj = d.points; + _nav.ptsBD = d.points.map(pt => { + const c = offsetCoord(pt[1], pt[0]); + return new BMapGL.Point(c.lng, c.lat); + }); + _nav.distance = d.distance; + _nav.duration = d.duration; + _nav.idx = 0; + _nav.recomputing = false; + _redrawRoute(0); } function stopNavigation() { - _clearNavOverlays(); + if (_nav && _nav.watchId !== null && navigator.geolocation) { + navigator.geolocation.clearWatch(_nav.watchId); + } + if (_nav && _nav.timer) clearTimeout(_nav.timer); + _clearNavLayers(); + _nav = null; + _navBanner(false); + _navPill(false); + _navBtnText("导航"); + try { if (map.resetHeading) map.resetHeading(); } catch (e) {} + _headingSupported = null; } function toggleNavigation() { const bike = selectedBike; if (!bike) return; - if (_navBikeCode && String(_navBikeCode) === String(bike.code)) { - stopNavigation(); // 再点一次 = 结束 + if (_nav && String(_nav.destCode) === String(bike.code)) { + stopNavigation(); return; } startNavigation(bike); } + // 拖动地图后:显示「返回导航」,超时自动回正 + function _onMapDragStart() { + if (!_nav) return; + _nav.follow = false; + if (_nav.timer) clearTimeout(_nav.timer); + _navPill(true); + } + + function _onMapDragEnd() { + if (!_nav || _nav.follow) return; + if (_nav.timer) clearTimeout(_nav.timer); + _nav.timer = setTimeout(() => { if (_nav && !_nav.follow) resumeNavigation(); }, + NAV_FREE_TIMEOUT); + } + + function resumeNavigation() { + if (!_nav) return; + _nav.follow = true; + _navPill(false); + if (_nav.timer) { clearTimeout(_nav.timer); _nav.timer = null; } + const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker) + ? autoLocationMarker.getPosition() : null; + if (me) { + const next = _nav.ptsBD[Math.min(_nav.idx + 1, _nav.ptsBD.length - 1)]; + _centerOnUser(me, _bearing(me, next)); + } + } + async function startNavigation(bike) { if (_navLoading) return; const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker) ? autoLocationMarker.getPosition() : null; - if (!me) { - showToast("请先开启定位,才能规划路线"); - return; - } + if (!me) { showToast("请先开启定位,才能规划路线"); return; } if (!bike || !bike.latitude || !bike.longitude) { - showToast("这辆车没有坐标,无法导航"); - return; + showToast("这辆车没有坐标,无法导航"); return; } - _clearNavOverlays(); + if (_nav) stopNavigation(); _navLoading = true; - const banner = document.getElementById("nav-banner"); + _navBanner(true); const bannerText = document.getElementById("nav-banner-text"); - if (banner) banner.hidden = false; if (bannerText) bannerText.textContent = "正在规划路线…"; try { - const gcj = (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02) - ? coordtransform.bd09togcj02(me.lng, me.lat) : null; + let gcj = null; + if (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02) { + gcj = coordtransform.bd09togcj02(me.lng, me.lat); + } if (!gcj) throw new Error("坐标转换不可用"); - const url = "/api/nav_route?mode=walking" - + "&origin_lat=" + gcj[1] + "&origin_lng=" + gcj[0] - + "&dest_lat=" + bike.latitude + "&dest_lng=" + bike.longitude; - const resp = await fetch(url, { headers: { "Authorization": "Bearer " + authToken } }); - const json = await resp.json(); - const d = json && json.data; - if (json.rtn_code !== 0 || !d || !d.points || !d.points.length) { - throw new Error((json && json.message) || "没有拿到路线"); - } + const d = await _requestNavRoute(gcj[1], gcj[0], bike.latitude, bike.longitude); - // GCJ02 折线 -> BD09,画在地图上 - const bdPoints = d.points.map(pt => { - const c = offsetCoord(pt[1], pt[0]); // offsetCoord(lat, lng) -> BD09 - return new BMapGL.Point(c.lng, c.lat); - }); - // 白色描边 + 蓝色主线:与「骑行区域边界」(#007AFF 细线) 区分开 - const casing = new BMapGL.Polyline(bdPoints, { - strokeColor: "#FFFFFF", strokeWeight: 11, - strokeOpacity: 0.95, strokeStyle: "solid" - }); - const line = new BMapGL.Polyline(bdPoints, { - strokeColor: "#0A84FF", strokeWeight: 6, - strokeOpacity: 1, strokeStyle: "solid" - }); - map.addOverlay(casing); - map.addOverlay(line); - _navOverlays.push(casing, line); + _nav = { + destCode: bike.code, follow: true, timer: null, watchId: null, + walking: [], remaining: [], endMarker: null, idx: 0, recomputing: false + }; + _applyRoute(d); + _navBtnText("结束"); - const endPoint = new BMapGL.Point(bdPoints[bdPoints.length - 1].lng, - bdPoints[bdPoints.length - 1].lat); - const endMarker = new BMapGL.Marker(endPoint); - map.addOverlay(endMarker); - _navOverlays.push(endMarker); - - if (typeof map.setViewport === "function") { - map.setViewport(bdPoints, { margins: [70, 70, 220, 70] }); - } - - _navBikeCode = bike.code; - const btnText = document.getElementById("bike-nav-btn-text"); - if (btnText) btnText.textContent = "结束"; - - const minutes = Math.max(1, Math.round(d.duration / 60)); - const distText = d.distance < 1000 - ? Math.round(d.distance) + " 米" - : (d.distance / 1000).toFixed(1) + " 公里"; - const first = (d.steps && d.steps[0] && d.steps[0].instruction) || ""; - const hint = first.replace(/<[^>]+>/g, "").slice(0, 14); + // 首次定位:压到屏幕下方 + 朝行进方向 + const start = _nav.ptsBD[0]; + const next = _nav.ptsBD[Math.min(1, _nav.ptsBD.length - 1)]; + _centerOnUser(start, _bearing(start, next)); if (bannerText) { - bannerText.textContent = "步行 " + distText + " · 约 " + minutes + " 分钟" - + (hint ? " " + hint : ""); + bannerText.textContent = d.distance < 1000 + ? "剩余 " + Math.round(d.distance) + " 米 · 约 " + + Math.max(1, Math.round(d.duration / 60)) + " 分钟" + : "剩余 " + (d.distance / 1000).toFixed(1) + " 公里 · 约 " + + Math.max(1, Math.round(d.duration / 60)) + " 分钟"; + } + + // 持续跟随 + if (navigator.geolocation) { + _nav.watchId = navigator.geolocation.watchPosition( + pos => _navTick(pos.coords), + err => console.warn("[导航] 定位失败", err.message), + { enableHighAccuracy: true, maximumAge: 3000, timeout: 10000 }); } } catch (err) { console.error("[导航] 失败", err); - if (banner) banner.hidden = true; + _navBanner(false); showToast("导航失败:" + (err && err.message ? err.message : "请稍后再试")); + if (_nav && !_nav.ptsBD) _nav = null; } finally { _navLoading = false; } } + // 地图拖动事件(只注册一次) + (function _bindNavMapEvents() { + const bind = () => { + if (!map || !map.addEventListener || map.__navBound) return; + map.__navBound = true; + map.addEventListener("dragstart", _onMapDragStart); + map.addEventListener("dragend", _onMapDragEnd); + }; + if (typeof map !== "undefined" && map) bind(); + else setTimeout(bind, 1500); + })(); + // 根据当前模式筛选车辆 function getFilteredBikes() { const allBikes = Object.values(markersData); diff --git a/templates/admin.html b/templates/admin.html index b63a4ea..fe1eea1 100644 --- a/templates/admin.html +++ b/templates/admin.html @@ -86,7 +86,7 @@ tr:hover{background:#3a3a3c}
卡片上的「步行 X 米 / 约 Y 分钟」用它算真实道路距离。
需服务端 AK + 已开通「步行路线规划(轻量)」;开了 SN 校验的要配套 SK。