Last active
August 29, 2015 14:02
-
-
Save dotMorten/2f8b710b615286457ce8 to your computer and use it in GitHub Desktop.
Gets the location based on a start point, a heading and a distance.
This file contains 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
using System; | |
namespace CodeFormulaOfTheDay | |
{ | |
/// <summary> | |
/// Extension methods for geodesic calculations. | |
/// </summary> | |
public static class Geodesic | |
{ | |
/// <summary> | |
/// Earth circumference in meters used for distance calculations - based on WGS84 ellipsoid. Change this to miles or kilometers to get | |
/// inputs/outputs in those units | |
/// </summary> | |
private const double EarthCircumference = 6378137; | |
/// <summary> | |
/// Gets the location based on a start point, a heading and a distance. | |
/// </summary> | |
/// <param name="startLat">The start latitude.</param> | |
/// <param name="startLong">The start longitude.</param> | |
/// <param name="distanceMeters">The distance in meters travelled in the direction of <c>heading</c>.</param> | |
/// <param name="heading">The heading in degrees.</param> | |
/// <param name="locationLat">The location latitude.</param> | |
/// <param name="locationLong">The location longitude.</param> | |
public static void GetLocationFromHeading(double startLat, double startLong, double distanceMeters, double heading, | |
out double locationLat, out double locationLong) | |
{ | |
double brng = heading / 180 * Math.PI; | |
double lon1 = startLong / 180 * Math.PI; | |
double lat1 = startLat / 180 * Math.PI; | |
double dR = distanceMeters / EarthCircumference; //Angular distance in radians | |
double lat2 = Math.Asin(Math.Sin(lat1) * Math.Cos(dR) + Math.Cos(lat1) * Math.Sin(dR) * Math.Cos(brng)); | |
double lon2 = lon1 + Math.Atan2(Math.Sin(brng) * Math.Sin(dR) * Math.Cos(lat1), Math.Cos(dR) - Math.Sin(lat1) * Math.Sin(lat2)); | |
double lon = lon2 / Math.PI * 180; | |
double lat = lat2 / Math.PI * 180; | |
while (lon < -180) lon += 360; | |
while (lat < -90) lat += 180; | |
while (lon > 180) lon -= 360; | |
while (lat > 90) lat -= 180; | |
locationLat = lat; | |
locationLong = lon; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment