Title: Distance using Longitude and latitude
Author: Chhibs
Email: annum0@gmail.com
Member ID: 12345
Language: C++
Platform: Windows, Linux
Technology: WiMAX,WiFi, WDM
Level: Intermediate, Advanced
Description: A quick code dump for **haversine formula**
Section Language c++
SubSection Howto

## Introduction

I have seen code for calculating distance using the haversine
formula using C# etc on the site, but nothing using c++, so here is the
code that just does that

## Background (optional)

I saw couple fo articles doing thie distance calculation using the
haversine formula but using .Net instead, since I code in C++(no .Net
until really needed), I ported to c++ and below is the code

From math forum

http://mathforum.org/library/drmath/view/51879.html

Presuming a spherical Earth with radius R (see below), and that the
locations of the two points in spherical coordinates (longitude and
latitude) are lon1,lat1 and lon2,lat2, then the Haversine Formula
(from R. W. Sinnott, "Virtues of the Haversine," Sky and Telescope,
vol. 68, no. 2, 1984, p. 159):
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
will give mathematically and computationally exact results. The
intermediate result c is the great circle distance in radians. The
great circle distance d will be in the same units as R.

## Using the code

I am basically just posting a snippet of code that I use in a class which does the distance calculation for me

#include <span class="code-keyword"><cmath></span>
double PI = 4.0*atan(1.0);
double dlat1=lat1*(PI/180);
double dlong1=long1*(PI/180);
double dlat2=lat2*(PI/180);
double dlong2=long2*(PI/180);
double dLong=dlong1-dlong2;
double dLat=dlat1-dlat2;
double aHarv= pow(sin(dLat/2.0),2.0)+cos(dlat1)*cos(dlat2)*pow(sin(dLong/2),2);
double cHarv=2*atan2(sqrt(aHarv),sqrt(1.0-aHarv));
const double earth=3963.19;
double distance=earth*cHarv;