Skip to content

Instantly share code, notes, and snippets.

@bangonkali
Last active December 2, 2016 21:22
Show Gist options
  • Save bangonkali/5dc8bc0164c919c090298f6233e4de8b to your computer and use it in GitHub Desktop.
Save bangonkali/5dc8bc0164c919c090298f6233e4de8b to your computer and use it in GitHub Desktop.
Gets the distance between two latitude and longitude points.
// 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