0

From a List of lat/long pairs, I am trying to find nearest lat/long pair w.r.t to a given Lat/Long . For ex- List of {42_-72,42,-75,43,-76} and a given point 42,-71

The Point 42,-72 is the nearest to 42,-71, hence output => 42,-72.

user33636
  • 1
  • 3
  • 1
    Hi there! What code do you have so far, and what trouble are you having with it? – tehDorf Nov 16 '17 at 23:52
  • Do you want to prioritize latitude or longitude in the case of a tie? Or do you want to return both? – Rufus L Nov 16 '17 at 23:55
  • It seems logical to me that you would tread them as points on a graph and calculate the distance from your target point to each candidate point, and then return the point which has the shortest distance. – Rufus L Nov 16 '17 at 23:56
  • What type is your `List` holding? Is it just a `List` or is it an object of some kind? (Such as `List`) – edkek Nov 17 '17 at 00:00
  • It is a List of objects which in turn holds the lat/long values – user33636 Nov 17 '17 at 14:49

1 Answers1

0

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. 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:

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;
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43