Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1515
暖寄归人
暖寄归人 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:48

    Thanks! Here is a C# version of OP's solutions using degrees. It utilises the System.Device.Location.GeoCoordinate class

        public static GeoCoordinate GetCentralGeoCoordinate(
            IList geoCoordinates)
        {
            if (geoCoordinates.Count == 1)
            {
                return geoCoordinates.Single();
            }
    
            double x = 0;
            double y = 0;
            double z = 0;
    
            foreach (var geoCoordinate in geoCoordinates)
            {
                var latitude = geoCoordinate.Latitude * Math.PI / 180;
                var longitude = geoCoordinate.Longitude * Math.PI / 180;
    
                x += Math.Cos(latitude) * Math.Cos(longitude);
                y += Math.Cos(latitude) * Math.Sin(longitude);
                z += Math.Sin(latitude);
            }
    
            var total = geoCoordinates.Count;
    
            x = x / total;
            y = y / total;
            z = z / total;
    
            var centralLongitude = Math.Atan2(y, x);
            var centralSquareRoot = Math.Sqrt(x * x + y * y);
            var centralLatitude = Math.Atan2(z, centralSquareRoot);
    
            return new GeoCoordinate(centralLatitude * 180 / Math.PI, centralLongitude * 180 / Math.PI);
        }
    

提交回复
热议问题