mysql 查詢一個地點(經緯度) 附近N公里內的數據。(根據一個地點的經緯度查詢這個地點方圓幾公里內的數據)
1.創建測試表
CREATE TABLE `location` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`longitude` decimal(13,10) NOT NULL,
`latitude` decimal(13,10) NOT NULL,
PRIMARY KEY (`id`),
KEY `long_lat_index` (`longitude`,`latitude`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.插入測試數據
insert into location(name,longitude,latitude) values
('廣州東站',113.332264,23.156206),
('林和西',113.330611,23.147234),
('天平架',113.328095,23.165376);
3.搜尋1公里內的數據
搜尋點坐標:時代廣場 113.323568, 23.146436
6370.996公里為地球的半徑
計算球面兩點坐標距離公式:
C = sin(MLatA)sin(MLatB)cos(MLonA-MLonB) + cos(MLatA)cos(MLatB)
Distance = RArccos(C)*Pi180
根據計算公式得到查詢語句如下:
select * from `location` where (
acos(
sin(([#latitude#]*3.1415)/180) * sin((latitude*3.1415)/180) +
cos(([#latitude#]*3.1415)/180) * cos((latitude*3.1415)/180) * cos(([#longitude#]*3.1415)/180 - (longitude*3.1415)/180)
)*6370.996
)<=1;
執行查詢:
SELECT * FROM `location` WHERE (ACOS(SIN((23.146436*3.1415)/180) * SIN((latitude*3.1415)/180) + COS((23.146436*3.1415)/180) * COS((latitude*3.1415)/180) * COS((113.323568*3.1415)/180 - (longitude*3.1415)/180))*6370.996)<=1;