package com.zbkj.common.utils;

public class DistanceUtil {

    // 将角度转换为弧度
    private static double toRadians(double angle) {
        return angle * Math.PI / 180.0;
    }

    // 计算两个经纬度点之间的距离（单位：公里）
    public static double haversineDistance(double lat1, double lon1, double lat2, double lon2) {
        double R = 6371.0; // 地球半径，单位：公里
        double dLat = toRadians(lat2 - lat1);
        double dLon = toRadians(lon2 - lon1);
        lat1 = toRadians(lat1);
        lat2 = toRadians(lat2);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return R * c; // 返回结果单位为公里
    }

    public static void main(String[] args) {
        double lat1 = 40.7128; // 纬度1
        double lon1 = -74.0060; // 经度1
        double lat2 = 34.0522; // 纬度2
        double lon2 = -118.2437; // 经度2
        double distance = haversineDistance(lat1, lon1, lat2, lon2);
        System.out.printf("距离: %.2f 公里\n", distance);
    }
}
