QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QGCGeo.cc
Go to the documentation of this file.
1/****************************************************************************
2 *
3 * (c) 2009-2024 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 *
5 * QGroundControl is licensed according to the terms in the file
6 * COPYING.md in the root of the source code directory.
7 *
8 ****************************************************************************/
9
10#include "QGCGeo.h"
11#include "QGCLoggingCategory.h"
12
13#include <QtCore/QLocale>
14#include <QtCore/QRegularExpression>
15#include <QtCore/QString>
16
17#include <cmath>
18
19#include <GeographicLib/Geocentric.hpp>
20#include <GeographicLib/Geodesic.hpp>
21#include <GeographicLib/GeodesicLine.hpp>
22#include <GeographicLib/LocalCartesian.hpp>
23#include <GeographicLib/MGRS.hpp>
24#include <GeographicLib/PolygonArea.hpp>
25#include <GeographicLib/UTMUPS.hpp>
26
27QGC_LOGGING_CATEGORY(QGCGeoLog, "Utilities.QGCGeo")
28
29namespace QGCGeo
30{
31
32// ============================================================================
33// NED (North-East-Down) Local Tangent Plane
34// ============================================================================
35
36void convertGeoToNed(const QGeoCoordinate &coord, const QGeoCoordinate &origin, double &x, double &y, double &z)
37{
38 if (coord == origin) {
39 x = y = z = 0.0;
40 return;
41 }
42
43 // Handle NaN altitude (QGeoCoordinate without altitude set)
44 const double originAlt = std::isnan(origin.altitude()) ? 0.0 : origin.altitude();
45 const double coordAlt = std::isnan(coord.altitude()) ? 0.0 : coord.altitude();
46
47 double east, north, up;
48 GeographicLib::LocalCartesian ltp(origin.latitude(), origin.longitude(), originAlt,
49 GeographicLib::Geocentric::WGS84());
50 ltp.Forward(coord.latitude(), coord.longitude(), coordAlt, east, north, up);
51
52 // Convert ENU to NED
53 x = north;
54 y = east;
55 z = -up;
56}
57
58void convertNedToGeo(double x, double y, double z, const QGeoCoordinate &origin, QGeoCoordinate &coord)
59{
60 // Convert NED to ENU
61 const double east = y;
62 const double north = x;
63 const double up = -z;
64
65 // Handle NaN altitude
66 const double originAlt = std::isnan(origin.altitude()) ? 0.0 : origin.altitude();
67
68 double lat, lon, alt;
69 GeographicLib::LocalCartesian ltp(origin.latitude(), origin.longitude(), originAlt,
70 GeographicLib::Geocentric::WGS84());
71 ltp.Reverse(east, north, up, lat, lon, alt);
72
73 coord.setLatitude(lat);
74 coord.setLongitude(lon);
75 coord.setAltitude(alt);
76}
77
78// ============================================================================
79// ENU (East-North-Up) Local Tangent Plane
80// ============================================================================
81
82QVector3D convertGpsToEnu(const QGeoCoordinate &coord, const QGeoCoordinate &ref)
83{
84 double x, y, z;
85 GeographicLib::LocalCartesian ltp(ref.latitude(), ref.longitude(), ref.altitude(),
86 GeographicLib::Geocentric::WGS84());
87 ltp.Forward(coord.latitude(), coord.longitude(), coord.altitude(), x, y, z);
88 return QVector3D(x, y, z);
89}
90
91QGeoCoordinate convertEnuToGps(const QVector3D &enu, const QGeoCoordinate &ref)
92{
93 double lat, lon, alt;
94 GeographicLib::LocalCartesian ltp(ref.latitude(), ref.longitude(), ref.altitude(),
95 GeographicLib::Geocentric::WGS84());
96 ltp.Reverse(enu.x(), enu.y(), enu.z(), lat, lon, alt);
97 return QGeoCoordinate(lat, lon, alt);
98}
99
100// ============================================================================
101// ECEF (Earth-Centered Earth-Fixed)
102// ============================================================================
103
104QVector3D convertGeodeticToEcef(const QGeoCoordinate &coord)
105{
106 double x, y, z;
107 GeographicLib::Geocentric::WGS84().Forward(coord.latitude(), coord.longitude(), coord.altitude(), x, y, z);
108 return QVector3D(x, y, z);
109}
110
111QGeoCoordinate convertEcefToGeodetic(const QVector3D &ecef)
112{
113 double lat, lon, alt;
114 GeographicLib::Geocentric::WGS84().Reverse(ecef.x(), ecef.y(), ecef.z(), lat, lon, alt);
115 return QGeoCoordinate(lat, lon, alt);
116}
117
118QVector3D convertEcefToEnu(const QVector3D &ecef, const QGeoCoordinate &ref)
119{
120 // ECEF -> Geodetic
121 double lat, lon, h;
122 GeographicLib::Geocentric::WGS84().Reverse(ecef.x(), ecef.y(), ecef.z(), lat, lon, h);
123
124 // Geodetic -> ENU
125 double x, y, z;
126 GeographicLib::LocalCartesian ltp(ref.latitude(), ref.longitude(), ref.altitude(),
127 GeographicLib::Geocentric::WGS84());
128 ltp.Forward(lat, lon, h, x, y, z);
129 return QVector3D(x, y, z);
130}
131
132QVector3D convertEnuToEcef(const QVector3D &enu, const QGeoCoordinate &ref)
133{
134 // ENU -> Geodetic
135 double lat, lon, h;
136 GeographicLib::LocalCartesian ltp(ref.latitude(), ref.longitude(), ref.altitude(),
137 GeographicLib::Geocentric::WGS84());
138 ltp.Reverse(enu.x(), enu.y(), enu.z(), lat, lon, h);
139
140 // Geodetic -> ECEF
141 double x, y, z;
142 GeographicLib::Geocentric::WGS84().Forward(lat, lon, h, x, y, z);
143 return QVector3D(x, y, z);
144}
145
146// ============================================================================
147// UTM (Universal Transverse Mercator)
148// ============================================================================
149
150int convertGeoToUTM(const QGeoCoordinate &coord, double &easting, double &northing)
151{
152 try {
153 int zone;
154 bool northp;
155 GeographicLib::UTMUPS::Forward(coord.latitude(), coord.longitude(), zone, northp, easting, northing);
156 return zone;
157 } catch (const GeographicLib::GeographicErr &e) {
158 qCDebug(QGCGeoLog) << e.what();
159 return 0;
160 }
161}
162
163bool convertUTMToGeo(double easting, double northing, int zone, bool southhemi, QGeoCoordinate &coord)
164{
165 try {
166 double lat, lon;
167 GeographicLib::UTMUPS::Reverse(zone, !southhemi, easting, northing, lat, lon);
168 coord.setLatitude(lat);
169 coord.setLongitude(lon);
170 return true;
171 } catch (const GeographicLib::GeographicErr &e) {
172 qCDebug(QGCGeoLog) << e.what();
173 return false;
174 }
175}
176
177// ============================================================================
178// MGRS (Military Grid Reference System)
179// ============================================================================
180
181QString convertGeoToMGRS(const QGeoCoordinate &coord)
182{
183 try {
184 int zone;
185 bool northp;
186 double x, y;
187 GeographicLib::UTMUPS::Forward(coord.latitude(), coord.longitude(), zone, northp, x, y);
188
189 std::string mgrs;
190 GeographicLib::MGRS::Forward(zone, northp, x, y, coord.latitude(), 5, mgrs);
191
192 // Format with spaces: "32TMT6588647092" -> "32TMT 65886 47092"
193 const QString qstr = QString::fromStdString(mgrs);
194 for (int i = qstr.length() - 1; i >= 0; i--) {
195 if (!qstr.at(i).isDigit()) {
196 const int numLen = (qstr.length() - i - 1) / 2;
197 return qstr.left(i + 1) + " " + qstr.mid(i + 1, numLen) + " " + qstr.mid(i + 1 + numLen);
198 }
199 }
200 return qstr;
201 } catch (const GeographicLib::GeographicErr &e) {
202 qCDebug(QGCGeoLog) << e.what();
203 return QString();
204 }
205}
206
207bool convertMGRSToGeo(const QString &mgrs, QGeoCoordinate &coord)
208{
209 try {
210 int zone, prec;
211 bool northp;
212 double x, y;
213 GeographicLib::MGRS::Reverse(mgrs.simplified().replace(" ", "").toStdString(), zone, northp, x, y, prec);
214
215 double lat, lon;
216 GeographicLib::UTMUPS::Reverse(zone, northp, x, y, lat, lon);
217
218 coord.setLatitude(lat);
219 coord.setLongitude(lon);
220 return true;
221 } catch (const GeographicLib::GeographicErr &e) {
222 qCDebug(QGCGeoLog) << e.what();
223 return false;
224 }
225}
226
227// ============================================================================
228// DMS (Degrees Minutes Seconds)
229// ============================================================================
230
231QString convertDegreesToDMS(double value, bool isLatitude)
232{
233 const QChar hemisphere = isLatitude ? ((value < 0) ? QLatin1Char('S') : QLatin1Char('N'))
234 : ((value < 0) ? QLatin1Char('W') : QLatin1Char('E'));
235
236 // Round once in hundredths of a second so seconds never display as 60.00
237 const qint64 hundredths = std::llround(std::abs(value) * 360000.0);
238 const qint64 degrees = hundredths / 360000;
239 const qint64 minutes = (hundredths % 360000) / 6000;
240 const double seconds = static_cast<double>(hundredths % 6000) / 100.0;
241
242 return QStringLiteral("%1° %2' %3\" %4").arg(degrees).arg(minutes).arg(seconds, 0, 'f', 2).arg(hemisphere);
243}
244
245double convertDMSToDegrees(const QString &text, bool isLatitude, bool *ok)
246{
247 if (ok) {
248 *ok = false;
249 }
250
251 QString s = text.trimmed().toUpper();
252 if (s.isEmpty()) {
253 return 0.0;
254 }
255
256 // Optional hemisphere letter, leading or trailing
257 const QChar positive = isLatitude ? QLatin1Char('N') : QLatin1Char('E');
258 const QChar negative = isLatitude ? QLatin1Char('S') : QLatin1Char('W');
259 QChar hemisphere;
260 if (s.back().isLetter()) {
261 hemisphere = s.back();
262 s.chop(1);
263 } else if (s.front().isLetter()) {
264 hemisphere = s.front();
265 s.remove(0, 1);
266 }
267 if (!hemisphere.isNull() && (hemisphere != positive) && (hemisphere != negative)) {
268 return 0.0;
269 }
270
271 // Degree/minute/second marks (ASCII and typographic) act as separators
272 static const QRegularExpression marks(QStringLiteral("[°º'\"′″]"));
273 s.replace(marks, QStringLiteral(" "));
274 static const QRegularExpression whitespace(QStringLiteral("\\s+"));
275 const QStringList fields = s.split(whitespace, Qt::SkipEmptyParts);
276 if (fields.isEmpty() || (fields.size() > 3)) {
277 return 0.0;
278 }
279
280 double values[3] = {0.0, 0.0, 0.0};
281 for (qsizetype i = 0; i < fields.size(); i++) {
282 bool fieldOk = false;
283 values[i] = QLocale::c().toDouble(fields.at(i), &fieldOk);
284 if (!fieldOk || !std::isfinite(values[i])) {
285 return 0.0;
286 }
287 }
288
289 const bool negativeDegrees = fields.at(0).startsWith(QLatin1Char('-'));
290 const double minutes = values[1];
291 const double seconds = values[2];
292 if ((minutes < 0) || (minutes >= 60) || (seconds < 0) || (seconds >= 60)) {
293 return 0.0;
294 }
295 // Only whole degrees may be followed by minutes, and only whole minutes by seconds
296 if (((fields.size() > 1) && (values[0] != std::trunc(values[0]))) || ((fields.size() > 2) && (minutes != std::trunc(minutes)))) {
297 return 0.0;
298 }
299 // A '-' together with a hemisphere letter is ambiguous
300 if (negativeDegrees && !hemisphere.isNull()) {
301 return 0.0;
302 }
303
304 double degrees = std::abs(values[0]) + (minutes / 60.0) + (seconds / 3600.0);
305 if (negativeDegrees || (hemisphere == negative)) {
306 degrees = -degrees;
307 }
308 if (std::abs(degrees) > (isLatitude ? 90.0 : 180.0)) {
309 return 0.0;
310 }
311
312 if (ok) {
313 *ok = true;
314 }
315 return degrees;
316}
317
318bool convertDMSToGeo(const QString &latitude, const QString &longitude, QGeoCoordinate &coord)
319{
320 bool latOk = false;
321 bool lonOk = false;
322 const double lat = convertDMSToDegrees(latitude, true, &latOk);
323 const double lon = convertDMSToDegrees(longitude, false, &lonOk);
324 if (!latOk || !lonOk) {
325 return false;
326 }
327
328 coord.setLatitude(lat);
329 coord.setLongitude(lon);
330 return true;
331}
332
333// ============================================================================
334// Geodesic Calculations (Great Circle on Ellipsoid)
335// ============================================================================
336
337double geodesicDistance(const QGeoCoordinate &from, const QGeoCoordinate &to)
338{
339 double distance;
340 GeographicLib::Geodesic::WGS84().Inverse(from.latitude(), from.longitude(),
341 to.latitude(), to.longitude(), distance);
342 return distance;
343}
344
345double geodesicAzimuth(const QGeoCoordinate &from, const QGeoCoordinate &to)
346{
347 double distance, azimuth1, azimuth2;
348 GeographicLib::Geodesic::WGS84().Inverse(from.latitude(), from.longitude(),
349 to.latitude(), to.longitude(), distance, azimuth1, azimuth2);
350
351 // Normalize to [0, 360)
352 if (azimuth1 < 0.0) {
353 azimuth1 += 360.0;
354 }
355 return azimuth1;
356}
357
358QGeoCoordinate geodesicDestination(const QGeoCoordinate &from, double azimuth, double distance)
359{
360 double lat, lon;
361 GeographicLib::Geodesic::WGS84().Direct(from.latitude(), from.longitude(), azimuth, distance, lat, lon);
362 return QGeoCoordinate(lat, lon, from.altitude());
363}
364
365// ============================================================================
366// Path and Polygon Calculations
367// ============================================================================
368
369double pathLength(const QList<QGeoCoordinate> &path)
370{
371 if (path.size() < 2) {
372 return 0.0;
373 }
374
375 double totalLength = 0.0;
376 for (int i = 1; i < path.size(); ++i) {
377 totalLength += geodesicDistance(path[i - 1], path[i]);
378 }
379 return totalLength;
380}
381
382double polygonArea(const QList<QGeoCoordinate> &polygon)
383{
384 if (polygon.size() < 3) {
385 return 0.0;
386 }
387
388 GeographicLib::PolygonArea poly(GeographicLib::Geodesic::WGS84());
389 for (const QGeoCoordinate &coord : polygon) {
390 poly.AddPoint(coord.latitude(), coord.longitude());
391 }
392
393 double perimeter, area;
394 poly.Compute(false, true, perimeter, area);
395 // Area sign indicates winding order (positive = counter-clockwise, negative = clockwise).
396 // Return absolute value since we only care about magnitude.
397 return qAbs(area);
398}
399
400double polygonPerimeter(const QList<QGeoCoordinate> &polygon)
401{
402 if (polygon.size() < 2) {
403 return 0.0;
404 }
405
406 GeographicLib::PolygonArea poly(GeographicLib::Geodesic::WGS84());
407 for (const QGeoCoordinate &coord : polygon) {
408 poly.AddPoint(coord.latitude(), coord.longitude());
409 }
410
411 double perimeter, area;
412 poly.Compute(false, true, perimeter, area);
413 return perimeter;
414}
415
416QList<QGeoCoordinate> interpolatePath(const QGeoCoordinate &from, const QGeoCoordinate &to, int numPoints)
417{
418 QList<QGeoCoordinate> result;
419
420 // Clamp to reasonable bounds to prevent excessive memory allocation
421 constexpr int kMaxPoints = 10000;
422 if (numPoints < 2) {
423 numPoints = 2;
424 } else if (numPoints > kMaxPoints) {
425 qCWarning(QGCGeoLog) << "interpolatePath: numPoints" << numPoints << "exceeds maximum, clamping to" << kMaxPoints;
426 numPoints = kMaxPoints;
427 }
428
429 if (from == to) {
430 for (int i = 0; i < numPoints; ++i) {
431 result.append(from);
432 }
433 return result;
434 }
435
436 // Create GeodesicLine for efficient multi-point interpolation
437 const GeographicLib::GeodesicLine line = GeographicLib::Geodesic::WGS84().InverseLine(
438 from.latitude(), from.longitude(), to.latitude(), to.longitude());
439
440 const double totalDistance = line.Distance();
441 const double altDiff = to.altitude() - from.altitude();
442
443 for (int i = 0; i < numPoints; ++i) {
444 const double fraction = static_cast<double>(i) / (numPoints - 1);
445 const double distance = totalDistance * fraction;
446
447 double lat, lon;
448 line.Position(distance, lat, lon);
449
450 const double alt = from.altitude() + altDiff * fraction;
451 result.append(QGeoCoordinate(lat, lon, alt));
452 }
453
454 return result;
455}
456
457QGeoCoordinate interpolateAtDistance(const QGeoCoordinate &from, const QGeoCoordinate &to, double distance)
458{
459 if (from == to || distance <= 0.0) {
460 return from;
461 }
462
463 const GeographicLib::GeodesicLine line = GeographicLib::Geodesic::WGS84().InverseLine(
464 from.latitude(), from.longitude(), to.latitude(), to.longitude());
465
466 const double totalDistance = line.Distance();
467
468 if (distance >= totalDistance) {
469 return to;
470 }
471
472 double lat, lon;
473 line.Position(distance, lat, lon);
474
475 // Linear altitude interpolation
476 const double fraction = distance / totalDistance;
477 const double alt = from.altitude() + (to.altitude() - from.altitude()) * fraction;
478
479 return QGeoCoordinate(lat, lon, alt);
480}
481
482} // namespace QGCGeo
Geographic coordinate conversion utilities using GeographicLib.
#define QGC_LOGGING_CATEGORY(name, categoryStr)
QList< QGeoCoordinate > interpolatePath(const QGeoCoordinate &from, const QGeoCoordinate &to, int numPoints)
Definition QGCGeo.cc:416
QVector3D convertEcefToEnu(const QVector3D &ecef, const QGeoCoordinate &ref)
Definition QGCGeo.cc:118
void convertGeoToNed(const QGeoCoordinate &coord, const QGeoCoordinate &origin, double &x, double &y, double &z)
Definition QGCGeo.cc:36
double polygonPerimeter(const QList< QGeoCoordinate > &polygon)
Definition QGCGeo.cc:400
double geodesicAzimuth(const QGeoCoordinate &from, const QGeoCoordinate &to)
Definition QGCGeo.cc:345
QVector3D convertGeodeticToEcef(const QGeoCoordinate &coord)
Definition QGCGeo.cc:104
QGeoCoordinate geodesicDestination(const QGeoCoordinate &from, double azimuth, double distance)
Definition QGCGeo.cc:358
double convertDMSToDegrees(const QString &text, bool isLatitude, bool *ok)
Definition QGCGeo.cc:245
QGeoCoordinate convertEcefToGeodetic(const QVector3D &ecef)
Definition QGCGeo.cc:111
QString convertGeoToMGRS(const QGeoCoordinate &coord)
Definition QGCGeo.cc:181
double pathLength(const QList< QGeoCoordinate > &path)
Definition QGCGeo.cc:369
double polygonArea(const QList< QGeoCoordinate > &polygon)
Definition QGCGeo.cc:382
double geodesicDistance(const QGeoCoordinate &from, const QGeoCoordinate &to)
Definition QGCGeo.cc:337
bool convertDMSToGeo(const QString &latitude, const QString &longitude, QGeoCoordinate &coord)
Definition QGCGeo.cc:318
QVector3D convertEnuToEcef(const QVector3D &enu, const QGeoCoordinate &ref)
Definition QGCGeo.cc:132
int convertGeoToUTM(const QGeoCoordinate &coord, double &easting, double &northing)
Definition QGCGeo.cc:150
void convertNedToGeo(double x, double y, double z, const QGeoCoordinate &origin, QGeoCoordinate &coord)
Definition QGCGeo.cc:58
QGeoCoordinate convertEnuToGps(const QVector3D &enu, const QGeoCoordinate &ref)
Definition QGCGeo.cc:91
QVector3D convertGpsToEnu(const QGeoCoordinate &coord, const QGeoCoordinate &ref)
Definition QGCGeo.cc:82
bool convertUTMToGeo(double easting, double northing, int zone, bool southhemi, QGeoCoordinate &coord)
Definition QGCGeo.cc:163
QString convertDegreesToDMS(double value, bool isLatitude)
Definition QGCGeo.cc:231
QGeoCoordinate interpolateAtDistance(const QGeoCoordinate &from, const QGeoCoordinate &to, double distance)
Definition QGCGeo.cc:457
bool convertMGRSToGeo(const QString &mgrs, QGeoCoordinate &coord)
Definition QGCGeo.cc:207