如何在 C# 中按距给定 lat/long 的距离(以英里为单位)对 lat/long 列表进行排序?
How to sort a list of lat/long by distance (in miles) from a given lat/long in C#?
我需要根据它们与用户当前 lat/long 的距离对 lat/long 值的列表进行排序。我还需要为每个条目显示以英里为单位的距离。
我发现 this answer 很接近,但 returns 最近的 lat/long 条目而不是列表。另外,我不明白过去可以转换为英里的距离单位。
简而言之,我需要一种方法...
- 您提供当前 Lat/Long 对和 Lat/Long 对列表
- Return Lat/Long 对的排序列表,距离以英里为单位
class Location
{
double Lat { get; set; }
double Long { get; set; }
double Distance { get; set; }
}
public List<Location> SortLocations(Location current, List<Location> locations)
{
// ???
}
您可以使用 GeoCoordinate
,如下所述:Calculating 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);
}
如果不想在locations
集合上设置Distance
属性,可以使用Select
:
return locationsWithDistance = locations.Select(
location => new Location
{
Lat = location.Lat,
Long = location.Long,
Distance = CalculateDistance(current, location)
}).OrderBy(location => location.Distance);
我需要根据它们与用户当前 lat/long 的距离对 lat/long 值的列表进行排序。我还需要为每个条目显示以英里为单位的距离。
我发现 this answer 很接近,但 returns 最近的 lat/long 条目而不是列表。另外,我不明白过去可以转换为英里的距离单位。
简而言之,我需要一种方法...
- 您提供当前 Lat/Long 对和 Lat/Long 对列表
- Return Lat/Long 对的排序列表,距离以英里为单位
class Location
{
double Lat { get; set; }
double Long { get; set; }
double Distance { get; set; }
}
public List<Location> SortLocations(Location current, List<Location> locations)
{
// ???
}
您可以使用 GeoCoordinate
,如下所述:Calculating 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);
}
如果不想在locations
集合上设置Distance
属性,可以使用Select
:
return locationsWithDistance = locations.Select(
location => new Location
{
Lat = location.Lat,
Long = location.Long,
Distance = CalculateDistance(current, location)
}).OrderBy(location => location.Distance);