如何在C#中计算从一个点到另一个点的X坐标

时间:2018-11-21 01:23:26

标签: c# geospatial distance

比方说,我有2个坐标,彼此相距〜222.33米:

self.ivTest.frame = NSRect(x: 0, y: 0, width: 100, height: 100)

这2点构成一个分段。

我如何计算距A或B A: 49.25818, -123.20626 B: 49.25813, -123.2032 米但又指向另一个点的Z点的坐标?

我已经使用X库知道了两点之间的距离。

System.Device.Location

我正在寻找这样的东西:

GeoCoordinate A = new GeoCoordinate(49.25818, -123.20626);
GeoCoordinate B = new GeoCoordinate(49.25813, -123.2032);
var distanceInMeters = A.GetDistanceTo(B);
// distanceInMeters = 222.33039783713738

我认为我可能需要方位或其他东西才能获得新的点位置。

我发现的大多数示例都是针对具有特定库的iOS,Android或GMaps。

2 个答案:

答案 0 :(得分:1)

这是我将如何做的概述。使用这种方法,无需显式处理坐标和距离之间的单位差异,因为采用目标与总距离之比可以消除单位。

totalDistance = distance in meters between point A and point B.
targetDistance = distance in meters to travel from point A to point B

ratio = targetDistance / totalDistance

diffX = B.X - A.X
diffY = B.Y - A.Y

targetX = A.X + (ratio * diffX)
targetY = A.Y + (ratio * diffY)

但这不会处理诸如179度经度和增加3度使您处于-178度经度的边缘情况。

答案 1 :(得分:0)

这是我的代码从http://www.movable-type.co.uk/scripts/latlong.html转换为C#。分数是从0到1,并且是沿着输出位置从第一点到第二点的距离的分数。您总是可以修改它以获取直线距离值。

public static (double Lat, double Lon) IntermediatePoint((double Lat, double Lon) StartPoint, (double Lat, double Lon) EndPoint, double fraction)
    {
        if (fraction < 0 || fraction > 1)
            throw new ArgumentOutOfRangeException();
        double angDist = Distance(StartPoint, EndPoint) / radius;
        double lat1 = StartPoint.Lat * (Math.PI / 180);
        double lon1 = StartPoint.Lon * (Math.PI / 180);
        double lat2 = EndPoint.Lat * (Math.PI / 180);
        double lon2 = EndPoint.Lon * (Math.PI / 180);
        double a = Math.Sin((1 - fraction) * angDist) / Math.Sin(angDist);
        double b = Math.Sin(fraction * angDist) / Math.Sin(angDist);
        double x = a * Math.Cos(lat1) * Math.Cos(lon1) + b * Math.Cos(lat2) * Math.Cos(lon2);
        double y = a * Math.Cos(lat1) * Math.Sin(lon1) + b * Math.Cos(lat2) * Math.Sin(lon2);
        double z = a * Math.Sin(lat1) + b * Math.Sin(lat2);
        double lat3 = Math.Atan2(z, Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2)));
        double lon3 = Math.Atan2(y, x);
        return (lat3 * (180 / Math.PI), lon3 * (180 / Math.PI));
    }
public static double Distance((double Lat, double Lon) point1, (double Lat, double Lon) point2)
    {
        double φ1 = point1.Lat * (Math.PI / 180.0);
        double φ2 = point2.Lat * (Math.PI / 180.0);
        double Δφ = (point2.Lat - point1.Lat) * (Math.PI / 180.0);
        double Δλ = (point2.Lon - point1.Lon) * (Math.PI / 180.0);
        double a = Math.Sin(Δφ / 2) * Math.Sin(Δφ / 2) + Math.Cos(φ1) * Math.Cos(φ2) * Math.Sin(Δλ / 2) * Math.Sin(Δλ / 2);
        double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

        return radius * c;
    }

radius是一个常数,代表以米为单位的地球半径。