欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA获取多个经纬度的中心点

程序员文章站 2024-03-24 12:20:04
...

经纬度的实体类

import lombok.Data;

@Data
public class GeoCoordinate {
    private double latitude;
    private double longitude;

    public GeoCoordinate(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public String ToString() {
        return String.format("{0},{1}", latitude, longitude);
    }
}

算法

/**
     * 根据输入的地点坐标计算中心点
     *
     * @param str ( 118.778076,30.905645;118.780764,30.914549;118.782928,30.9186;118.785621,30.92202; )
     * @return
     */
    public static GeoCoordinate getCenterPoint(String str) {
        String[] arr = str.split(";");
        int total = arr.length;
        double X = 0, Y = 0, Z = 0;
        for (int i = 0; i < arr.length; i++) {
            double lat, lon, x, y, z;
            lon = Double.parseDouble(arr[i].split(",")[0]) * Math.PI / 180;
            lat = Double.parseDouble(arr[i].split(",")[1]) * Math.PI / 180;
            x = Math.cos(lat) * Math.cos(lon);
            y = Math.cos(lat) * Math.sin(lon);
            z = Math.sin(lat);
            X += x;
            Y += y;
            Z += z;
        }

        X = X / total;
        Y = Y / total;
        Z = Z / total;
        double Lon = Math.atan2(Y, X);
        double Hyp = Math.sqrt(X * X + Y * Y);
        double Lat = Math.atan2(Z, Hyp);

        return new GeoCoordinate(Lat * 180 / Math.PI, Lon * 180 / Math.PI);
    }

    /// <summary>
    /// 根据输入的地点坐标计算中心点
    /// </summary>
    /// <param name="geoCoordinateList"></param>
    /// <returns></returns>
    public static GeoCoordinate getCenterPointFromListOfCoordinates(java.util.List<GeoCoordinate> geoCoordinateList) {
        int total = geoCoordinateList.size();
        double X = 0, Y = 0, Z = 0;
        for (GeoCoordinate g : geoCoordinateList) {
            double lat, lon, x, y, z;
            lat = g.getLatitude() * Math.PI / 180;
            lon = g.getLongitude() * Math.PI / 180;
            x = Math.cos(lat) * Math.cos(lon);
            y = Math.cos(lat) * Math.sin(lon);
            z = Math.sin(lat);
            X += x;
            Y += y;
            Z += z;
        }
        X = X / total;
        Y = Y / total;
        Z = Z / total;
        double Lon = Math.atan2(Y, X);
        double Hyp = Math.sqrt(X * X + Y * Y);
        double Lat = Math.atan2(Z, Hyp);
        return new GeoCoordinate(Lat * 180 / Math.PI, Lon * 180 / Math.PI);
    }

### 参考文章

主要参考:C#版

https://blog.csdn.net/yl2isoft/article/details/16368397

 详细的算法说明,可以参考。

http://www.geomidpoint.com/calculation.html

自己写完才发现的java版

https://blog.csdn.net/weixin_42402326/article/details/93751115

相关标签: 算法 java gis