简体   繁体   English

给定纬度/经度,从C#中的纬度/经度列表中找到最接近的纬度/经度对

[英]Given a lat/long, find the nearest lat/long pair from a list of lat/long in c#

From a List of lat/long pairs, I am trying to find nearest lat/long pair wrt to a given Lat/Long . 我试图从经纬度对的列表中找到最接近给定纬度/经度的纬度对/经度对。 For ex- List of {42_-72,42,-75,43,-76} and a given point 42,-71 对于{42_-72,42,-75,43,-76}和给定点42-71的前列表

The Point 42,-72 is the nearest to 42,-71, hence output => 42,-72. 点42-72最接近42-71,因此输出=> 42-72。

I would start by creating a method that can get the distance between two points. 我将从创建一个可以获取两点之间距离的方法开始。 If we consider that in any right triangle, a^2 + b^2 = c^2 , and the distance from point P1 to point P2 is c , then we can use this formula to get the distance between two points since we know their X and Y coordinates. 如果我们认为在任何直角三角形中a^2 + b^2 = c^2 ,并且从点P1到点P2的距离为c ,则可以使用此公式获取两点之间的距离,因为我们知道它们的距离XY坐标。 The distance a is the difference between P2.X and P1.X , and the distance b is the difference between P2.Y and P1.Y : 距离aP2.XP1.X之间的差,距离bP2.YP1.Y之间的差:

private static double GetDistance(Point a, Point b)
{
    return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));
}

Then we can create a method that takes in a target point and a list of candidate points and returns the candidate which is the shortest distance from the target: 然后,我们可以创建一个方法,该方法接受目标点和候选点列表,并返回距目标最短距离的候选:

private static Point GetClosestPoint(Point target, List<Point> candidates)
{
    if (candidates == null) throw new ArgumentNullException(nameof(candidates));
    if (!candidates.Any()) throw new ArgumentException("The candidates list is empty.");

    var minDistance = double.MaxValue;
    var closestPoint = new Point();

    foreach (var candidate in candidates)
    {
        var distance = GetDistance(target, candidate);
        if (distance > minDistance) continue;
        minDistance = distance;
        closestPoint = candidate;
    }

    return closestPoint;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM