Normalizing latitude and longitude in C++

Posting here for convenient lookup later. There are numerous ways these angles can be “normalized”, but typically we want a latitude between -90 and 90 and a longitude between -180 and 180 (e.g., instead of allowing a longitude of 270, etc.). I’m including boilerplate conversions between radians and degrees here as well.

static double radiansToDegrees(double rad)
{
  return (rad * 180.0) / M_PI;
};

static double degreesToRadians(double deg)
{
  return (deg * M_PI) / 180.0;
}; 

static double normalizeLatitudeDegrees(double latitudeDeg)
{
  // Latitude: [-90, 90]
  double lowerBound{ -90.0 }, upperBound{ 90.0 };
  if (latitudeDeg >= lowerBound && latitudeDeg <= upperBound)
  {
    // No normalization required
    return latitudeDeg;
  }
  if (latitudeDeg >= 360.0 || latitudeDeg <= -360.0)
  {
    // Normalize to degree in (-360, 360)
    latitudeDeg = fmod(latitudeDeg, 360.0);
  }
  if (latitudeDeg < -90.0)
  {
    // Normalize to positive degree in [0, 360)
    latitudeDeg = 360.0 + latitudeDeg;
  }
  if (latitudeDeg > 90.0 && latitudeDeg <= 270.0)
  {
    // Normalize (90, 270] to [-90, 90]
    latitudeDeg = 180.0 - latitudeDeg;
  }
  if (latitudeDeg > 270.0)
  {
    // Normalize (270, 360] to [-90, 0]
    latitudeDeg = 270.0 - latitudeDeg;
  }
  return latitudeDeg;
}

static double normalizeLongitudeDegrees(double longitudeDeg)
{
  // Longitude: (-180, 180]
  double lowerBound{ -180.0 }, upperBound{ 180.0 };
  if (longitudeDeg > lowerBound && longitudeDeg <= upperBound)
  {
    // No normalization required
    return longitudeDeg;
  }
  if (longitudeDeg >= 360.0 || longitudeDeg <= -360.0)
  {
    // Normalize to degree in (-360, 360)
    longitudeDeg = fmod(longitudeDeg, 360.0);
  }
  if (longitudeDeg <= -180.0)
  {
    // Normalize to positive degree in [0, 180)
    longitudeDeg = 360.0 + longitudeDeg;
  }
  if (longitudeDeg > 180.0)
  {
    // Normalize to positive degree in (-180, 0)
    longitudeDeg = longitudeDeg - 360.0;
  }
  return longitudeDeg;
}

Leave a Comment