Monday, August 16, 2010

C# How to add distance and calculate new location from Lat\Lon

In one of my geo spatial projects I faced the need to calculate new Lat \ Lon location based on other Lat \ Lon Location , distance and bearing , for example what is the location that is 300 meters NE of a particular location as described in this illusrtartion :

Here is the formula that for given a start point, initial bearing, and distance it calculates the destination point and final bearing travelling along a (shortest distance) great circle arc

lat2 = asin(sin(lat1)*cos(d/R) + cos(lat1)*sin(d/R)*cos(θ))

lon2 = lon1 + atan2(sin(θ)*sin(d/R)*cos(lat1), cos(d/R)−sin(lat1)*sin(lat2))

Where d is the distance travelled and R is the earth’s radius , d/R is the angular distance (in radians)
Here is the a function written in C# that applies the formula :

const double EarthRadius = 6378137.0;
const double DegreesToRadians = 0.0174532925;
const double RadiansToDegrees = 57.2957795;
/// <summary>
/// Calculates the new-point from a given source at a given range (meters) and bearing (degrees). .
/// </summary>
/// <param name="source">Orginal Point</param>
/// <param name="range">Range in meters</param>
/// <param name="bearing">Bearing in degrees</param>
/// <returns>End-point from the source given the desired range and bearing.</returns>

public LatLon CalculateDerivedPosition(LatLon source, double range, double bearing)

{
double latA = source.Lat * DegreesToRadians;
double lonA = source.Lon * DegreesToRadians;
double angularDistance = range / EarthRadius;
double trueCourse = bearing * DegreesToRadians;

double lat = Math.Asin(Math.Sin(latA) * Math.Cos(angularDistance) +Math.Cos(latA) * Math.Sin(angularDistance) * Math.Cos(trueCourse));

double dlon = Math.Atan2(Math.Sin(trueCourse) * Math.Sin(angularDistance) * Math.Cos(latA),Math.Cos(angularDistance) - Math.Sin(latA) * Math.Sin(lat));
double lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI;

return new LatLon(lat * RadiansToDegrees,lon * RadiansToDegrees);

}

4 comments:

  1. Thanks for this :) Really help me.

    ReplyDelete
  2. Everybody loves you will find many interactions, I just genuinely veteran, I have give preference to additional information when it comes to this unique, for it happens to be fantastic., With the help of using pick up dispersal of. distance calculator UK

    ReplyDelete
  3. Bearing in degrees.What does this value means?

    ReplyDelete