Last active
November 13, 2022 07:53
-
-
Save sukesh-ak/75154f27e3027e625bff1a5312c5dbc6 to your computer and use it in GitHub Desktop.
Spherical Trignometry : HaversineDistance function to find distance between 2 GeoCordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Returns the distance in miles or kilometers of any two GeoCordinates | |
/// Ref: https://en.wikipedia.org/wiki/Haversine_formula | |
/// </summary> | |
/// <param name="pos1">Location 1</param> | |
/// <param name="pos2">Location 2</param> | |
/// <param name="unit">Miles or Kilometers or Meters</param> | |
/// <returns>Distance in the requested unit</returns> | |
public static double HaversineDistance(LatLng pos1, LatLng pos2, DistanceUnit unit) | |
{ | |
double R = (unit == DistanceUnit.Miles) ? 3960.0 : 6371.0; | |
double lat = (pos2.Latitude - pos1.Latitude).ToRadians(); | |
double lng = (pos2.Longitude - pos1.Longitude).ToRadians(); | |
double h1 = Math.Sin(lat / 2) * Math.Sin(lat / 2) | |
+ Math.Cos(pos1.Latitude.ToRadians()) | |
* Math.Cos(pos2.Latitude.ToRadians()) | |
* Math.Sin(lng / 2) * Math.Sin(lng / 2); | |
var h2 = 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1))); | |
if (unit == DistanceUnit.Meters) | |
return h2; | |
else | |
return R* h2; | |
} | |
public enum DistanceUnit { Miles, Kilometers, Meters }; | |
/// <summary> | |
/// Specifies a Latitude / Longitude point. | |
/// </summary> | |
public class LatLng | |
{ | |
public double Latitude { get; set; } | |
public double Longitude { get; set; } | |
public double Elevation { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment