Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

How to calculate distance between two geographical coordinates? (C#)

Geolocation manipulations become quite often programming task. Below is a simple function that calculated distance between two coordinates in kilometers. If you prefer miles, simply multiply results by 0.6214.

 public  static  double  GetDistance(double  Lat1, double  Lon1, double  Lat2, double  Lon2)
 {
     int  R = 6371;
 
     double  rLat1 = ToRadian(Lat1);
     double  rLat2 = ToRadian(Lat2);
 
     double  dLat = rLat2 - rLat1;
     double  dLon = ToRadian(Lon2 - Lon1);
 
     double  a = Math .Pow(Math .Sin(dLat / 2), 2) + 
         Math .Pow(Math .Sin(dLon / 2), 2) *
         Math .Cos(rLat1) * Math .Cos(rLat2);
 
     double  b = 2 * Math .Atan2(Math .Sqrt(a), Math .Sqrt(1 - a));
 
     return  R * b;
 }
 
 public  static  double  ToRadian(double  Grad)
 {
     return  Math .PI * Grad / 180;
 }
 

Enjoy!