Calculating the Distance between 2 places by using Latitudes and Longitudes in DoTNet

Hello guys,

As mentioned in the title we will Discuss how to get the Distance between 2 Locations.

We will do it as a function that can be accessible and peaceable in any class.

Let's define a function with two inputs firstly,

private double HaversineDistance(string loc1str,string loc2str)
{
//code 

 }

as the input is the string we have to convert that string into a double by using the below,

string[] loc1 = loc1str.Split(", ");
string[] loc2 = loc2str.Split(", ");

By Using Math we will get the exact distance. (it may be 0.03meter different)

The function and action goes below,

private double HaversineDistance(string loc1str,string loc2str)

{

                    NumberFormatInfo provider = new NumberFormatInfo();

                    provider.NumberDecimalSeparator = "."; 

                    // string loc1str="17.353407649759806, 78.53191718216988";

                    string[] loc1 = loc1str.Split(", ");

                    // string loc2str="17.34453519500451, 78.53211168200997";

                    string[] loc2 = loc2str.Split(", "); 

                    double dDistance = Double.MinValue;

                    // converting into double.
                    double dLat1InRad = Convert.ToDouble(loc1[0], provider) * (Math.PI / 180.0);

                    double dLong1InRad = Convert.ToDouble(loc1[1], provider) * (Math.PI / 180.0); 

                    double dLat2InRad = Convert.ToDouble(loc2[0], provider) * (Math.PI / 180.0);

                    double dLong2InRad = Convert.ToDouble(loc2[1], provider) * (Math.PI / 180.0);

                    // calculating the rad.
                    double dLongitude = dLong2InRad - dLong1InRad;

                    double dLatitude = dLat2InRad - dLat1InRad;

                    // Intermediate result a.

                    double a = Math.Pow(Math.Sin(dLatitude / 2.0), 2.0) + 

                            Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) * 

                            Math.Pow(Math.Sin(dLongitude / 2.0), 2.0);

                    // Intermediate result c (great circle distance in Radians).

                    double c = 2.0 * Math.Asin(Math.Sqrt(a));

                    // Distance.

                    // const Double kEarthRadiusMiles = 3956.0;

                    const Double kEarthRadiusKms = 6376.5;

                    dDistance = kEarthRadiusKms * c;

                    return dDistance; 

  }
Output: 0.98

Thank You...

Sign In or Register to comment.