feat: 地图导航——点「导航」画出到车的步行路线
## 后端 - walk_route.get_nav_route():一次拿齐 distance/duration/steps/points - steps[] 抽成 instruction(含高亮标签)、turn_type、distance、duration、path - 分段折线合并成整条,超过 1500 点按等间隔抽稀 - SN 签名与接口路径解耦(build_query 支持传 path),riding/driving 也可用 - 新增 /api/nav_route(需登录,按 IP 20 次/分钟限流),mode=walking|riding ## 前端 - 车辆卡片新增「导航」按钮:拉 /api/nav_route → GCJ02 折线转 BD09 → 白色描边 + 蓝色主线画在地图上(与 #007AFF 的骑行边界区分) → 加终点标记 → setViewport 自动适配视野 - 底部导航信息条:「步行 424 米 · 约 6 分钟 向东南方向出发…」,带「结束导航」 - 再点一次按钮 / 关闭卡片都会清掉路线 实测:校内站位与车直线相距约 310 米,百度步行 424 米 / 6 分钟,折线与路网贴合。 136 pytest + 29 node 全绿。
This commit is contained in:
@@ -266,6 +266,44 @@ def api_config():
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/api/nav_route")
|
||||||
|
def api_nav_route():
|
||||||
|
"""导航路线:距离/耗时/分段指引/整条折线(前端直接画到地图上)。
|
||||||
|
|
||||||
|
参数:origin_lat/origin_lng/dest_lat/dest_lng(GCJ02),mode=walking|riding
|
||||||
|
返回:{rtn_code:0, data:{distance, duration, points:[[lng,lat],...], steps:[...]}}
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||||
|
|
||||||
|
from routes.auth import _client_ip
|
||||||
|
from rate_limit import hit as rl_hit
|
||||||
|
# 导航比查卡片更重,按 IP 每分钟 20 次
|
||||||
|
if not rl_hit(("nav_route", _client_ip()), 20, 60):
|
||||||
|
return jsonify({"rtn_code": 429, "message": "导航请求过于频繁,请稍后再试"}), 429
|
||||||
|
|
||||||
|
try:
|
||||||
|
o_lat = float(request.args.get("origin_lat"))
|
||||||
|
o_lng = float(request.args.get("origin_lng"))
|
||||||
|
d_lat = float(request.args.get("dest_lat"))
|
||||||
|
d_lng = float(request.args.get("dest_lng"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
|
||||||
|
|
||||||
|
mode = (request.args.get("mode") or "walking").strip().lower()
|
||||||
|
if mode not in ("walking", "riding"):
|
||||||
|
mode = "walking"
|
||||||
|
|
||||||
|
import walk_route
|
||||||
|
data = walk_route.get_nav_route(o_lat, o_lng, d_lat, d_lng, api=mode)
|
||||||
|
if data.get("error"):
|
||||||
|
return jsonify({"rtn_code": 500, "message": data["error"]}), 200
|
||||||
|
response = jsonify({"rtn_code": 0, "data": data})
|
||||||
|
response.headers["Cache-Control"] = "private, max-age=30"
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/walk_route")
|
@bp.route("/api/walk_route")
|
||||||
def api_walk_route():
|
def api_walk_route():
|
||||||
"""步行路线:真实道路距离 + 步行耗时(百度轻量级路线规划)。
|
"""步行路线:真实道路距离 + 步行耗时(百度轻量级路线规划)。
|
||||||
|
|||||||
@@ -2752,3 +2752,41 @@
|
|||||||
border-color: var(--ui-line-strong) !important;
|
border-color: var(--ui-line-strong) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* 导航信息条:浮在底部扫码栏上方 */
|
||||||
|
.nav-banner {
|
||||||
|
position: fixed;
|
||||||
|
left: 12px;
|
||||||
|
right: 12px;
|
||||||
|
bottom: calc(84px + env(safe-area-inset-bottom, 0px));
|
||||||
|
z-index: 260;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: var(--bg-card, #fff);
|
||||||
|
border: 1px solid var(--border-color, #e5e5ea);
|
||||||
|
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.18);
|
||||||
|
}
|
||||||
|
.nav-banner[hidden] { display: none; }
|
||||||
|
.nav-banner-main { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||||
|
.nav-banner-icon { font-size: 16px; line-height: 1; }
|
||||||
|
.nav-banner-text {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-primary, #1c1c1e);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.nav-banner-stop {
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding: 6px 12px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: none;
|
||||||
|
background: var(--bg-secondary, #f2f2f7);
|
||||||
|
color: var(--text-primary, #1c1c1e);
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1378,6 +1378,121 @@
|
|||||||
} catch (e) { /* 保留直线估算 */ }
|
} catch (e) { /* 保留直线估算 */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== 导航:画「我 -> 车」的路线 ==========
|
||||||
|
let _navOverlays = [];
|
||||||
|
let _navBikeCode = 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 = "导航";
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopNavigation() {
|
||||||
|
_clearNavOverlays();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleNavigation() {
|
||||||
|
const bike = selectedBike;
|
||||||
|
if (!bike) return;
|
||||||
|
if (_navBikeCode && String(_navBikeCode) === String(bike.code)) {
|
||||||
|
stopNavigation(); // 再点一次 = 结束
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startNavigation(bike);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startNavigation(bike) {
|
||||||
|
if (_navLoading) return;
|
||||||
|
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||||
|
? autoLocationMarker.getPosition() : null;
|
||||||
|
if (!me) {
|
||||||
|
showToast("请先开启定位,才能规划路线");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!bike || !bike.latitude || !bike.longitude) {
|
||||||
|
showToast("这辆车没有坐标,无法导航");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_clearNavOverlays();
|
||||||
|
_navLoading = true;
|
||||||
|
const banner = document.getElementById("nav-banner");
|
||||||
|
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;
|
||||||
|
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) || "没有拿到路线");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
|
||||||
|
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);
|
||||||
|
if (bannerText) {
|
||||||
|
bannerText.textContent = "步行 " + distText + " · 约 " + minutes + " 分钟"
|
||||||
|
+ (hint ? " " + hint : "");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[导航] 失败", err);
|
||||||
|
if (banner) banner.hidden = true;
|
||||||
|
showToast("导航失败:" + (err && err.message ? err.message : "请稍后再试"));
|
||||||
|
} finally {
|
||||||
|
_navLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 根据当前模式筛选车辆
|
// 根据当前模式筛选车辆
|
||||||
function getFilteredBikes() {
|
function getFilteredBikes() {
|
||||||
const allBikes = Object.values(markersData);
|
const allBikes = Object.values(markersData);
|
||||||
@@ -3609,6 +3724,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function closeCard() {
|
function closeCard() {
|
||||||
|
try { if (typeof stopNavigation === "function") stopNavigation(); } catch (e) {}
|
||||||
const card = document.getElementById("bike-card");
|
const card = document.getElementById("bike-card");
|
||||||
const overlay = document.getElementById("card-overlay");
|
const overlay = document.getElementById("card-overlay");
|
||||||
card.classList.remove("show");
|
card.classList.remove("show");
|
||||||
|
|||||||
@@ -193,6 +193,15 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 导航信息条 -->
|
||||||
|
<div class="nav-banner" id="nav-banner" hidden>
|
||||||
|
<div class="nav-banner-main">
|
||||||
|
<span class="nav-banner-icon">🧭</span>
|
||||||
|
<span class="nav-banner-text" id="nav-banner-text">正在规划路线…</span>
|
||||||
|
</div>
|
||||||
|
<button class="nav-banner-stop" onclick="stopNavigation()">结束导航</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- 底部扫码栏 -->
|
<!-- 底部扫码栏 -->
|
||||||
<div class="scan-bar">
|
<div class="scan-bar">
|
||||||
<input class="scan-input" id="scan-input" type="number" pattern="[0-9]*" maxlength="5" placeholder="输入5位车牌号" />
|
<input class="scan-input" id="scan-input" type="number" pattern="[0-9]*" maxlength="5" placeholder="输入5位车牌号" />
|
||||||
@@ -720,6 +729,10 @@
|
|||||||
<span class="bike-code" id="card-code">#51287</span>
|
<span class="bike-code" id="card-code">#51287</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="bike-card-header-btns">
|
<div class="bike-card-header-btns">
|
||||||
|
<button class="bike-card-find-btn" id="bike-nav-btn" onclick="toggleNavigation()" title="导航到车">
|
||||||
|
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 11l19-9-9 19-2-8-8-2z"/></svg>
|
||||||
|
<span id="bike-nav-btn-text">导航</span>
|
||||||
|
</button>
|
||||||
<button class="bike-card-find-btn" id="bike-find-btn-header" onclick="findBike()" title="寻车">
|
<button class="bike-card-find-btn" id="bike-find-btn-header" onclick="findBike()" title="寻车">
|
||||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
|
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
|
||||||
<span>寻车</span>
|
<span>寻车</span>
|
||||||
|
|||||||
+79
-3
@@ -237,7 +237,7 @@ def estimate(origin_lat, origin_lng, dest_lat, dest_lng) -> dict:
|
|||||||
# ========== 百度接口 ==========
|
# ========== 百度接口 ==========
|
||||||
|
|
||||||
def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
|
def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
|
||||||
mode="official") -> dict:
|
mode="official", api="walking", with_steps=False) -> dict:
|
||||||
_throttle()
|
_throttle()
|
||||||
params = {
|
params = {
|
||||||
"ak": ak,
|
"ak": ak,
|
||||||
@@ -248,7 +248,8 @@ def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
|
|||||||
if sk:
|
if sk:
|
||||||
# 开了 SN 校验就必须带 timestamp(否则 status=2 timestamp is required when sn isset)
|
# 开了 SN 校验就必须带 timestamp(否则 status=2 timestamp is required when sn isset)
|
||||||
params["timestamp"] = int(time.time())
|
params["timestamp"] = int(time.time())
|
||||||
url = BASE_URL + "?" + build_query(params, sk, mode)
|
api_path = "/directionlite/v1/" + api
|
||||||
|
url = HOST + api_path + "?" + build_query(params, sk, mode, api_path)
|
||||||
resp = requests.get(url, timeout=REQUEST_TIMEOUT)
|
resp = requests.get(url, timeout=REQUEST_TIMEOUT)
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
@@ -263,7 +264,82 @@ def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
|
|||||||
duration = route.get("duration", result.get("duration"))
|
duration = route.get("duration", result.get("duration"))
|
||||||
if distance is None or duration is None:
|
if distance is None or duration is None:
|
||||||
raise RuntimeError(f"返回缺字段: {str(data)[:200]}")
|
raise RuntimeError(f"返回缺字段: {str(data)[:200]}")
|
||||||
return {"distance": int(distance), "duration": int(duration)}
|
out = {"distance": int(distance), "duration": int(duration)}
|
||||||
|
if with_steps:
|
||||||
|
out["steps"] = _parse_steps(route.get("steps") or [])
|
||||||
|
out["points"] = _merge_path(out["steps"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_steps(raw_steps) -> list:
|
||||||
|
"""把 steps[] 抽成前端要的最小集合(含折线)。"""
|
||||||
|
steps = []
|
||||||
|
for st in raw_steps:
|
||||||
|
if not isinstance(st, dict):
|
||||||
|
continue
|
||||||
|
points = []
|
||||||
|
for pair in str(st.get("path") or "").split(";"):
|
||||||
|
if not pair:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
lng_s, lat_s = pair.split(",")
|
||||||
|
points.append([float(lng_s), float(lat_s)])
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
steps.append({
|
||||||
|
"instruction": str(st.get("instruction") or ""),
|
||||||
|
"distance": int(st.get("distance") or 0),
|
||||||
|
"duration": int(st.get("duration") or 0),
|
||||||
|
"turn_type": str(st.get("turn_type") or ""),
|
||||||
|
"turn_type_id": st.get("turn_type_id"),
|
||||||
|
"points": points,
|
||||||
|
})
|
||||||
|
return steps
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_path(steps, max_points=1500) -> list:
|
||||||
|
"""把所有分段的折线接成一条,超长时按等间隔抽稀。"""
|
||||||
|
points = []
|
||||||
|
for st in steps:
|
||||||
|
pts = st.get("points") or []
|
||||||
|
if points and pts and points[-1] == pts[0]:
|
||||||
|
pts = pts[1:]
|
||||||
|
points.extend(pts)
|
||||||
|
if len(points) > max_points:
|
||||||
|
stride = max(1, len(points) // max_points)
|
||||||
|
sampled = points[::stride]
|
||||||
|
if sampled[-1] != points[-1]:
|
||||||
|
sampled.append(points[-1])
|
||||||
|
return sampled
|
||||||
|
return points
|
||||||
|
|
||||||
|
|
||||||
|
def get_nav_route(origin_lat, origin_lng, dest_lat, dest_lng, api="walking") -> dict:
|
||||||
|
"""导航用:一次拿齐距离/耗时/分段指引/整条折线。失败返回 error。"""
|
||||||
|
try:
|
||||||
|
o_lat, o_lng = float(origin_lat), float(origin_lng)
|
||||||
|
d_lat, d_lng = float(dest_lat), float(dest_lng)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return {"error": "坐标非法"}
|
||||||
|
|
||||||
|
ak = get_ak()
|
||||||
|
if not ak:
|
||||||
|
return {"error": "未配置百度 AK"}
|
||||||
|
|
||||||
|
sk = get_sk()
|
||||||
|
last_error = None
|
||||||
|
for mode in _sn_modes():
|
||||||
|
try:
|
||||||
|
got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode,
|
||||||
|
api=api, with_steps=True)
|
||||||
|
_SN_MODE[0] = mode
|
||||||
|
return {**got, "api": api}
|
||||||
|
except Exception as exc:
|
||||||
|
last_error = exc
|
||||||
|
text = str(exc)
|
||||||
|
if "211" not in text and "SN" not in text.upper():
|
||||||
|
break
|
||||||
|
return {"error": f"百度返回失败: {last_error}"}
|
||||||
|
|
||||||
|
|
||||||
def get_walk_route(origin_lat, origin_lng, dest_lat, dest_lng, use_cache=True) -> dict:
|
def get_walk_route(origin_lat, origin_lng, dest_lat, dest_lng, use_cache=True) -> dict:
|
||||||
|
|||||||
Reference in New Issue
Block a user