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.

  1. public double HaversineDistance(LatLng pos1, LatLng pos2, DistanceUnit unit)
  2. {
  3.     double R = (unit == DistanceUnit.Miles) ? 3959 : 6371;
  4.     var la1 = pos1.Latitude;
  5.     var lo1 = pos1.Longitude;
  6.     var la2 = pos2.Latitude;
  7.     var lo2 = pos2.Longitude;
  8.     var lat1 = la1 * Math.PI / 180;
  9.     var lon1 = lo1 * Math.PI / 180;
  10.     var lat2 = la2 * Math.PI / 180;
  11.     var lon2 = lo2 * Math.PI / 180;
  12.     var dLat = lat2 - lat1;
  13.     var dLon = lon2 - lon1;
  14.     var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(lat1) * Math.Cos(lat2) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
  15.     var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
  16.     var d = R * c;
  17.     return d;
  18. }
  1. public class LatLng
  2. {
  3.     public double Latitude { get; set; }
  4.     public double Longitude { get; set; }
  5.     public LatLng()
  6.     {
  7.     }
  8.     public LatLng(double lat, double lng)
  9.     {
  10.         this.Latitude = lat;
  11.         this.Longitude = lng;
  12.     }
  13. }

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Link To This Post/Page

Spread The Word

Add this button to your blog:
JJ Technology Solutions

Blog Archive

Trackers

eXTReMe Tracker
facebook

- Copyright © JJ Technology Solutions - Powered by Source Code Solutions -