- Back to Home »
- ASP.Net , C# »
Posted by : Jebastin
Friday, 20 December 2013
The following function is used to find the distance between two Latitude & Longitude co-ordinates using Haversine formula.
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical triangles.
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical triangles.
- public double HaversineDistance(LatLng pos1, LatLng pos2, DistanceUnit unit)
- {
- double R = (unit == DistanceUnit.Miles) ? 3959 : 6371;
- var la1 = pos1.Latitude;
- var lo1 = pos1.Longitude;
- var la2 = pos2.Latitude;
- var lo2 = pos2.Longitude;
- var lat1 = la1 * Math.PI / 180;
- var lon1 = lo1 * Math.PI / 180;
- var lat2 = la2 * Math.PI / 180;
- var lon2 = lo2 * Math.PI / 180;
- var dLat = lat2 - lat1;
- var dLon = lon2 - lon1;
- var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(lat1) * Math.Cos(lat2) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
- var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
- var d = R * c;
- return d;
- }
- public class LatLng
- {
- public double Latitude { get; set; }
- public double Longitude { get; set; }
- public LatLng()
- {
- }
- public LatLng(double lat, double lng)
- {
- this.Latitude = lat;
- this.Longitude = lng;
- }
- }