- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathGeoLocation.cs
36 lines (30 loc) · 1.35 KB
/
GeoLocation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
usingSystem;
namespaceAlgorithms.Other;
publicstaticclassGeoLocation
{
privateconstdoubleEarthRadiusKm=6371.01d;
/// <summary>
/// Calculates spherical distance between 2 points given their latitude, longitude coordinates.
/// https://www.movable-type.co.uk/scripts/latlong.html.
/// </summary>
/// <param name="lat1">Latitude of point A.</param>
/// <param name="lng1">Longitude of point A.</param>
/// <param name="lat2">Latitude of point B.</param>
/// <param name="lng2">Longitude of point B.</param>
/// <returns>Spherical distance between A and B.</returns>
publicstaticdoubleCalculateDistanceFromLatLng(doublelat1,doublelng1,doublelat2,doublelng2)
{
varpi180=Math.PI/180d;
varlat1Radian=lat1*pi180;
varlng1Radian=lng1*pi180;
varlat2Radian=lat2*pi180;
varlng2Radian=lng2*pi180;
vardiffLat=lat2Radian-lat1Radian;
vardiffLng=lng2Radian-lng1Radian;
varhaversine=
Math.Sin(diffLat/2)*Math.Sin(diffLat/2)
+Math.Cos(lat1Radian)*Math.Cos(lat2Radian)*Math.Sin(diffLng/2)*Math.Sin(diffLng/2);
vardistance=EarthRadiusKm*(2d*Math.Atan2(Math.Sqrt(haversine),Math.Sqrt(1-haversine)));
returndistance*1000;// Convert from km -> m
}
}