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...
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.