- 直线距离 ≥ 20km 时卡片不再显示「导航」按钮(距离格同隐藏), 正在导航该车时仍保留「结束」 - startNavigation 兜底静默返回;_requestNavRoute 识别 too_far 不弹报错 - 后端 get_nav_route 调百度前按上限拦截(步行/骑行 200km、驾车 500km), 返回 error_kind=too_far 与中文提示;百度的 "the distance of path must less then 200Km" 也翻成中文 - 顺手修 get_nav_route 里 float(d_lng) -> float(dest_lng) 的笔误 (会让整个函数抛 UnboundLocalError) - 卡片顶部按钮是否收成纯图标改为实测:车牌被 ellipsis 截断才收, 同时考虑车牌长度与屏宽;resize 与「导航/结束」换字后重新测量 - 「寻车」放大镜换成描边铃铛 SVG,title 改为「寻车(响铃)」 测试:136 pytest + 30 node 全绿
420 lines
15 KiB
Python
420 lines
15 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""百度「步行路线规划(轻量)」:真实道路距离 + 步行耗时。
|
||
|
||
为什么要它:卡片原来只会拿直线距离 ÷ 80 米/分钟估时间,绕楼绕围墙时明显偏乐观。
|
||
百度轻量级路线规划接口(directionlite)直接给 `distance`(米)和 `duration`(秒),
|
||
且支持 `coord_type=gcj02` —— 正好和上游车辆坐标同一套,不用转换。
|
||
|
||
配额与限流(2026-11 实测控制台:0.5 万次/天,3 QPS):
|
||
- 结果按「起点+终点」四舍五入到 4 位小数(约 10 米)入库缓存 7 天;
|
||
- 进程内做 3 QPS 节流(保守取 350ms 间隔);
|
||
- 任何失败(没配 AK / 240 APP 服务被禁用 / 超时 / 配额耗尽)都退回本地估算,
|
||
绝不让卡片空着。
|
||
|
||
配置(缺一即走估算):
|
||
- 环境变量 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK
|
||
- 或 server_config.json 里的 "baidu_route_ak" / "baidu_route_sk"
|
||
注意:
|
||
- 必须用**服务端**类型的 AK,且开通「步行路线规划(轻量)」;
|
||
- 页面里那个浏览器端 AK 调这个接口会返回 {"status":240,"message":"APP 服务被禁用"}(已实测);
|
||
- 若该 AK 在控制台开了「SN 校验」,请求必须带 sn(否则 211),所以需要配套的 SK,
|
||
见 `_build_query()`。
|
||
"""
|
||
import hashlib
|
||
import json
|
||
import math
|
||
import os
|
||
import sqlite3
|
||
import threading
|
||
import time
|
||
from pathlib import Path
|
||
from urllib.parse import quote, quote_plus, urlencode
|
||
|
||
import requests
|
||
|
||
HOST = "https://api.map.baidu.com"
|
||
PATH = "/directionlite/v1/walking"
|
||
BASE_URL = HOST + PATH
|
||
CACHE_PATH = Path(__file__).parent / "walk_cache.db"
|
||
CACHE_TTL_SECONDS = 7 * 24 * 3600
|
||
# 坐标精度:4 位小数 ≈ 11 米,够用且能显著提高缓存命中率
|
||
COORD_PRECISION = 4
|
||
# 3 QPS 配额,保守按 350ms 一次
|
||
MIN_INTERVAL_SECONDS = 0.35
|
||
REQUEST_TIMEOUT = 6
|
||
|
||
# 本地估算参数(百度不可用时兜底)
|
||
DETOUR_FACTOR = 1.3 # 直线 -> 道路的经验绕行系数
|
||
WALK_METERS_PER_MIN = 75.0 # 4.5 km/h
|
||
|
||
_lock = threading.Lock()
|
||
_last_call_at = [0.0]
|
||
_cache_ready = [False]
|
||
|
||
|
||
# ========== 配置 ==========
|
||
|
||
def _server_config() -> dict:
|
||
try:
|
||
path = Path(__file__).parent / "server_config.json"
|
||
if path.exists():
|
||
return json.loads(path.read_text("utf-8"))
|
||
except Exception:
|
||
pass
|
||
return {}
|
||
|
||
|
||
def get_ak() -> str:
|
||
"""服务端 AK:环境变量优先,其次 server_config.json 的 baidu_route_ak。"""
|
||
env = (os.environ.get("BAIDU_ROUTE_AK") or "").strip()
|
||
if env:
|
||
return env
|
||
return str(_server_config().get("baidu_route_ak") or "").strip()
|
||
|
||
|
||
def get_sk() -> str:
|
||
"""SN 校验用的 SK(私钥)。AK 未开 SN 校验时可以留空。"""
|
||
env = (os.environ.get("BAIDU_ROUTE_SK") or "").strip()
|
||
if env:
|
||
return env
|
||
return str(_server_config().get("baidu_route_sk") or "").strip()
|
||
|
||
|
||
def is_enabled() -> bool:
|
||
return bool(get_ak())
|
||
|
||
|
||
def save_credentials(ak: str, sk: str = None) -> bool:
|
||
"""把 AK/SK 写进 server_config.json(管理端弹窗用)。
|
||
|
||
sk 传 None 表示保持原值不动;传 "" 表示清空。
|
||
"""
|
||
path = Path(__file__).parent / "server_config.json"
|
||
try:
|
||
cfg = {}
|
||
if path.exists():
|
||
cfg = json.loads(path.read_text("utf-8")) or {}
|
||
cfg["baidu_route_ak"] = (ak or "").strip()
|
||
if sk is not None:
|
||
cfg["baidu_route_sk"] = (sk or "").strip()
|
||
path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
return True
|
||
except Exception as exc:
|
||
print(f"[步行路线] 保存 AK/SK 失败: {exc}")
|
||
return False
|
||
|
||
|
||
def masked_credentials() -> dict:
|
||
"""给管理端回显用:AK 全量(管理员要看),SK 只回显尾 4 位。"""
|
||
ak = get_ak()
|
||
sk = get_sk()
|
||
return {"ak": ak, "sk_set": bool(sk),
|
||
"sk_tail": sk[-4:] if sk else "", "enabled": bool(ak)}
|
||
|
||
|
||
def build_query(params: dict, sk: str = "", mode: str = "official",
|
||
path: str = None) -> str:
|
||
"""按百度 SN 规则拼查询串。
|
||
|
||
百度官方样例(geocoder/v2 那份)与社区常见写法算出的 sn 不一致,
|
||
没有 SK 无法判定哪个对,所以两种都实现,由上层自动试:
|
||
- official:quote("path?query", safe=...) -> 追加 SK -> quote_plus -> md5
|
||
- simple :urlencode(按 key 升序, safe="") -> md5("path?query" + SK)
|
||
"""
|
||
api_path = path or PATH # SN 是绑路径的,换接口必须换路径
|
||
items = sorted((k, v) for k, v in params.items() if k != "sn")
|
||
if mode == "simple":
|
||
query = urlencode(items, encoding="utf-8", safe="")
|
||
if not sk:
|
||
return query
|
||
digest = hashlib.md5((api_path + "?" + query + sk).encode("utf-8")).hexdigest()
|
||
return query + "&sn=" + digest
|
||
|
||
raw_query = "&".join(f"{k}={v}" for k, v in items)
|
||
encoded = quote(api_path + "?" + raw_query, safe="/:=&?#+!$,;'@()*[]")
|
||
query = encoded[len(api_path) + 1:]
|
||
if not sk:
|
||
return query
|
||
digest = hashlib.md5(quote_plus(encoded + sk).encode("utf-8")).hexdigest()
|
||
return query + "&sn=" + digest
|
||
|
||
|
||
# 记住哪种 SN 算法能通,避免每次先撞一次 211
|
||
_SN_MODE = [None]
|
||
|
||
|
||
def _sn_modes():
|
||
if _SN_MODE[0]:
|
||
other = "simple" if _SN_MODE[0] != "simple" else "official"
|
||
return [_SN_MODE[0], other]
|
||
return ["official", "simple"]
|
||
|
||
|
||
# ========== 缓存 ==========
|
||
|
||
def _conn():
|
||
conn = sqlite3.connect(CACHE_PATH, timeout=5)
|
||
if not _cache_ready[0]:
|
||
conn.execute("""
|
||
CREATE TABLE IF NOT EXISTS walk_cache (
|
||
key TEXT PRIMARY KEY,
|
||
distance_m INTEGER NOT NULL,
|
||
duration_s INTEGER NOT NULL,
|
||
created_at REAL NOT NULL
|
||
)
|
||
""")
|
||
conn.commit()
|
||
_cache_ready[0] = True
|
||
return conn
|
||
|
||
|
||
def _cache_key(o_lat, o_lng, d_lat, d_lng) -> str:
|
||
p = COORD_PRECISION
|
||
return "%.*f,%.*f|%.*f,%.*f" % (p, o_lat, p, o_lng, p, d_lat, p, d_lng)
|
||
|
||
|
||
def _cache_get(key):
|
||
try:
|
||
conn = _conn()
|
||
row = conn.execute(
|
||
"SELECT distance_m, duration_s, created_at FROM walk_cache WHERE key = ?",
|
||
(key,)).fetchone()
|
||
conn.close()
|
||
if not row:
|
||
return None
|
||
if time.time() - float(row[2]) > CACHE_TTL_SECONDS:
|
||
return None
|
||
return {"distance": int(row[0]), "duration": int(row[1])}
|
||
except Exception as exc:
|
||
print(f"[步行路线] 读缓存失败: {exc}")
|
||
return None
|
||
|
||
|
||
def _cache_put(key, distance_m, duration_s):
|
||
try:
|
||
conn = _conn()
|
||
conn.execute(
|
||
"INSERT OR REPLACE INTO walk_cache (key, distance_m, duration_s, created_at) "
|
||
"VALUES (?, ?, ?, ?)", (key, int(distance_m), int(duration_s), time.time()))
|
||
conn.commit()
|
||
conn.close()
|
||
except Exception as exc:
|
||
print(f"[步行路线] 写缓存失败: {exc}")
|
||
|
||
|
||
# ========== 节流 ==========
|
||
|
||
def _throttle():
|
||
"""全局 3 QPS 上限(百度给的并发就是 3)。"""
|
||
with _lock:
|
||
wait = _last_call_at[0] + MIN_INTERVAL_SECONDS - time.time()
|
||
if wait > 0:
|
||
time.sleep(wait)
|
||
_last_call_at[0] = time.time()
|
||
|
||
|
||
# ========== 估算兜底 ==========
|
||
|
||
# 百度各出行方式的距离上限(公里)。步行超 200km 会直接报
|
||
# "the distance of path must less then 200Km",先自己挡掉。
|
||
_MAX_ROUTE_KM = {"walking": 200, "riding": 200, "driving": 500}
|
||
|
||
|
||
def _haversine_m(lat1, lng1, lat2, lng2) -> float:
|
||
"""两点球面距离(米)。"""
|
||
r = 6371000.0
|
||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||
dphi = p2 - p1
|
||
dlmb = math.radians(lng2 - lng1)
|
||
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
|
||
return 2 * r * math.asin(math.sqrt(a))
|
||
|
||
|
||
def estimate(origin_lat, origin_lng, dest_lat, dest_lng) -> dict:
|
||
"""直线 → 道路经验估算。永远有返回值。"""
|
||
try:
|
||
lat1, lng1, lat2, lng2 = map(float, (origin_lat, origin_lng, dest_lat, dest_lng))
|
||
except (TypeError, ValueError):
|
||
return {"distance": 0, "duration": 0, "source": "none"}
|
||
r = 6371000.0
|
||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||
dphi = p2 - p1
|
||
dlmb = math.radians(lng2 - lng1)
|
||
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
|
||
straight = 2 * r * math.asin(math.sqrt(a))
|
||
distance = int(round(straight * DETOUR_FACTOR))
|
||
duration = int(round(max(distance, 1) / WALK_METERS_PER_MIN * 60))
|
||
return {"distance": distance, "duration": duration, "straight": int(round(straight)),
|
||
"source": "estimate"}
|
||
|
||
|
||
# ========== 百度接口 ==========
|
||
|
||
def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
|
||
mode="official", api="walking", with_steps=False) -> dict:
|
||
_throttle()
|
||
params = {
|
||
"ak": ak,
|
||
"origin": f"{origin_lat:.6f},{origin_lng:.6f}",
|
||
"destination": f"{dest_lat:.6f},{dest_lng:.6f}",
|
||
"coord_type": "gcj02", # 入参坐标系:上游车辆坐标就是 GCJ02
|
||
# 关键:coord_type 只管"输入",折线默认按 BD09 返回(ret_coordtype 默认 bd09ll)。
|
||
# 不显式指定的话,前端再把 BD09 当 GCJ02 转一次,整体会偏 500~900 米。
|
||
"ret_coordtype": "gcj02",
|
||
}
|
||
if sk:
|
||
# 开了 SN 校验就必须带 timestamp(否则 status=2 timestamp is required when sn isset)
|
||
params["timestamp"] = int(time.time())
|
||
api_path = "/directionlite/v1/" + api
|
||
url = HOST + api_path + "?" + build_query(params, sk, mode, api_path)
|
||
resp = requests.get(url, timeout=REQUEST_TIMEOUT)
|
||
resp.raise_for_status()
|
||
data = resp.json()
|
||
status = data.get("status")
|
||
if status != 0:
|
||
raise RuntimeError(f"status={status} message={data.get('message')}")
|
||
result = data.get("result") or {}
|
||
# directionlite 正常返回 result.routes[0].{distance,duration};
|
||
# 少数版本把 distance/duration 直接挂在 result 上,一并兜住。
|
||
route = (result.get("routes") or [{}])[0]
|
||
distance = route.get("distance", result.get("distance"))
|
||
duration = route.get("duration", result.get("duration"))
|
||
if distance is None or duration is None:
|
||
raise RuntimeError(f"返回缺字段: {str(data)[:200]}")
|
||
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": "坐标非法"}
|
||
|
||
# 百度步行/骑行路线对距离有上限(超过会返回 status=2 的英文报错),
|
||
# 先自己算直线距离挡掉,别把 "the distance of path must less then 200Km" 抛给用户。
|
||
max_km = _MAX_ROUTE_KM.get(api, 200)
|
||
if max_km:
|
||
straight_km = _haversine_m(o_lat, o_lng, d_lat, d_lng) / 1000.0
|
||
if straight_km > max_km:
|
||
return {"error": f"距离太远(约 {straight_km:.0f} 公里),不提供{api}导航",
|
||
"error_kind": "too_far"}
|
||
|
||
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
|
||
msg = str(last_error)
|
||
if "200Km" in msg or "too long" in msg.lower():
|
||
return {"error": "距离太远,无法规划路线", "error_kind": "too_far"}
|
||
return {"error": f"百度返回失败: {last_error}"}
|
||
|
||
|
||
def get_walk_route(origin_lat, origin_lng, dest_lat, dest_lng, use_cache=True) -> dict:
|
||
"""返回 {distance(米), duration(秒), source: baidu|cache|estimate}。
|
||
|
||
source=cache 也代表数据来自百度(命中缓存)。
|
||
"""
|
||
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 estimate(origin_lat, origin_lng, dest_lat, dest_lng)
|
||
|
||
if not (math.isfinite(o_lat) and math.isfinite(o_lng)
|
||
and math.isfinite(d_lat) and math.isfinite(d_lng)):
|
||
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||
|
||
key = _cache_key(o_lat, o_lng, d_lat, d_lng)
|
||
if use_cache:
|
||
hit = _cache_get(key)
|
||
if hit:
|
||
return {**hit, "source": "cache"}
|
||
|
||
ak = get_ak()
|
||
if not ak:
|
||
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||
|
||
sk = get_sk()
|
||
got = None
|
||
last_error = None
|
||
for mode in _sn_modes():
|
||
try:
|
||
got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode)
|
||
_SN_MODE[0] = mode # 记住能通的算法
|
||
break
|
||
except Exception as exc:
|
||
last_error = exc
|
||
text = str(exc)
|
||
# 只有 SN 相关错误才值得换算法重试,其余(配额/超时)直接退回估算
|
||
if "211" not in text and "SN" not in text.upper():
|
||
break
|
||
if got is None:
|
||
print(f"[步行路线] 百度调用失败,退回估算: {last_error}")
|
||
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||
|
||
_cache_put(key, got["distance"], got["duration"])
|
||
return {**got, "source": "baidu"}
|