使用MySQL的geometry型別處理經緯度距離問題

Shawn發表於2019-01-30

建表

CREATE TABLE `map` (
  `id` int(11) NOT NULL,
  `address` varchar(255) NOT NULL DEFAULT ``,
  `location` geometry NOT NULL,
  PRIMARY KEY (`id`),
  SPATIAL KEY `idx_location` (`location`)
)

插入

INSERT INTO map (id, address, location) VALUES (1, `somewhere`, ST_GeomFromText(`POINT(121.366961 31.190049)`));

注意必須使用 ST_GeomFromText 函式,且 POINT() 裡面是:經度+空格+緯度

查詢

1. 檢視經緯度

SELECT address, ST_AsText(location) AS location FROM map;

2. 計算兩點之間的距離

SELECT ST_Distance_Sphere(POINT(121.590347, 31.388094),location) AS distant FROM map;

算出來的結果,單位是米
注意現在POINT()裡面經緯度之間是逗號分隔的

3. 查詢距離小於1000m的地點,並由遠及近排序

SELECT id, address, ST_Distance_Sphere(POINT(121.590347, 31.388094),location) AS distant FROM map WHERE ST_Distance_Sphere(POINT(121.590347, 31.388094),location) < 1000 ORDER BY distant;

相關文章