【问题标题】:How to calculate distance between 2 coordinates [duplicate]如何计算2个坐标之间的距离[重复]
【发布时间】:2014-11-27 05:28:43
【问题描述】:

我需要使用 c# 在 Windows 8.1 应用程序中找到 2 点之间的距离(Km),所以我使用了下面的函数,但返回的值不正确,请提供任何帮助:

public static double DistanceTo(Double latitude1, Double longitude1, Double latitude2, Double longitude2)
    {
        var a = latitude1 - latitude2;
        var b = longitude1 - longitude2;

        return Math.Sqrt(a * a + b * b);
    }

【问题讨论】:

  • 该公式为您提供两点之间的位移而不是距离。
  • @bit 这个公式并没有给你任何有用的东西。
  • 有什么公式可以告诉我距离吗?
  • @ahmad 检查链接的重复问题
  • 勾股定理只适用于二维欧几里得空间。您需要使用适用于球体的方法。只需搜索您想做的事情,就会有很多点击。

标签: c#


【解决方案1】:

您使用了错误的公式。这就是你没有得到正确结果的原因。 您使用的公式是我们用于计算两点之间距离的公式 在同一平面上,并且可以使用毕达哥拉定理证明。但是,当我们要计算球体表面上两点之间的距离时(我们假设地球是一个完美的球体),我们不使用这种类型。

Here 是一个链接,其中包含正确的公式和 JavaScript 中的实现。

下面,我有一个 C# 实现

首先我们必须定义一个方法,它将一个角度作为参数,并返回它的弧度值。

public double ConvertToRadians(double angle)
{
    return (Math.PI / 180) * angle;
}

然后我们可以定义计算距离的方法:

public static double DistanceTo(double latitude1, 
                                double longitude1, 
                                double latitude2, 
                                double longitude2)
{
    // The radius of the earth in Km.
    // You could also use a better estimation of the radius of the earth
    // using decimals digits, but you have to change then the int to double.
    int R = 6371; 

    double f1 = ConvertToRadians(latitude1);
    double f2 = ConvertToRadians(latitude2);

    double df = ConvertToRadians(latitude1-latitude2);
    double dl = ConvertToRadians(longitude1-longitude2);

    double a = Math.Sin(dφ/2) * Math.Sin(dφ/2) +
    Math.Cos(f1) * Math.Cos(f2) *
    Math.Sin(dλ/2) * Math.Sin(dλ/2);

    double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a));

    // Calculate the distance.
    double d = R * c;

    return d; 
}

如果你不想像上面那样实现它,你可以使用GeoCoordinate类,它

表示由纬度和确定的地理位置 经度坐标。还可能包括高度、准确性、速度和 课程信息。

如果你这样做了,那么:

var point1 = new GeoCoordinate(latitude1, longitude1);
var point2 = new GeoCoordinate(latitude2, latitude2);

然后你得到point1point2 之间的距离,如下所示:

point1.GetDistanceTo(point2);

【讨论】:

【解决方案2】:

试试这样的:

var coord1 = new GeoCoordinate(lat1, long1);
var coord2 = new GeoCoordinate(lat2, long2);

var distance = coord1.GetDistanceTo(coord2);

here。好像是重复的

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 2020-02-12
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    相关资源
    最近更新 更多