package cn.iocoder.yudao.framework.common.util.distance;

/**
 * 距离计算 工具类
 */
public class GeoUtil {
    public static int distance(double lat1, double lon1, double lat2, double lon2) {
        final int R = 6371000; // 地球平均半径，单位：米
        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return (int) (R * c);
    }


    /**
     * 计算两个经纬度的距离是否在范围内
     *
     * @param lat1  位置1的纬度
     * @param lon1  位置1的经度
     * @param lat2  位置2的纬度
     * @param lon2  位置2的经度
     * @param range 范围（米）
     * @return 范围内返回 1 范围外返回 0
     */
    public static int distance(double lat1, double lon1, double lat2, double lon2, Integer range) {
        if (range == null) {
            return 0;
        }
        int distance = distance(lat1, lon1, lat2, lon2);
        if (range < distance) {
            return 0;
        }
        return 1;
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        double lat1 = 28.616284;
        double lon1 = 118.102703;

        double lat2 = 28.629981;
        double lon2 = 118.08502;
        double distance = distance(lat1, lon1, lat2, lon2);
        System.out.println("距离是: " + distance + " 米");
        System.out.println("耗时: " + (System.currentTimeMillis() - time));
    }

}
