Last active
December 2, 2016 21:22
-
-
Save bangonkali/5dc8bc0164c919c090298f6233e4de8b to your computer and use it in GitHub Desktop.
Gets the distance between two latitude and longitude points.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.geodatasource.com/developers/c-sharp | |
using System; | |
namespace <your_namespace> | |
{ | |
public class GeoCoordinate | |
{ | |
public double Latitude { get; set; } | |
public double Longitude { get; set; } | |
public GeoCoordinate(double latitude, double longitude) | |
{ | |
Latitude = latitude; | |
Longitude = longitude; | |
} | |
public double GetDistanceTo(GeoCoordinate coordinate) | |
{ | |
return Distance(Latitude, Longitude, coordinate.Latitude, coordinate.Longitude, 'K'); | |
} | |
public double GetDistanceToInKm(GeoCoordinate coordinate) | |
{ | |
return Distance(Latitude, Longitude, coordinate.Latitude, coordinate.Longitude, 'K'); | |
} | |
public double GetDistanceToInNauticalMiles(GeoCoordinate coordinate) | |
{ | |
return Distance(Latitude, Longitude, coordinate.Latitude, coordinate.Longitude, 'N'); | |
} | |
private static double Distance(double lat1, double lon1, double lat2, double lon2, char unit) | |
{ | |
double theta = lon1 - lon2; | |
double dist = Math.Sin(Deg2Rad(lat1)) * Math.Sin(Deg2Rad(lat2)) + Math.Cos(Deg2Rad(lat1)) * Math.Cos(Deg2Rad(lat2)) * Math.Cos(Deg2Rad(theta)); | |
dist = Math.Acos(dist); | |
dist = Rad2Deg(dist); | |
dist = dist * 60 * 1.1515; | |
if (unit == 'K') | |
{ | |
dist = dist * 1.609344; | |
} | |
else if (unit == 'N') | |
{ | |
dist = dist * 0.8684; | |
} | |
return (dist); | |
} | |
private static double Deg2Rad(double deg) | |
{ | |
return (deg * Math.PI / 180.0); | |
} | |
private static double Rad2Deg(double rad) | |
{ | |
return (rad / Math.PI * 180.0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment