Skip to content

Instantly share code, notes, and snippets.

@stuartd
Created April 17, 2019 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stuartd/96f78589e0b7ff293ae72bfc883b22e8 to your computer and use it in GitHub Desktop.
Save stuartd/96f78589e0b7ff293ae72bfc883b22e8 to your computer and use it in GitHub Desktop.
public enum DistanceType {
Miles = 1,
Kilometers,
Feet,
Meter
}
public static class DistanceCalculator {
private const double radianCalculator = Math.PI / 180;
public static DistanceResult CalculateDistance(double lat1, double lon1, double lat2, double lon2, DistanceType type) {
return CalculateDistance(
new LatLong { Latitude = lat1, Longitude = lon1 },
new LatLong { Latitude = lat2, Longitude = lon2 }, type);
}
public static DistanceResult CalculateDistance(LocationConstraint loc1, LocationConstraint loc2, DistanceType type) {
return CalculateDistance(new LatLong(loc1), new LatLong(loc2), type);
}
public static DistanceResult CalculateDistance(ILatLong pos1, ILatLong pos2, DistanceType type) {
// This is the Haversine formula.
double radiusOfEarth;
switch (type) {
case DistanceType.Miles:
radiusOfEarth = 3960;
break;
case DistanceType.Kilometers:
radiusOfEarth = 6371;
break;
case DistanceType.Feet:
throw new NotImplementedException();
case DistanceType.Meter:
throw new NotImplementedException();
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
double ToRadian(double value) {
return radianCalculator * value;
}
double latitudeDistance = ToRadian(pos2.Latitude - pos1.Latitude);
double longitudeDistance = ToRadian(pos2.Longitude - pos1.Longitude);
double lat1Radians = ToRadian(pos1.Latitude);
double lat2Radians = ToRadian(pos2.Latitude);
var a = Math.Sin(latitudeDistance / 2) * Math.Sin(latitudeDistance / 2) +
Math.Sin(longitudeDistance / 2) * Math.Sin(longitudeDistance / 2) *
Math.Cos(lat1Radians) * Math.Cos(lat2Radians);
double distance = radiusOfEarth * 2 * Math.Asin(Math.Sqrt(a));
return new DistanceResult(distance, type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment