如何在C#中按距给定纬度/经度的距离(以英里为单位)对纬度/经度列表进行排序?

时间:2019-12-14 06:01:21

标签: c# geolocation

我需要根据纬度/经度值与用户当前纬度/经度的距离对列表进行排序。我还需要为每个条目显示以英里为单位的距离。

我发现this answer很近,但返回最近的经/纬度条目而不是列表。另外,我不了解以前能够转换为英里的距离单位。

简而言之,我需要一种方法...

  1. 您提供当前的纬度/经度对和纬度/经度对列表
  2. 返回以纬度为单位的纬度/经度对的排序列表
class Location
{
   double Lat { get; set; }
   double Long { get; set; }
   double Distance { get; set; }
}

public List<Location> SortLocations(Location current, List<Location> locations)
{
   // ???
}

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用此处所述的GeoCoordinateCalculating the distance between 2 points in c#

一旦您可以计算出距离,就可以执行以下操作:

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

如果您不想在Distance集合上设置locations属性,则可以使用Select

return locationsWithDistance = locations.Select(
    location => new Location
    {
        Lat = location.Lat,
        Long = location.Long,
        Distance = CalculateDistance(current, location)
    }).OrderBy(location => location.Distance);