How would I go about resolving this in C#?

I have a line segment (great circle distance) defined by two Lon-Lat pairs (call them points A and B). A third point somewhere on the Earth sphere.

The line segment closes the shortest distance between A and B. Third Lon-Lat pair is the point C.

How do I calculate the distance between the point C, and the closest point on the AB segment?

In fact, I am looking for an algorithm to find the spherical distance between an arbitrary point C and a geodesic segment AB.

What i have for now:

public static float DistanceInKilometres(PointF A, PointF B, PointF C)
    var d13 = Haversine_KM_F(A, C);
    var R = 3961.3;
    var brng12 = Bearing(A, B);
    var brng13 = Bearing(A, C);
    var dXt = Math.Asin(Math.Sin(d13 / R) * Math.Sin(brng13 - brng12)) * R;
    return (float)dXt;

public static Double Bearing(PointF coordinate1, PointF coordinate2)
    var latitude1 = coordinate1.Y.ToRadian();
    var latitude2 = coordinate2.Y.ToRadian();
    var longitudeDifference = (coordinate2.X - coordinate1.X).ToRadian();
    var y = Math.Sin(longitudeDifference) * Math.Cos(latitude2);
    var x = Math.Cos(latitude1) * Math.Sin(latitude2) -
    Math.Sin(latitude1) * Math.Cos(latitude2) * Math.Cos(longitudeDifference);
    return (Math.Atan2(y, x).ToDegree() + 360) % 360;

private static float ToRadian(this float angle)
    return (float)(Math.PI * angle / 180.0);

private static float ToDegree(this float angle)
  return (float)(Math.PI * angle / 180.0);
  • Can you please elaborate on "this"? – CaptDragon Apr 11 '12 at 15:06
  • Hope I'm being clear. – JJ_Jason Apr 11 '12 at 15:15
  • I'm afraid it's not clear at all, JJ. Are you looking for an algorithm to find the spherical distance between an arbitrary point C and a geodesic segment AB? – whuber Apr 11 '12 at 16:15
  • Yes, exactly that. – JJ_Jason Apr 12 '12 at 9:06
  • Is that the same as this question? – Kirk Kuykendall Apr 12 '12 at 19:33

The more general problem, posed for an ellipsoid of revolution, is considered in Section 8 of


This gives solutions of the interception problem (the problem at hand) and the intersection problem using the ellipsoidal gnomonic projection. The same technique will apply to a sphere, of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.