I have a table that contains lat and lng fields.
Now I want to sort this table’s data based on a given location’s lat and lng so that the closest location is displayed first and the rest are sorted based on the same principle.
result = result.OrderBy(x => Haversine(x.BeginningLat ?? 0, lat ?? 0, x.BeginningLng ?? 0, lng?? 0));
private static double Haversine(double lat1, double lat2, double lon1, double lon2)
{
const double r = 6378100; // meters
var sdlat = Math.Sin((lat2 - lat1) / 2);
var sdlon = Math.Sin((lon2 - lon1) / 2);
var q = sdlat * sdlat + Math.Cos(lat1) * Math.Cos(lat2) * sdlon * sdlon;
var d = 2 * r * Math.Asin(Math.Sqrt(q));
return d;
}