36
• # KB: Distance between two points on globe - Calculation using C#

 SUNDAY, MARCH 28, 2010

The Haversine formula is used for calculating the distance between two points on the globe. This function gives a nearly accurate distance value, and is used widely in GPS related calculations and for vehicle tracking. This article provides a code snippet for calculating distance between two points taking latitude and longitude values as example.

This article is a sequel to the previous article on the same topic, but using T-SQL for calculation - Calculate distance between two points on globe from latitude and longitude coordinates. Please refer to this article for details of the Haversine formula and distance calculation.

The C# implementation of the Haversine formula is:

public double GetDistanceBetweenPoints(double lat1, double long1, double lat2, double long2)
{
double distance = 0;

double dLat = (lat2 - lat1) / 180* Math.PI;
double dLong = (long2 - long1) / 180 * Math.PI;

double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
+ Math.Cos(lat2) * Math.Sin(dLong/2) * Math.Sin(dLong/2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

// For this you can assume any of the two points.

//Numerator part of function
double nr = Math.Pow(radiusE * radiusP * Math.Cos(lat1 / 180 * Math.PI), 2);
//Denominator part of the function
double dr = Math.Pow(radiusE * Math.Cos(lat1 / 180 * Math.PI), 2)
+ Math.Pow(radiusP * Math.Sin(lat1 / 180 * Math.PI), 2);
double radius = Math.Sqrt(nr / dr);

//Calaculate distance in metres. Web Scraping - Extract all links from a web page using VB.NET Visual Basic .NET 50944 views Shopping Cart display using ASP.NET ListView and floating DIV (CSS) ASP.NET 50371 views Tableless layouts using floating DIV Web Designing 44966 views Generate High Quality Favicon.ico Web Designing 33350 views Simple Website Scraping: Extract all text contents from webpage C#.NET 27421 views