MySQL计算经纬度距离
现在开发计算距离自身所在地到目的地的距离算是一个比较常见的需求,基本上都是通过两地的经纬度查询直线距离,忘记之前自己有没有写过,反正印象都是通过一定的算法来获取的。
今天开发一个需求,发现有用到这个东西,于是就打算搜索一下算法,然后在MySQL中写一个函数,方便自己以后或者他人多次调用,这样SQL也整洁很多。
在处理的过程中,无意间发现MySQL 5.7版本自带有经纬度计算的函数,那还写个毛线,直接拿来用就行。不过嘛,现成的是有了,还是要做一下验证的。
MYSQL经纬度函数
-
官网说明:https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html#function_st-distance-sphere
-
ST_Distance_Sphere(g1, g2 [, radius])
Returns the mimimum spherical distance between two points and/or multipoints on a sphere, in meters, or
NULL
if any geometry argument isNULL
or empty.Calculations use a spherical earth and a configurable radius. The optional
radius
argument should be given in meters. If omitted, the default radius is 6,370,986 meters. AnER_WRONG_ARGUMENTS
error occurs if theradius
argument is present but not positive.The geometry arguments should consist of points that specify (longitude, latitude) coordinate values:
- Longitude and latitude are the first and second coordinates of the point, respectively.
- Both coordinates are in degrees.
- Longitude values must be in the range (-180, 180]. Positive values are east of the prime meridian.
- Latitude values must be in the range [-90, 90]. Positive values are north of the equator.
Supported argument combinations are (
Point
,Point
), (Point
,MultiPoint
), and (MultiPoint
,Point
). AnER_GIS_UNSUPPORTED_ARGUMENT
error occurs for other combinations.If any geometry argument is not a syntactically well-formed geometry byte string, an
ER_GIS_INVALID_DATA
error occurs.mysql> SET @pt1 = ST_GeomFromText('POINT(0 0)'); mysql> SET @pt2 = ST_GeomFromText('POINT(180 0)'); mysql> SELECT ST_Distance_Sphere(@pt1, @pt2); +--------------------------------+ | ST_Distance_Sphere(@pt1, @pt2) | +--------------------------------+ | 20015042.813723423 | +--------------------------------+
函数使用示例
select ST_Distance_Sphere(point(114.029381, 22.60939),point(114.012108,22.53652))from dual;
函数有效性验证
-
百度地址到三个地方的距离
-
使用经纬度函数到三地的距离
--深圳北站:8294.58m select ST_Distance_Sphere(point(114.029381,22.60939),point(114.012108,22.53652)) from dual; --中山小榄车站:78812.50m select ST_Distance_Sphere(point(113.258316,22.671085),point(114.012108,22.53652)) from dual; --广州南站:91251.88m select ST_Distance_Sphere(point(113.269325,22.988558),point(114.012108,22.53652)) from dual;
-
结论
总的来说误差在100米左右,还是可以接受的。