Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1528
暖寄归人
暖寄归人 2020-11-27 09:27

Given a set of latitude and longitude points, how can I calculate the latitude and longitude of the center point of that set (aka a point that would center a view on all poi

21条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 09:35

    Java Version if anyone needs it. Constants defined static to not calculate them twice.

    /**************************************************************************************************************
     *   Center of geometry defined by coordinates
     **************************************************************************************************************/
    private static double pi = Math.PI / 180;
    private static double xpi = 180 / Math.PI;
    
    public static Coordinate center(Coordinate... arr) {
        if (arr.length == 1) {
            return arr[0];
        }
        double x = 0, y = 0, z = 0;
    
        for (Coordinate c : arr) {
            double latitude = c.lat() * pi, longitude = c.lon() * pi;
            double cl = Math.cos(latitude);//save it as we need it twice
            x += cl * Math.cos(longitude);
            y += cl * Math.sin(longitude);
            z += Math.sin(latitude);
        }
    
        int total = arr.length;
    
        x = x / total;
        y = y / total;
        z = z / total;
    
        double centralLongitude = Math.atan2(y, x);
        double centralSquareRoot = Math.sqrt(x * x + y * y);
        double centralLatitude = Math.atan2(z, centralSquareRoot);
    
        return new Coordinate(centralLatitude * xpi, centralLongitude * xpi);
    }
    

提交回复
热议问题