Skip to content

Instantly share code, notes, and snippets.

@olafurjohannsson
Created January 9, 2019 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olafurjohannsson/25033d613e8e51352c340e058be52c0a to your computer and use it in GitHub Desktop.
Save olafurjohannsson/25033d613e8e51352c340e058be52c0a to your computer and use it in GitHub Desktop.
C++ geodetic2ecef - lat lon to cartesian, assuming an ellipsoid
#include <math.h>
constexpr double R = 6378.137;
constexpr double ESQ (6.69437999014 * 0.001);
constexpr double DEG2RAD = M_PI / 180.0;
template<typename T>
struct point {
using coordinate_type = T;
T x;
T y;
T z;
};
template<class T> using Point = point<T>;
// Assumes a ellipsoid, this is more accurate than the classic sphere conversion
Point<double> geodetic2ecef( double lat, double lon, double alt ) {
lat *= DEG2RAD;
lon *= DEG2RAD;
auto xi = std::sqrt( 1 - ESQ * std::sin( lat ) * std::sin( lat ));
auto x = ( R / xi + alt ) * std::cos( lat ) * std::cos( lon );
auto y = ( R / xi + alt ) * std::cos( lat ) * std::sin( lon );
auto z = ( R / xi * ( 1 - ESQ) + alt ) * std::sin( lat );
return Point<double>{ x, y, z };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment