mysql空间函数计算坐标距离
有一张表,表中有每个人所在位置及经纬度,现在求表中所有人离指定经纬度的位置。
drop table if exists `teacher`; create table `teacher` ( `id` int not null auto_increment, `name` varchar(50) character set utf8 collate utf8_general_ci not null, `longitude` decimal(9, 6) null default null, `latitude` decimal(9, 6) null default null, `address` varchar(100) character set utf8mb4 collate utf8mb4_general_ci null default null, primary key (`id`) using btree ) engine = innodb auto_increment = 4 character set = utf8mb4 collate = utf8mb4_general_ci row_format = dynamic; -- ---------------------------- -- records of teacher -- ---------------------------- insert into `teacher` values (1, '张三', 116.397755, 39.903179, '天安门'); insert into `teacher` values (2, '李四', 116.397029, 39.917840, '故宫'); insert into `teacher` values (3, '王五', 116.190595, 39.876665, '园博园'); insert into `teacher` values (4, '赵六', 116.410829, 39.881983, '天坛公园');
假设本人目前在人民 大会堂,经度116.393823,纬度39.905024,现在要查询表中四个人距本人多少米。
现在用mysql提供的空间函数演示计算。
1. st_distance函数
st_distance函数计算:
select *, round( st_distance ( point ( longitude, latitude ), point ( 116.393823, 39.905024 ))* 111195, 2 ) dis from teacher
2. st_distance_sphere函数
st_distance_sphere函数计算:
select *, round( st_distance_sphere ( point ( 116.393823, 39.905024 ), point ( `longitude`, `latitude` ) ), 2 ) dis from teacher order by dis
比较两种查询结果,距离有不小的偏差。因为第一种st_distance函数计算的是两点间的度,所以在计算出度数后再乘以111195得出米,而每度的长度并不一致所以有误差。第二种st_distance_sphere函数直接计算两点间的距离,更加准确。
对比下地图测距:
3. st_distance_sphere取值范围问题(极易踩坑)
在st_distance_sphere 函数中使用point计算经纬度时有限制取值范围,其中纬度为大于等于-90度小于等于90度,而经度却是大于-180度且小于等于180度。
如下所示:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论