【Java AWT 图形界面编程】经度 Longitude 、纬度 Latitude 计算 ( 经度、纬度概念 | 根据经纬度计算距离 )

Source





一、经度、纬度概念



经度 Longitude , 本初子午线 位置 为 0 度经线 , 相当于水平 x 轴 的坐标 , 经度的取值范围 -180 度 ~ +180 度 ;

纬度 Latitude , 相当于 垂直 y 轴 的坐标 , 纬度的取值范围 -90 度 ~ + 90 度 ;

在这里插入图片描述

西经 和 南纬 是负数 ;

在这里插入图片描述





二、根据经纬度计算距离



根据 球面三角学Haversine 公式 , 计算 两个 经纬度 之间的距离 :

  • Java 语言 :
public class LocationUtils {
    
      
    
    private static final double EARTH_RADIUS = 6371; // 地球平均半径,单位为公里
    
    public static double getDistance(double lat1, double lon1, double lat2, double lon2) {
    
      
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lon1) - Math.toRadians(lon2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000) / 1000.0; // 保留三位小数
        return s;
    }
}
  • Python 语言 :
import math

def distance(lat1, lon1, lat2, lon2):
    R = 6371 # 地球半径,单位为公里
    dlat = math.radians(lat2 - lat1)
    dlon = math.radians(lon2 - lon1)
    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
        * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = R * c # 距离,单位为公里
    return d