| 函數 | 說明 |
ll_to_earth(lat, lng) | 經緯度 → earth 類型(地球表面點) |
earth_distance(pt1, pt2) | 兩點大圓距離(米) |
earth_box(center, radius_m) | 返回立方體盒子,供 @> 索引掃描 |
@> (cube 操作符) | 判斷點是否在盒子內 |
實戰查詢
按距離排序(最近的前 10 條)
SELECT id, name,
earth_distance(ll_to_earth(:my_lat, :my_lng), ll_to_earth(lat, lng)) AS dist_m
FROM events
ORDER BY dist_m
LIMIT 10;
查找半徑 5 公里內記錄(利用索引)
-- 先建索引
CREATE INDEX idx_events_geo ON events USING GIST (ll_to_earth(lat, lng));
-- 查詢
SELECT id, name
FROM events
WHERE earth_box(ll_to_earth(:my_lat, :my_lng), 5000) @> ll_to_earth(lat, lng);
earth_box 返回的盒子比真實圓略大(外接矩形),查詢後可選再用 earth_distance 精確過濾一次。
數據類型建議
經緯度用 DOUBLE PRECISION(8 字節),精度約 10-15 度(亞毫米級),完全足夠。避免用 FLOAT 或自定義類型,以免索引/驅動程序兼容問題。
總結
僅用標準 DOUBLE PRECISION + 兩個擴展 + 一個 GIST 索引,即可構建高性能地理位置服務(附近餐廳、打車派單、地理圍欄等),無需重型 PostGIS,極適合中小型項目快速交付。
copyright ©
萬盛學電腦網 all rights reserved