计算两个坐标点之间的距离代码,C#版和mysql版

2015-11-5 11:23

c#版

    public class GisHelper
    {
        public const double PI = 3.141593;
        public static int CalculateDistance(double lon1, double lat1, double lon2, double lat2)
        {
            return (int)Math.Round(
                6378.138 * 2 * Math.Asin(
                    Math.Sqrt(
                        Math.Pow(
                            Math.Sin(
                                (lat1 * PI / 180 - lat2 * PI / 180) / 2)
                            , 2)
                            +
                            Math.Cos(lat1 * PI / 180) * Math.Cos(lat2 * PI / 180) *
                                Math.Pow(Math.Sin((lon1 * PI / 180 - lon2 * PI / 180) / 2), 2)
                            )
                        )
                    );
        }
    }

这个是我改自于网上查到的mysql版,测试如下

        [TestMethod]
        public void TestCalDist()
        {
            //北京西站到东站,14公里
            var tt = GisHelper.CalculateDistance(116.327805, 39.901209, 116.490506, 39.909179);
            Console.Write(tt);
        }

运行结果14公里,用百度地图测量后也是14公里,说明代码正确。下面是mysql版

CREATE FUNCTION `CalDist`(lon1 int, lat1 int, lon2 int, lat2 int) RETURNS int(11)
BEGIN

RETURN round(
	6378.138*2*asin(
		sqrt(
			pow(
				sin(
					(lat1*pi()/180-lat2*pi()/180)/2)
                ,2)
                +
                cos(lat1*pi()/180)*cos(lat2*pi()/180)*
					pow(sin((lon1*pi()/180-lon2*pi()/180)/2),2)
				)
			)
		);
END

我把它封装到了mysql函数中,记录下来说不定以后还要用到

 

点击:loading..
收藏到:中国收客网
评论