mysql计算出两个经纬度的距离,MySQL函数计算两个纬度和经度之间的距离

If you have a latitude and longitude stored in your database and need to calculate the distance between two coordinates. How can you calculate it using a MySQL function?

解决方案

After searching around for awhile, I gave up and wrote it myself. I was able to adapt some other code to the following MySQL function.

DELIMITER $$

/*

Takes two latitudes and longitudes in degrees. You could comment out the conversion if you want to pass as radians.

Calculate the distance in miles, change the radius to the earth's radius in km to get km.

*/

DROP FUNCTION IF EXISTS GETDISTANCE$$

CREATE FUNCTION GETDISTANCE

(deg_lat1 FLOAT, deg_lng1 FLOAT, deg_lat2 FLOAT, deg_lng2 FLOAT)

RETURNS FLOAT

DETERMINISTIC

BEGIN

DECLARE distance FLOAT;

DECLARE delta_lat FLOAT;

DECLARE delta_lng FLOAT;

DECLARE lat1 FLOAT;

DECLARE lat2 FLOAT;

DECLARE a FLOAT;

SET distance = 0;

/*Convert degrees to radians and get the variables I need.*/

SET delta_lat = radians(deg_lat2 - deg_lat1);

SET delta_lng = radians(deg_lng2 - deg_lng1);

SET lat1 = radians(deg_lat1);

SET lat2 = radians(deg_lat2);

/*Formula found here: http://www.movable-type.co.uk/scripts/latlong.html*/

SET a = sin(delta_lat/2.0) * sin(delta_lat/2.0) + sin(delta_lng/2.0) * sin(delta_lng/2.0) * cos(lat1) * cos(lat2);

SET distance = 3956.6 * 2 * atan2(sqrt(a), sqrt(1-a));

RETURN distance;

END$$

DELIMITER ;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值