#!/usr/bin/env python3 # -*- coding: utf-8 -*- """校园地点:两类,用途严格分开。 1) poi(楼/兴趣点):只有一个坐标点,**不设范围**。 骑行起终点归属规则 = 最近的楼(哪个近就是哪个),标签为「XX附近」。 2) parking(停车点):只有一个坐标点 + 统计半径(默认 150m)。 **只用于订阅提醒**「这个点附近现在有没有车」,不参与起终点归属。 坐标系约定(与前端 coordtransform.js 同算法): - campus_locations 里的坐标统一为 GCJ02 —— 与上游车辆接口(bike_history)一致; - 管理面板在百度地图上点选得到 BD09,入库前先经 bd09togcj02 转换; - 上游 parkeArea 的坐标本身就是 GCJ02,**不要再转**,直接取点入库; - 本模块内置同款转换函数,供后端兜底/校验。 """ import json import math # POI 最近归属的距离上限(米)。仅作为「离谱保护」:校园尺度内单校区骑车 # 起终点必然落在最近楼栋数百米内;超过该值说明坐标异常,不给标签。 POI_MAX_MATCH_M = 3000 # 停车点默认统计半径(米):订阅时判断"这个点附近有没有车" DEFAULT_PARKING_RADIUS_M = 150 # ========== 坐标转换(与 static/js/coordtransform.js 同算法) ========== _X_PI = 3.14159265358979324 * 3000.0 / 180.0 _PI = 3.1415926535897932384626 _A = 6378245.0 _EE = 0.00669342162296594323 def _out_of_china(lng, lat): return (lng < 72.004 or lng > 137.8347) or (lat < 0.8293 or lat > 55.8271) def _transform_lat(lng, lat): ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + \ 0.1 * lng * lat + 0.2 * math.sqrt(abs(lng)) ret += (20.0 * math.sin(6.0 * lng * _PI) + 20.0 * math.sin(2.0 * lng * _PI)) * 2.0 / 3.0 ret += (20.0 * math.sin(lat * _PI) + 40.0 * math.sin(lat / 3.0 * _PI)) * 2.0 / 3.0 ret += (160.0 * math.sin(lat / 12.0 * _PI) + 320 * math.sin(lat * _PI / 30.0)) * 2.0 / 3.0 return ret def _transform_lng(lng, lat): ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + \ 0.1 * lng * lat + 0.1 * math.sqrt(abs(lng)) ret += (20.0 * math.sin(6.0 * lng * _PI) + 20.0 * math.sin(2.0 * lng * _PI)) * 2.0 / 3.0 ret += (20.0 * math.sin(lat * _PI) + 40.0 * math.sin(lat / 3.0 * _PI)) * 2.0 / 3.0 ret += (150.0 * math.sin(lng / 12.0 * _PI) + 300.0 * math.sin(lng / 30.0 * _PI)) * 2.0 / 3.0 return ret def bd09_to_gcj02(lng, lat): """百度 BD09 -> 国测局 GCJ02(车辆/计算坐标系)。""" x = lng - 0.0065 y = lat - 0.006 z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * _X_PI) theta = math.atan2(y, x) - 0.000003 * math.cos(x * _X_PI) return [z * math.cos(theta), z * math.sin(theta)] def gcj02_to_bd09(lng, lat): """GCJ02 -> BD09(需要回显到百度地图时用)。""" z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * _X_PI) theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * _X_PI) return [z * math.cos(theta) + 0.0065, z * math.sin(theta) + 0.006] def wgs84_to_gcj02(lng, lat): """WGS84(GPS 原始)-> GCJ02。 用途:浏览器 `navigator.geolocation` 给的是 WGS84,上游车辆/停车区是 GCJ02,两者直接比较会差 500 米左右。算法与 static/js/coordtransform.js 的 `wgs84togcj02` 完全一致。 """ lng, lat = float(lng), float(lat) if _out_of_china(lng, lat): return [lng, lat] dlat = _transform_lat(lng - 105.0, lat - 35.0) dlng = _transform_lng(lng - 105.0, lat - 35.0) radlat = lat / 180.0 * _PI magic = math.sin(radlat) magic = 1 - _EE * magic * magic sqrtmagic = math.sqrt(magic) dlat = (dlat * 180.0) / ((_A * (1 - _EE)) / (magic * sqrtmagic) * _PI) dlng = (dlng * 180.0) / (_A / sqrtmagic * math.cos(radlat) * _PI) return [lng + dlng, lat + dlat] def gcj02_to_wgs84(lng, lat): """GCJ02 -> WGS84(把内部算出的点转回浏览器/上游使用的坐标系)。 用不动点迭代反解(4 轮即收敛到厘米级):先按 GCJ02 猜一个 WGS84,再用 正向转换量修正。比 coordtransform 的「对称偏移」反解精度更高 —— 后者在 本地实测约 1 米误差,会吃到停车区边界的判断上。 """ lng, lat = float(lng), float(lat) if _out_of_china(lng, lat): return [lng, lat] w_lng, w_lat = lng, lat for _ in range(4): g_lng, g_lat = wgs84_to_gcj02(w_lng, w_lat) w_lng -= (g_lng - lng) w_lat -= (g_lat - lat) return [w_lng, w_lat] # ========== 几何工具 ========== def haversine_m(lat1, lng1, lat2, lng2): """球面距离(米)。""" try: lat1, lng1, lat2, lng2 = float(lat1), float(lng1), float(lat2), float(lng2) except (TypeError, ValueError): return float("inf") r = 6371000.0 p1, p2 = math.radians(lat1), math.radians(lat2) dphi = math.radians(lat2 - lat1) 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 point_in_polygon(lat, lng, polygon): """ray casting 判断点是否在多边形内。polygon = [[lat,lng],...](兼容旧数据)""" inside = False n = len(polygon) j = n - 1 for i in range(n): yi, xi = polygon[i][0], polygon[i][1] yj, xj = polygon[j][0], polygon[j][1] if ((yi > lat) != (yj > lat)) and \ (lng < (xj - xi) * (lat - yi) / (yj - yi + 1e-12) + xi): inside = not inside j = i return inside def parse_polygon(raw): """解析 polygon JSON -> [[lat,lng],...];非法返回 [](仅兼容历史数据)。""" if not raw: return [] try: data = json.loads(raw) if isinstance(raw, str) else raw except (TypeError, ValueError): return [] if not isinstance(data, list): return [] pts = [] for p in data: try: if isinstance(p, (list, tuple)) and len(p) >= 2: pts.append([float(p[0]), float(p[1])]) except (TypeError, ValueError): continue return pts # ========== 地点库 ========== def load_locations(conn=None, kind=None): """读取地点;kind 可选 'poi' / 'parking' 过滤。""" own = conn is None if own: from db import get_db conn = get_db() sql = ("SELECT id, name, kind, latitude, longitude, radius, polygon " "FROM campus_locations") params = () if kind: sql += " WHERE kind = ?" params = (kind,) sql += " ORDER BY id" try: rows = conn.execute(sql, params).fetchall() except Exception: rows = [] if own: conn.close() return [dict(r) for r in rows] def get_location(location_id, conn=None): own = conn is None if own: from db import get_db conn = get_db() try: row = conn.execute( "SELECT id, name, kind, latitude, longitude, radius, polygon " "FROM campus_locations WHERE id = ?", (location_id,) ).fetchone() except Exception: row = None if own: conn.close() return dict(row) if row else None def nearest_poi(lat, lng, locations=None): """返回 (最近的楼名, 距离米);没有楼或超出保护距离返回 (None, None)。 起终点归属只用这个函数 —— 「哪个近就是哪个」,不依赖任何手动范围。 """ if lat is None or lng is None: return None, None try: lat, lng = float(lat), float(lng) except (TypeError, ValueError): return None, None pois = [l for l in (locations if locations is not None else load_locations(kind="poi")) if l.get("kind", "poi") == "poi" and l.get("latitude") is not None and l.get("longitude") is not None] if not pois: return None, None best, best_d = None, float("inf") for p in pois: d = haversine_m(lat, lng, p["latitude"], p["longitude"]) if d < best_d: best, best_d = p["name"], d if best is None or best_d > POI_MAX_MATCH_M: return None, None return best, best_d def resolve_location_label(lat, lng, locations=None): """坐标(GCJ02) -> 「博学楼附近」标签(最近的楼);无楼或超距返回 None。""" name, _ = nearest_poi(lat, lng, locations) return f"{name}附近" if name else None def _num(value, default=0.0): """安全转数字。注意不能用 `value or default`:0 是合法值(如 status=0=可用)。""" if value is None or value == "": return default try: return float(value) except (TypeError, ValueError): return default def bikes_near_parking(points, loc): """统计某个停车点附近的车辆(订阅用)。 points: [{bike_code, latitude, longitude, state, status, electric}, ...] (调用方保证是每辆车最近一条记录) loc: campus_locations 行(kind='parking',按坐标 + 半径判断) 返回: {"available": n, "low": n, "total": n, "codes": [可用车牌...]} """ available, low, total, codes = 0, 0, 0, [] try: lat0, lng0 = float(loc.get("latitude")), float(loc.get("longitude")) except (TypeError, ValueError): return {"available": 0, "low": 0, "total": 0, "codes": []} radius = loc.get("radius") try: radius = float(radius) if radius else DEFAULT_PARKING_RADIUS_M except (TypeError, ValueError): radius = DEFAULT_PARKING_RADIUS_M # 兼容历史多边形停车区:点在多边形内也算 poly = parse_polygon(loc.get("polygon")) for p in points: try: plat, plng = float(p.get("latitude")), float(p.get("longitude")) except (TypeError, ValueError): continue hit = False if lat0 is not None and lng0 is not None: hit = haversine_m(plat, plng, lat0, lng0) <= radius if not hit and len(poly) >= 3: hit = point_in_polygon(plat, plng, poly) if not hit: continue total += 1 state = int(_num(p.get("state"), 1)) status = int(_num(p.get("status"), 1)) electric = _num(p.get("electric"), 0.0) # 上游语义:state=1 且 status=1 才是「使用中」;空闲可用 = state=1 且 status!=1 if state == 1 and status != 1 and electric >= 20: available += 1 codes.append(str(p.get("bike_code") or "")) elif state == 10 or electric < 20: low += 1 return {"available": available, "low": low, "total": total, "codes": codes} # ========== 车型判定(与前端 map.js getBikeKind 同一套规则) ========== BIKE_KIND_LABELS = {"small": "小车", "big": "大车", "red": "红车"} def bike_kind(code) -> str: """按编号判定车型: - 超过 5 位(如 30000193):新引进红色外观车 → red - 5 位取前三位号段:511 及以上=big(大车),510 及以下=small(小车) """ digits = "".join(ch for ch in str(code or "") if ch.isdigit()) if len(digits) > 5: return "red" if not digits: return "small" num = int(digits) series = num // (10 ** (len(digits) - 3)) if len(digits) >= 5 else num return "big" if series >= 511 else "small" def parking_candidates(points, loc, kinds=None, min_electric=0, max_electric=100, sort_by="electric_desc", limit=20): """列出某停车点附近**空闲可用**车辆候选,按规则排序后返回前 limit 个。 points: 每辆车最近一条采集点(GCJ02) kinds: 允许的车型集合(None/空 = 不限制) 返回: [{"bike_code","kind","kind_label","electric","distance"}, ...] """ if loc is None or loc.get("latitude") is None or loc.get("longitude") is None: return [] try: lat0, lng0 = float(loc["latitude"]), float(loc["longitude"]) except (TypeError, ValueError): return [] try: radius = float(loc.get("radius") or DEFAULT_PARKING_RADIUS_M) except (TypeError, ValueError): radius = DEFAULT_PARKING_RADIUS_M kind_filter = set(kinds or []) or {"small", "big", "red"} try: min_e = float(min_electric if min_electric is not None else 0) max_e = float(max_electric if max_electric is not None else 100) except (TypeError, ValueError): min_e, max_e = 0.0, 100.0 out = [] for p in points: try: plat, plng = float(p.get("latitude")), float(p.get("longitude")) except (TypeError, ValueError): continue electric = _num(p.get("electric"), 0.0) state = int(_num(p.get("state"), 1)) status = int(_num(p.get("status"), 1)) dist = haversine_m(plat, plng, lat0, lng0) if dist > radius: continue # 只挑「空闲可用」:state=1 且 status!=1;电量落在设定区间 if not (state == 1 and status != 1): continue if electric < min_e or electric > max_e: continue k = bike_kind(p.get("bike_code")) if k not in kind_filter: continue out.append({ "bike_code": str(p.get("bike_code") or ""), "kind": k, "kind_label": BIKE_KIND_LABELS.get(k, k), "electric": round(electric, 1), "distance": round(dist), }) if sort_by == "electric_asc": out.sort(key=lambda x: (x["electric"], x["distance"])) elif sort_by == "distance_asc": out.sort(key=lambda x: (x["distance"], -x["electric"])) else: # electric_desc(默认:电量从高到低) out.sort(key=lambda x: (-x["electric"], x["distance"])) try: limit = max(1, int(limit or 20)) except (TypeError, ValueError): limit = 20 return out[:limit] # 兼容旧调用名 def bikes_near_location(points, loc): return bikes_near_parking(points, loc)