# Distance between locations using latitude and longitude

, 16 Dec 2005 CPOL
 Rate this:
Calculate the distance between two locations given their latitude and longitude.

## Introduction

This code drop is part of a Smash and Grab series. I'll bet there are a lot of other programmers out there that would like to make code available to others, but just don't want to spend hours required to create a full-blown "CodeProject" article. This is an attempt to see if I can make some useful code available to other programmers, and do it in 10 minutes. I encourage others to contribute to "Smash and Grab".

The basic rules are:

• It should be a C# class, which solves a simple problem.
• Don't waste the reader's time with GUI stuff and "OnClick" methods.
• If at all possible, make it a console app with a "Main()" that illustrates its functionality.

The point of this series is to present usable pre-canned classes or techniques which solve a real world problem without going into too much detail about how it works. I mean, who really cares about how System.Collections.ArrayList works, you just use it.

Please fully comment the code so that the person who really cares (and has the time) will be able to understand the underlying algorithm.

## Using the code

I wanted a .NET class which would tell me the distance between two locations. There were all sorts of bits of code out on the net which attempted to do this in JavaScript but the programmers obviously could not separate the algorithm from the GUI. This is my humble attempt at a pure non-GUI class which will calculate the distance between two locations.

using System;
using System.Text;

public class CDistanceBetweenLocations
{
public static double Calc(double Lat1,
double Long1, double Lat2, double Long2)
{
/*
The Haversine formula according to Dr. Math.
http://mathforum.org/library/drmath/view/51879.html

dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
c = 2 * atan2(sqrt(a), sqrt(1-a))
d = R * c

Where
* dlon is the change in longitude
* dlat is the change in latitude
* c is the great circle distance in Radians.
* R is the radius of a spherical Earth.
* The locations of the two points in
spherical coordinates (longitude and
latitude) are lon1,lat1 and lon2, lat2.
*/
double dDistance = Double.MinValue;
double dLat1InRad = Lat1 * (Math.PI / 180.0);
double dLong1InRad = Long1 * (Math.PI / 180.0);
double dLat2InRad = Lat2 * (Math.PI / 180.0);
double dLong2InRad = Long2 * (Math.PI / 180.0);

// Intermediate result a.
double a = Math.Pow(Math.Sin(dLatitude / 2.0), 2.0) +
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;

return dDistance;
}

public static double Calc(string NS1, double Lat1, double Lat1Min,
string EW1, double Long1, double Long1Min, string NS2,
double Lat2, double Lat2Min, string EW2,
double Long2, double Long2Min)
{
double NS1Sign = NS1.ToUpper() == "N" ? 1.0 : -1.0;
double EW1Sign = EW1.ToUpper() == "E" ? 1.0 : -1.0;
double NS2Sign = NS2.ToUpper() == "N" ? 1.0 : -1.0;
double EW2Sign = EW2.ToUpper() == "E" ? 1.0 : -1.0;
return (Calc(
(Lat1 + (Lat1Min / 60)) * NS1Sign,
(Long1 + (Long1Min / 60)) * EW1Sign,
(Lat2 + (Lat2Min / 60)) * NS2Sign,
(Long2 + (Long2Min / 60)) * EW2Sign
));
}

public static void Main(string[] args)
{
if (args.Length < 12)
{
System.Console.WriteLine("usage: DistanceBetweenLocations" +
" N 43 35.500 W 80 27.800 N 43 35.925 W 80 28.318");
return;
}
System.Console.WriteLine(Calc(
args[0],
System.Double.Parse(args[1]),
System.Double.Parse(args[2]),
args[3],
System.Double.Parse(args[4]),
System.Double.Parse(args[5]),
args[6],
System.Double.Parse(args[7]),
System.Double.Parse(args[8]),
args[9],
System.Double.Parse(args[10]),
System.Double.Parse(args[11])));

}

}

Here is an MS-SQL user defined function. I never really understood why this math functionality was in SQL Server until now! You can use this function in a query statement to find the nearest Tim Horton's!!!

CREATE FUNCTION [dbo].[DistanceBetween] (@Lat1 as real,
@Long1 as real, @Lat2 as real, @Long2 as real)
RETURNS real
AS
BEGIN

