创建测试表
CREATE TABLE `t` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`longitude` decimal(16,8) DEFAULT NULL COMMENT '经度',
`latitude` decimal(16,8) DEFAULT NULL COMMENT '纬度',
`comment` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
插入测试数据
INSERT INTO `palmnew`.`t` (`id`, `longitude`, `latitude`, `comment`) VALUES (1, 120.25298300, 30.24810000, '天猫超市');
INSERT INTO `palmnew`.`t` (`id`, `longitude`, `latitude`, `comment`) VALUES (2, 120.25271300, 30.24854100, '老百姓健康药房');
INSERT INTO `palmnew`.`t` (`id`, `longitude`, `latitude`, `comment`) VALUES (3, 120.25398000, 30.24845900, '浙江农信');
INSERT INTO `palmnew`.`t` (`id`, `longitude`, `latitude`, `comment`) VALUES (4, 120.25188200, 30.24813900, '沙县小吃');
INSERT INTO `palmnew`.`t` (`id`, `longitude`, `latitude`, `comment`) VALUES (5, 120.25261000, 30.24871200, '瑞卡租车');
INSERT INTO `palmnew`.`t` (`id`, `longitude`, `latitude`, `comment`) VALUES (6, 120.25323900, 30.24739400, '豆腐泡泡');
INSERT INTO `palmnew`.`t` (`id`, `longitude`, `latitude`, `comment`) VALUES (7, 120.25208400, 30.24863000, '钱塘梨园');
测试数据示例图片
拾取坐标系统网址:拾取坐标系统 (baidu.com),以下为钱塘梨园(120.252089,30.248626)坐标点反查,测试数据中的坐标点都能在图中找到对应
以下以杭州铅笔酒店公寓(120.252722,30.248189)为中心点(实际工作中就是传进来的经度和纬度),查找附近离它最近的两个点,具体sql如下:
SELECT *
FROM t
WHERE 30.248189 > LATITUDE - 1
AND 30.248189 < LATITUDE + 1
AND 120.252722 > LONGITUDE - 1
AND 120.252722 < LONGITUDE + 1
ORDER BY ACOS(
SIN((LATITUDE * 3.1415) / 180) * SIN((30.248189 * 3.1415) / 180) +
COS((LATITUDE * 3.1415) / 180) * COS((30.248189 * 3.1415) / 180) *
COS((LONGITUDE * 3.1415) / 180 - (120.252722 * 3.1415) / 180)
) * 6380 ASC
LIMIT 2
结果:
可以看到,离杭州铅笔酒店公寓最近的两个点确实是天猫超市和老百姓健康药房。实际应用中一般是根据传进来的经纬度进行周边搜索,比如查询最近的餐馆、公园什么的