简体   繁体   中英

How to sort a list of lat/long by distance (in miles) from a given lat/long in C#?

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)
{
   // ???
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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