Convert GPS Coordinates to Meters in code

Here are two utility functions to help you work with GPS coordinates on the ground. The functions are in C. I'll try to make a Bascom example soon.

typedef struct
{
float lat,
lng,
hdn;
} GPSPosition;
/* Returns distance between two lat,long pairs in meters
   current: where you are now (lat, long)
   desired: where you want to be
   return: how far you have to go
   heading is ignored in both structures */

float ComputeDistance(GPSPosition *current, GPSPosition *desired)
{
    float dlon, dlat, a, c;
    dlon = desired->lng - current->lng;
    dlat = desired->lat - current->lat;
    a = pow(sin(dlat/2),2) + cos(current->lat) * cos(desired->lat) * pow(sin(dlon/2),2);
    c = 2 * atan2(sqrt(a), sqrt(1-a));
    return 6378140 * c;  /* 6378140 is the radius of the Earth in meters*/

    /* Formulas from Dr. Math
       http://mathforum.org/library/drmath/view/51879.html

   */
}

/*    Returns radians east of north that you should head if you are
at current and wish to go to desired.
    current: your current lat, long
  desired: the lat, long you wish to go to
  return: radians east of north (-PI to +PI I think)
*/
float ComputeDesiredHeading(GPSPosition *current, GPSPosition *desired)
{
    float midterm, dummy;
    midterm = atan2
              (
              sin(desired->lng-current->lng)*cos(desired->lat),
              cos(current->lat)*sin(desired->lat)
-sin(current->lat)*cos(desired->lat)*cos(desired->lng-current->lng)
      );
    return modf(midterm, &dummy);

    /* Formulas from Dr. Math
   http://mathforum.org/library/drmath/view/55417.html
   */
}

 

Tags: