MySql geometry

通过 MySql geometry 存储用户经纬度, 搜索附近的人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- 创建表
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`longitude` decimal(10,7) DEFAULT NULL,
`latitude` decimal(10,7) DEFAULT NULL,
`geom` geometry DEFAULT NULL,
`desc` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- 写入数据
INSERT INTO `test`.`test`(`longitude`, `latitude`, `geom`, `desc`) VALUES (118.0824300, 24.4457900, ST_GeomFromText('POINT(118.082 24.4458)'), '福建省厦门市思明区民族路33号中共厦门市思明区委员会(寿山路南)');
INSERT INTO `test`.`test`(`longitude`, `latitude`, `geom`, `desc`) VALUES (118.0671500, 24.4446400, ST_GeomFromText('POINT(118.067 24.4446)'), '福建省厦门市思明区鹭江道西侧鼓浪屿');
INSERT INTO `test`.`test`(`longitude`, `latitude`, `geom`, `desc`) VALUES (118.1044670, 24.4350380, ST_GeomFromText('POINT(118.104 24.435)'), '福建省厦门市思明区思明南路422号厦门大学');
INSERT INTO `test`.`test`(`longitude`, `latitude`, `geom`, `desc`) VALUES (118.0826410, 24.4528320, ST_GeomFromText('POINT(118.083 24.4528)'), '福建省厦门市思明区思明南路189号中华城');
INSERT INTO `test`.`test`(`longitude`, `latitude`, `geom`, `desc`) VALUES (118.1727416, 24.4857075, ST_GeomFromText('POINT(118.173 24.4857)'), '福建省厦门市思明区金山路与吕岭路交汇处西北侧宝龙一城');

-- 查询与指定经纬度之间的距离
-- 宝龙一城
SELECT CONCAT(longitude, ',', latitude), `desc`, ST_DISTANCE_SPHERE(POINT(118.1727416, 24.4857075), geom) AS distance FROM test;
-- 梅园大厦
SELECT CONCAT(longitude, ',', latitude), `desc`, ST_DISTANCE_SPHERE(POINT(119.0052, 25.43842), geom) AS distance FROM test;

之前也有一种用于计算距离的SQL, 经过对比, 使用 geometry 更准确

1
2
3
-- 不推荐使用
SELECT CONCAT(longitude, ',', latitude), `desc`, GLength(GeomFromText(CONCAT('LineString(24.4857075 118.1727416,', latitude, ' ', longitude, ')'))) / 0.0000092592666666667 AS distance FROM test;
SELECT CONCAT(longitude, ',', latitude), `desc`, GLength(GeomFromText(CONCAT('LineString(25.43842 119.0052,', latitude, ' ', longitude, ')'))) / 0.0000092592666666667 AS distance FROM test;
0%