SET @dLat1InRad = @Lat1 * (PI()/180.0);
SET @dLong1InRad = @Long1 * (PI()/180.0);
SET @dLat2InRad = @Lat2 * (PI()/180.0);
SET @dLong2InRad = @Long2 * (PI()/180.0);

DECLARE @dLongitude as float(53);
DECLARE @dLatitude as float(53);
/* Intermediate result a. */
DECLARE @a as float(53);
SET @a = SQUARE (SIN (@dLatitude / 2.0)) + COS (@dLat1InRad)
* SQUARE(SIN (@dLongitude / 2.0));
/* Intermediate result c (great circle distance in Radians). */
DECLARE @c as real;
SET @c = 2.0 * ATN2 (SQRT (@a), SQRT (1.0 - @a));
/* SET kEarthRadius = 3956.0 miles */
SET @kEarthRadius = 6376.5;        /* kms */

DECLARE @dDistance as real;
SET @dDistance = @kEarthRadius * @c;
return (@dDistance);
END

OK, this first one took me longer than 10 minutes, but the next one won't.

## Share

Software Developer (Senior)
No Biography provided

 First PrevNext
 My vote of 5 Bernard Chayer 27-Jun-13 6:47
 My vote of 4 9410662422 19-Oct-12 21:44
 question about the other way around omrivm 12-Aug-11 6:30
 question fithri 1-Aug-11 17:50
 Re: question Gary Dryden 2-Aug-11 4:46
 Question? Richardg3 27-Jul-11 22:24
 Re: Question? Gary Dryden 28-Jul-11 3:58
 Simpler Trig ziopino70 15-Apr-10 23:08
 Distance Calculator for Postgre The Swatchster 6-Apr-10 7:08
 Find one bug ! kingdomkao 13-Jan-09 15:51
 Re: Find one bug ! Member 2144619 5-Apr-09 6:22
 Thanks! Edithzor 29-Jul-08 13:28
 No nonsense - straight, working code LarsenLP 7-Sep-07 1:15
 Miles or Kilometers? deanj 30-Jul-07 10:10
 Re: Miles or Kilometers? Gary Dryden 30-Jul-07 13:33
 Finding lat and long for address sides_dale 14-Mar-06 16:14
 Re: Finding lat and long for address Gary Dryden 15-Mar-06 3:25
 From Bill SerGio Bill SerGio, The Infomercial King 17-Dec-05 0:49
 Unit testing Marc Clifton 16-Dec-05 9:40
 Not as good as my article Bill SerGio, The Infomercial King 16-Dec-05 6:31
 Re: Not as good as my article Harkos 16-Dec-05 11:06
 From Bill SerGio Bill SerGio, The Infomercial King 17-Dec-05 2:01
 Re: From Bill SerGio Simon Capewell 22-Dec-05 6:39
 Re: Not as good as my article jtstogner 16-Dec-05 16:20
 Re: Not as good as my article Gary Dryden 16-Dec-05 16:34
 Re: Not as good as my article jtstogner 16-Dec-05 19:50
 Re: Not as good as my article Bill SerGio, The Infomercial King 17-Dec-05 0:38
 Re: Not as good as my article jtstogner 17-Dec-05 4:01
 Re: Not as good as my article Bill SerGio, The Infomercial King 17-Dec-05 4:14
 Re: Not as good as my article jtstogner 17-Dec-05 4:23
 pathetic. Was: Re: Not as good as my article frugalmail 18-Dec-05 8:33
 Re: pathetic. Was: Re: Not as good as my article jtstogner 18-Dec-05 10:29
 Your English is So BAD! Bill SerGio, The Infomercial King 17-Dec-05 4:49
 Amercans don't support you tvproducer3 16-Aug-07 1:15
 Re: Amercans don't support you Dave19751995 27-Sep-07 8:18
 Re: Not as good as my article Bill SerGio, The Infomercial King 17-Dec-05 2:05
 Re: Not as good as my article Bill SerGio, The Infomercial King 17-Dec-05 0:34
 Re: Not as good as my article Simon Capewell 22-Dec-05 4:56
 Re: Not as good as my article Bill SerGio, The Infomercial King 22-Dec-05 5:45
 Re: Not as good as my article Simon Capewell 22-Dec-05 6:06
 Last Visit: 31-Dec-99 19:00     Last Update: 27-Mar-15 14:22 Refresh 12 Next »