package com.uavps.framework.udp.utils;

public class WebMercator {
    private static final double EARTH_RADIUS = 6378137; // 地球赤道半径（单位：米）
    private static final double MAX_LATITUDE = 85.0511287798; // 墨卡托投影的最大纬度

    // 将经纬度转换为 Web 墨卡托坐标（单位：米）
    public static double[] lonLatToMeters(double lon, double lat) {
//        // 限制纬度范围（避免无限大的坐标）
//        lat = Math.max(Math.min(MAX_LATITUDE, lat), -MAX_LATITUDE);
//
//        double x = lon * (EARTH_RADIUS * Math.PI / 180.0);
//        double y = Math.log(Math.tan((90 + lat) * Math.PI / 360.0)) / (Math.PI / 180.0);
//        y = y * (EARTH_RADIUS * Math.PI / 180.0);
//
//        return new double[]{x, y};
        return new double[]{lon, lat};
    }

    // 将 Web 墨卡托坐标转回经纬度
    public static double[] metersToLonLat(double x, double y) {
        double lon = x / (EARTH_RADIUS * Math.PI / 180.0);
        double lat = (Math.atan(Math.exp(y / (EARTH_RADIUS * Math.PI / 180.0))) * 360.0 / Math.PI) - 90;
        return new double[]{lon, lat};
    }

    public static void main(String[] args) {
        double[] xy = lonLatToMeters(116.4074, 39.9042); // 北京经纬度
        System.out.println("x (meters): " + xy[0]); // 输出: ~1.295e7
        System.out.println("y (meters): " + xy[1]); // 输出: ~4.87e6
    }
}
