0

I need to sort a list of lat/long values based on their distance from the user's current lat/long. I also need to display the distance in Miles for each entry.

I found this answer that is close but returns the nearest lat/long entry rather than a list. Also, I don't understand the distance unit used to be able to convert to Miles.

In short, I need a method where...

  1. You provide a current Lat/Long pair and a list of Lat/Long pairs
  2. Return a sorted list of Lat/Long pairs with distance in Miles
class Location
{
   double Lat { get; set; }
   double Long { get; set; }
   double Distance { get; set; }
}

public List<Location> SortLocations(Location current, List<Location> locations)
{
   // ???
}
Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76
Hoss
  • 692
  • 1
  • 7
  • 20
  • can you tell about lat , long pair, that do you want to get distance between two lat long or between one lat and long? – Ahmed Ali Dec 14 '19 at 06:12

1 Answers1

1

You may be able to use GeoCoordinate as mentioned here: Calculating the distance between 2 points in c#

Once you can calculate the distance, then you can do something like:

public List<Location> SortLocations(Location current, List<Location> locations)
{
    foreach (var location in locations)
    {
        location.Distance = CalculateDistance(current, location);
    }
    // Return the list sorted by distance
    return locations.OrderBy(loc => loc.Distance);
}

If you don't want to set the Distance property on the locations collection, you can use Select:

return locationsWithDistance = locations.Select(
    location => new Location
    {
        Lat = location.Lat,
        Long = location.Long,
        Distance = CalculateDistance(current, location)
    }).OrderBy(location => location.Distance);
Matt U
  • 4,970
  • 9
  • 28
  • 1
    This is perfect thanks! I had never heard of GeoCoordinate, its great as it simplifies code and returns distance in meters (easy conversion to miles). Then sorting list by distance is perfect, I overlooked that now obvious approach (distance first, then sort distance). I got this all implemented in my code and works great. – Hoss Dec 15 '19 at 09:38