Friday, 15 September 2017

Distance calculation function between lat and long in c#

 public class DistanceCalculationHelper
    {
        public static double GetDistance(decimal lat1, decimal long1, decimal lat2, decimal lon2,char unit='K')
        {
            try
            {
                //const double PI = 3.1415926535897931;
                //double rlat1 = Math.PI * double.Parse(lat1.ToString()) / 180;
                //double rlat2 = Math.PI * double.Parse(lat2.ToString()) / 180;
                //double theta = double.Parse(long1.ToString()) - double.Parse(lon2.ToString());
                //double rtheta = Math.PI * theta / 180;
                //double dist =
                //    Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) *
                //    Math.Cos(rlat2) * Math.Cos(rtheta);
                //dist = Math.Acos(dist);
                //dist = dist * 180 / Math.PI;
                //dist = dist * 60 * 1.1515;

                //switch (unit)
                //{
                //    case 'K': //Kilometers -> default
                //        return dist * 1.609344;
                //    case 'N': //Nautical Miles
                //        return dist * 0.8684;
                //    case 'M': //Miles
                //        return dist;
                //}

                //return dist;

                var sCoord = new GeoCoordinate(double.Parse(lat1.ToString()), double.Parse(long1.ToString()));
                var eCoord = new GeoCoordinate(double.Parse(lat2.ToString()), double.Parse(lon2.ToString()));
                return Math.Round((sCoord.GetDistanceTo(eCoord) / 1000), 2);
                        }
            catch
            {
                return 0;
            }
        }
    }

No comments:

Post a Comment