Search code examples
c++boosttypesgeospatialboost-units

using boost::units to calculate geo coordinates


I'm trying to do a type-safe C++ implementation of the formula from [Calculate distance, bearing and more between Latitude/Longitude points][1]. Unfortunately I'm running into C++ type errors that bury the actual problem under endless template expansions. I think I'm really close:

#include <iostream>
#include <boost/units/systems/angle/degrees.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/plane_angle.hpp>
#include <boost/units/systems/si/prefixes.hpp>
#include <boost/units/cmath.hpp>
#include <boost/units/io.hpp>

using namespace boost::units;
using namespace boost::units::si;

struct Position
{
public:
    using angle_type = quantity<degree::plane_angle>;
    Position(const angle_type &latitude, const angle_type &longitude) : m_latitude{latitude}, m_longitude{longitude} {}
    angle_type m_latitude;
    angle_type m_longitude;
};

const quantity<si::length> earth_radius{6371. * kilo * meters};

Position move(const Position &start, quantity<degree::plane_angle> bearing, quantity<si::length> distance)
{
    const auto angular_distance = distance / earth_radius;

    auto latitude2 = asin(sin(start.m_latitude) * cos(angular_distance) +
                          cos(start.m_latitude) * sin(angular_distance) * cos(bearing));

    auto longitude2 = start.m_longitude + atan2(sin(bearing) * sin(angular_distance) * cos(start.m_latitude),
                                                cos(angular_distance) - sin(start.m_latitude) * sin(latitude2));
    return Position(latitude2, longitude2);
}

int main(int, char **)
{
    return 0;
}

Error messages:

/home/jpo/src/units/main.cpp:30:41: error: no match for ‘operator+’
(operand types are ‘const angle_type’ and ‘double’)

   30 |     auto longitude2 = start.m_longitude + atan2(sin(bearing) * sin(angular_distance) * cos(start.m_latitude),
      |                       ~~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |                             |                  |
      |                             |                  double
      |                             const angle_type

Solution

  • Problem is, that

    const auto angular_distance = distance / earth_radius;
    

    is dimensionless when it should be an angle. Changing this to

    quantity<degree::plane_angle> angular_distance{(distance / earth_radius).value() * radians};
    

    makes the code compile.