user1194842
user1194842

Reputation: 71

How to get nearest X points to a given point with Lat and Long?

I have list of points with latitude and longitude coordinates, from which I want to enter a point say X. I need help coming up with an algorithm to determine the closest 3 list members to that point x.

Upvotes: 0

Views: 2043

Answers (1)

Arthur
Arthur

Reputation: 134

You can basically just approach this as a 3D nearest point problem. (I don't have the Lat / Lon to Cartesian (x,y,z) calc at hand right now, but you can easily find that using google).

public class LatLonPoint
{
   public double Latitude { get; set; }
   public double Longitude { get; set; }

   public double X
   {
      get
      {
      .......
      }
   }

   public double Y ....
   public double Z .....

   public double DistanceTo(LatLonPoint point)
   {
     double dX = point.X - X;
     double dY = point.Y - Y;
     double dZ = point.Z - Z;

     return Math.Sqrt(dX * dX + dY * dY + dZ * dZ);
   }
}

Your class code:

// Your list of points
private List<LatLonPoint> _points = new List<LatLonPoint>();

public LatLonPoint FindClosestPoint(LatLonPoint x)
{
    var closestPoint = null;
    double closestDistance = double.MaxValue;

    foreach (var point in latLonList)
    {
        double distanceToPoint = point.DistanceTo(x);
        if (distanceToPoint < closestDistance)
        {
           closestPoint = point;
           closestDistance = distanceToPoint;
        }
    }

    return closestPoint;
}

Upvotes: 1

Related Questions