根据经纬度计算两地的直线距离

import java.lang.Math;

public class DistanceCalculator {
    private static final int EARTH_RADIUS = 6371; // 地球半径(单位:千米)

    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                   Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                   Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double distance = EARTH_RADIUS * c;
        return distance;
    }

    public static void main(String[] args) {
        double lat1 = 28.198746; // 长沙五一广场的纬度
        double lon1 = 112.976217; // 长沙五一广场的经度
        double lat2 = 28.224186; // 长沙麓谷信息港B的纬度
        double lon2 = 112.905898; // 长沙麓谷信息港B的经度

        double distance = calculateDistance(lat1, lon1, lat2, lon2);
        System.out.println("长沙五一广场到长沙麓谷信息港B的直线距离:" + distance + "千米");
    }
}

你可能感兴趣的:(java,java,算法,开发语言)