根据经纬度坐标 计算两点的球面距离

地球半径取6378.138千米,输出distance单位米。

SQL写法:

select 
    ROUND(
        6378.138 * 2 * ASIN(
            SQRT(
                POW(
                    SIN(
                        (
                            latitude1 * PI() / 180 - latitude2 * PI() / 180
                        ) / 2
                    ),
                    2
                ) + COS(latitude1 * PI() / 180) * COS(latitude2 * PI() / 180) 
            * POW(     SIN(     (     longitude1 * PI() / 180 - longitude2 * PI() / 180     ) / 2   ),    2   ) ) ) * 1000 ) AS distance from table where id = 28;

执行结果:

 

 

Java程序写法:

public double getDistance(double lon1, double lat1, double lon2, double lat2) {

        // 地球半径
        double EARTH_RADIUS = 6378.138;
        
        //经纬度转换成弧度
        lat1 = ConvertDegreesToRadians(lat1);
        lon1 = ConvertDegreesToRadians(lon1);
        lat2 = ConvertDegreesToRadians(lat2);
        lon2 = ConvertDegreesToRadians(lon2);

        //差值
        double vLon = Math.abs(lon1 - lon2);
        double vLat = Math.abs(lat1 - lat2);

        double h = HaverSine(vLat) + Math.cos(lat1) * Math.cos(lat2) * HaverSine(vLon);

        double distance = 2 * EARTH_RADIUS * Math.asin(Math.sqrt(h));

        return distance;
    }

    // HaverSine公式
    public double HaverSine(double x)
    {
        double v = Math.sin(x / 2);
        return v * v;
    }
    
    // 将角度换算为弧度
    public static double ConvertDegreesToRadians(double degrees)
    {
        return degrees * Math.PI / 180;
    }

 

 
posted @ 2020-10-19 20:34  果冻迪迪  阅读(1328)  评论(0编辑  收藏  举报