Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qgeocoordinate.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
7
8#include <QDateTime>
9#include <QHash>
10#include <QDataStream>
11#include <QDebug>
12#include <QtCore/qmetaobject.h> // for QMetaEnum
13#include <QMetaType>
14#include <qnumeric.h>
15#include <qmath.h>
16
18
19QT_IMPL_METATYPE_EXTERN(QGeoCoordinate)
20
21static const double qgeocoordinate_EARTH_MEAN_RADIUS = 6371.0072;
22
23
24QGeoCoordinatePrivate::QGeoCoordinatePrivate():
25 lat(qQNaN()),
26 lng(qQNaN()),
27 alt(qQNaN())
28{}
29
30QGeoCoordinatePrivate::QGeoCoordinatePrivate(const QGeoCoordinatePrivate &other)
31 : QSharedData(other),
32 lat(other.lat),
33 lng(other.lng),
34 alt(other.alt),
35 altType(other.altType)
36{}
37
38QGeoCoordinatePrivate::~QGeoCoordinatePrivate()
39{}
40
41
42QGeoMercatorCoordinatePrivate::QGeoMercatorCoordinatePrivate():
43 QGeoCoordinatePrivate(),
44 m_mercatorX(qQNaN()),
45 m_mercatorY(qQNaN())
46{}
47
48QGeoMercatorCoordinatePrivate::QGeoMercatorCoordinatePrivate(const QGeoMercatorCoordinatePrivate &other)
49 : QGeoCoordinatePrivate(other),
50 m_mercatorX(other.m_mercatorX),
51 m_mercatorY(other.m_mercatorY)
52{}
53
54QGeoMercatorCoordinatePrivate::~QGeoMercatorCoordinatePrivate()
55{}
56
57/*!
58 \class QGeoCoordinate
59 \inmodule QtPositioning
60 \ingroup QtPositioning-positioning
61 \since 5.2
62
63 \brief The QGeoCoordinate class defines a geographical position on the surface of the Earth.
64
65 A QGeoCoordinate is defined by latitude, longitude, and optionally, altitude.
66
67 Use type() to determine whether a coordinate is a 2D coordinate (has
68 latitude and longitude only) or 3D coordinate (has latitude, longitude
69 and altitude). Use distanceTo() and azimuthTo() to calculate the distance
70 and bearing between coordinates.
71
72 The coordinate values should be specified using the WGS84 datum. For more information
73 on geographical terms see this article on \l {http://en.wikipedia.org/wiki/Geographic_coordinate_system}{coordinates} and
74 another on \l {http://en.wikipedia.org/wiki/Geodetic_system}{geodetic systems}
75 including WGS84.
76
77 The altitude can be measured from different reference surfaces, for
78 example from the mean sea level (MSL) or from the WGS84 reference
79 ellipsoid. Use altitudeType() to find out which reference surface is used
80 for the altitude value, if it is known.
81
82 Azimuth in this context is equivalent to a compass bearing based on true north.
83
84 This class is also accessible in QML as \l[QML]{geoCoordinate}.
85*/
86
87/*!
88 \enum QGeoCoordinate::CoordinateType
89 Defines the types of a coordinate.
90
91 \value InvalidCoordinate An invalid coordinate. A coordinate is invalid if its latitude or longitude values are invalid.
92 \value Coordinate2D A coordinate with valid latitude and longitude values.
93 \value Coordinate3D A coordinate with valid latitude and longitude values, and also an altitude value.
94*/
95
96/*!
97 \enum QGeoCoordinate::CoordinateFormat
98 Defines the possible formatting options for toString().
99
100 \value Degrees Returns a string representation of the coordinates in decimal degrees format.
101 \value DegreesWithHemisphere Returns a string representation of the coordinates in decimal degrees format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates.
102 \value DegreesMinutes Returns a string representation of the coordinates in degrees-minutes format.
103 \value DegreesMinutesWithHemisphere Returns a string representation of the coordinates in degrees-minutes format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates.
104 \value DegreesMinutesSeconds Returns a string representation of the coordinates in degrees-minutes-seconds format.
105 \value DegreesMinutesSecondsWithHemisphere Returns a string representation of the coordinates in degrees-minutes-seconds format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates.
106
107 \sa toString()
108*/
109
110/*!
111 \enum QGeoCoordinate::AltitudeType
112 \since 6.13
113
114 Defines the reference surface from which the \l altitude is measured.
115
116 \value Unknown The reference surface of the altitude is not known. This
117 is the default value.
118 \value MSL The altitude is measured above the mean sea level (MSL). The
119 mean sea level is usually approximated by a geoid model, such as
120 EGM96 or EGM2008, so this altitude is also known as orthometric
121 height.
122 \value WGS84 The altitude is measured above the
123 \l {http://en.wikipedia.org/wiki/World_Geodetic_System}{WGS84}
124 reference ellipsoid. This altitude is also known as ellipsoidal
125 height.
126
127 Not all platforms provide information about the reference surface of the
128 altitude. In such cases the coordinates reported by the positioning
129 sources will have the altitude type set to \c Unknown.
130
131 Use \l {QGeoPositionInfoSource::}{preferredAltitudeType} to select the
132 preferred reference surface for the altitude of the reported positions.
133
134 \sa altitudeType(), setAltitudeType(),
135 QGeoPositionInfoSource::preferredAltitudeType
136*/
137
138/*!
139 \property QGeoCoordinate::latitude
140 \brief This property holds the latitude in decimal degrees.
141
142 The property is undefined (\l {qQNaN()}) if the latitude has not been set.
143 A positive latitude indicates the Northern Hemisphere, and a negative
144 latitude indicates the Southern Hemisphere. When setting the latitude the
145 new value should be in the
146 \l {http://en.wikipedia.org/wiki/World_Geodetic_System}{WGS84} datum format.
147
148 To be valid, the latitude must be between -90 to 90 inclusive.
149
150 While this property is introduced in Qt 5.5, the related accessor functions
151 exist since the first version of this class.
152
153 \since 5.5
154*/
155
156/*!
157 \property QGeoCoordinate::longitude
158 \brief This property holds the longitude in decimal degrees.
159
160 The property is undefined (\l {qQNaN()}) if the longitude has not been set.
161 A positive longitude indicates the Eastern Hemisphere, and a negative
162 longitude indicates the Western Hemisphere. When setting the longitude the
163 new value should be in the
164 \l {http://en.wikipedia.org/wiki/World_Geodetic_System}{WGS84} datum format.
165
166 To be valid, the longitude must be between -180 to 180 inclusive.
167
168 While this property is introduced in Qt 5.5, the related accessor functions
169 exist since the first version of this class.
170
171 \since 5.5
172*/
173
174/*!
175 \property QGeoCoordinate::altitude
176 \brief This property holds the altitude in meters.
177
178 The property is undefined (\l {qQNaN()}) if the altitude has not been set.
179
180 Use altitudeType() to determine the reference surface from which the
181 altitude is measured.
182
183 While this property is introduced in Qt 5.5, the related accessor functions
184 exist since the first version of this class.
185
186 \since 5.5
187*/
188
189/*!
190 \property QGeoCoordinate::altitudeType
191 \brief This property holds the type of the altitude.
192 \since 6.13
193
194 The altitude type specifies the reference surface from which the
195 \l altitude is measured.
196
197 The default value is
198 \l {QGeoCoordinate::AltitudeType}{AltitudeType::Unknown}.
199
200 \sa AltitudeType
201*/
202
203/*!
204 \property QGeoCoordinate::isValid
205 \brief This property holds the validity of this geo coordinate.
206
207 The geo coordinate is valid if the \l [CPP]{longitude} and \l [CPP]{latitude}
208 properties have been set to valid values.
209
210 While this property is introduced in Qt 5.5, the related accessor functions
211 exist since the first version of this class.
212
213 \since 5.5
214*/
215
216/*!
217 Constructs a coordinate. The coordinate will be invalid until
218 setLatitude() and setLongitude() have been called.
219*/
220QGeoCoordinate::QGeoCoordinate()
221 : d(new QGeoCoordinatePrivate)
222{
223}
224
225/*!
226 Constructs a coordinate with the given \a latitude and \a longitude.
227
228 If the latitude is not between -90 to 90 inclusive, or the longitude
229 is not between -180 to 180 inclusive, none of the values are set and
230 the type() will be QGeoCoordinate::InvalidCoordinate.
231
232 \sa isValid()
233*/
234QGeoCoordinate::QGeoCoordinate(double latitude, double longitude)
235 : d(new QGeoCoordinatePrivate)
236{
237 if (QLocationUtils::isValidLat(latitude) && QLocationUtils::isValidLong(longitude)) {
238 d->lat = latitude;
239 d->lng = longitude;
240 }
241}
242
243/*!
244 Constructs a coordinate with the given \a latitude, \a longitude
245 and \a altitude.
246
247 If the latitude is not between -90 to 90 inclusive, or the longitude
248 is not between -180 to 180 inclusive, none of the values are set and
249 the type() will be QGeoCoordinate::InvalidCoordinate.
250
251 Note that \a altitude specifies the altitude in meters. The altitude type
252 of the constructed coordinate is
253 \l {QGeoCoordinate::AltitudeType}{AltitudeType::Unknown}. Use
254 setAltitudeType() to specify the reference surface of the altitude.
255
256 \sa isValid(), setAltitudeType()
257*/
258QGeoCoordinate::QGeoCoordinate(double latitude, double longitude, double altitude)
259 : d(new QGeoCoordinatePrivate)
260{
261 if (QLocationUtils::isValidLat(latitude) && QLocationUtils::isValidLong(longitude)) {
262 d->lat = latitude;
263 d->lng = longitude;
264 d->alt = altitude;
265 }
266}
267
268/*!
269 Constructs a coordinate from the contents of \a other.
270*/
271QGeoCoordinate::QGeoCoordinate(const QGeoCoordinate &other)
272 : d(other.d)
273{}
274
275/*!
276 \fn QGeoCoordinate::QGeoCoordinate(QGeoCoordinate &&other)
277 \since 6.2
278
279 Constructs a coordinate by moving from \a other.
280
281 \note The moved-from QGeoCoordinate object can only be destroyed or
282 assigned to. The effect of calling other functions than the destructor
283 or one of the assignment operators is undefined.
284*/
285
286/*!
287 Assigns \a other to this coordinate and returns a reference to this coordinate.
288*/
289QGeoCoordinate &QGeoCoordinate::operator=(const QGeoCoordinate &other)
290{
291 if (this == &other)
292 return *this;
293
294 d = other.d;
295 return (*this);
296}
297
298/*!
299 \fn QGeoCoordinate &QGeoCoordinate::operator=(QGeoCoordinate &&other)
300 \since 6.2
301
302 Move-assigns \a other to this coordinate and returns a reference to this
303 coordinate.
304
305 \note The moved-from QGeoCoordinate object can only be destroyed or
306 assigned to. The effect of calling other functions than the destructor
307 or one of the assignment operators is undefined.
308*/
309
310/*!
311 Destroys the coordinate object.
312*/
313QGeoCoordinate::~QGeoCoordinate()
314{
315}
316
317QT_DEFINE_QSDP_SPECIALIZATION_DTOR(QGeoCoordinatePrivate)
318
319/*!
320 \fn bool QGeoCoordinate::operator==(const QGeoCoordinate &lhs, const QGeoCoordinate &rhs)
321
322 Returns \c true if the latitude, longitude, altitude and altitude type of
323 the \a lhs coordinate are the same as those of the \a rhs coordinate.
324 Otherwise returns \c false.
325
326 The longitude will be ignored if the latitude is +/- 90 degrees.
327
328 \note Since Qt 6.13, the \l {altitudeType()}{altitude type} is also
329 taken into account if the coordinates have altitude.
330*/
331
332/*!
333 \fn bool QGeoCoordinate::operator!=(const QGeoCoordinate &lhs, const QGeoCoordinate &rhs)
334
335 Returns \c true if latitude, longitude, altitude, or altitude type of the
336 \a lhs coordinate are not identical to those of the \a rhs coordinate.
337 Otherwise returns \c false.
338
339 \note Since Qt 6.13, the \l {altitudeType()}{altitude type} is also
340 taken into account if the coordinates have altitude.
341*/
342
343/*!
344 \fn void QGeoCoordinate::swap(QGeoCoordinate &other)
345 \since 6.2
346 \memberswap{coordinate}
347*/
348
349/*!
350 Returns \c true if the \l longitude and \l latitude are valid.
351*/
352bool QGeoCoordinate::isValid() const
353{
354 CoordinateType t = type();
355 return t == Coordinate2D || t == Coordinate3D;
356}
357
358/*!
359 Returns the type of this coordinate.
360*/
361QGeoCoordinate::CoordinateType QGeoCoordinate::type() const
362{
363 if (QLocationUtils::isValidLat(d->lat)
364 && QLocationUtils::isValidLong(d->lng)) {
365 if (qIsNaN(d->alt))
366 return Coordinate2D;
367 return Coordinate3D;
368 }
369 return InvalidCoordinate;
370}
371
372
373/*!
374 Returns the latitude, in decimal degrees. The return value is undefined
375 if the latitude has not been set.
376
377 A positive latitude indicates the Northern Hemisphere, and a negative
378 latitude indicates the Southern Hemisphere.
379
380 \sa setLatitude(), type()
381*/
382double QGeoCoordinate::latitude() const
383{
384 return d->lat;
385}
386
387/*!
388 Sets the latitude (in decimal degrees) to \a latitude. The value should
389 be in the WGS84 datum.
390
391 To be valid, the latitude must be between -90 to 90 inclusive.
392
393 \sa latitude()
394*/
395void QGeoCoordinate::setLatitude(double latitude)
396{
397 d->lat = latitude;
398}
399
400/*!
401 Returns the longitude, in decimal degrees. The return value is undefined
402 if the longitude has not been set.
403
404 A positive longitude indicates the Eastern Hemisphere, and a negative
405 longitude indicates the Western Hemisphere.
406
407 \sa setLongitude(), type()
408*/
409double QGeoCoordinate::longitude() const
410{
411 return d->lng;
412}
413
414/*!
415 Sets the longitude (in decimal degrees) to \a longitude. The value should
416 be in the WGS84 datum.
417
418 To be valid, the longitude must be between -180 to 180 inclusive.
419
420 \sa longitude()
421*/
422void QGeoCoordinate::setLongitude(double longitude)
423{
424 d->lng = longitude;
425}
426
427/*!
428 Returns the altitude in meters.
429
430 The return value is undefined if the altitude has not been set.
431
432 The altitude is always given in meters, but it can be measured from
433 different reference surfaces:
434
435 \list
436 \li \e {Mean Sea Level (MSL)}. The altitude is the height above the
437 mean sea level of the Earth, which is usually approximated by a
438 geoid model, such as EGM96 or EGM2008. This altitude is also known
439 as orthometric height.
440 \li \e {WGS84 ellipsoid}. The altitude is the height above the
441 \l {http://en.wikipedia.org/wiki/World_Geodetic_System}{WGS84}
442 reference ellipsoid. This is also known as ellipsoidal height.
443 \endlist
444
445 Use altitudeType() to determine the reference surface from which the
446 altitude is measured. By default, \l {QGeoCoordinate::AltitudeType}
447 {AltitudeType::Unknown} is used, in which case the reference surface
448 depends on the backend that provides the position updates, as shown in
449 the following table.
450
451 \table
452 \header
453 \li Backend
454 \li Default altitude type
455 \li Comment
456 \row
457 \li \l {Qt Positioning Android plugin}{android}
458 \li WGS84 (default) or MSL
459 \li The altitude is WGS84 by default. Starting from Android 14, the
460 backend can provide the MSL altitude instead if the
461 \c useMslAltitude plugin parameter is set to \c true. See
462 \l {Qt Positioning Android plugin} for more details. Starting from
463 Qt 6.13 the behavior can also be controlled with the
464 \l QGeoPositionInfoSource::preferredAltitudeType property.
465 \row
466 \li \l {Qt Positioning Core Location plugin}{corelocation}
467 \li MSL
468 \li
469 \row
470 \li \l {Qt Positioning NMEA plugin}{nmea}
471 \li MSL
472 \li The altitude is read from the GGA sentence. This also applies
473 to \l QNmeaPositionInfoSource.
474 \row
475 \li winrt (Windows)
476 \li MSL
477 \li By default, the altitude is reported only if the platform states
478 that it is measured from the geoid.
479 \endtable
480
481 Starting from Qt 6.13, the preferred altitude type for these backends can
482 be controlled with the \l QGeoPositionInfoSource::preferredAltitudeType
483 property. The backends will try to report the preferred altitude type, but
484 may fall back to another altitude type if the preferred type is not
485 available. They will set altitudeType() accordingly.
486
487 The other backends, such as \l {Qt Positioning GeoClue v2 plugin}{geoclue2}
488 or wasm, have no reliable way to determine the type of the returned
489 altitude. The underlying platform APIs do not specify it, and it can
490 depend on the actual source of the position data. These backends will always
491 report \l altitudeType() as \l {QGeoCoordinate::}{AltitudeType::Unknown}.
492
493 \sa setAltitude(), type(), altitudeType(), {Qt Positioning Plugins},
494 QGeoPositionInfoSource::preferredAltitudeType
495*/
496double QGeoCoordinate::altitude() const
497{
498 return d->alt;
499}
500
501/*!
502 Sets the altitude (in meters) to \a altitude.
503
504 Use setAltitudeType() to specify the reference surface of the altitude.
505
506 \sa altitude(), setAltitudeType()
507*/
508void QGeoCoordinate::setAltitude(double altitude)
509{
510 d->alt = altitude;
511}
512
513/*!
514 \since 6.13
515
516 Returns the altitude type of this coordinate. The altitude type specifies
517 the reference surface from which the altitude() is measured.
518
519 The default value is
520 \l {QGeoCoordinate::AltitudeType}{AltitudeType::Unknown}.
521
522 \sa setAltitudeType(), altitude()
523*/
524QGeoCoordinate::AltitudeType QGeoCoordinate::altitudeType() const
525{
526 return d->altType;
527}
528
529/*!
530 \since 6.13
531
532 Sets the altitude type of this coordinate to \a type.
533
534 The altitude type specifies the reference surface from which the
535 altitude() is measured.
536
537 \note This function does not convert the altitude value. It only changes
538 the reference surface that the current altitude value is assumed to be
539 measured from.
540
541 \sa altitudeType(), setAltitude()
542*/
543void QGeoCoordinate::setAltitudeType(AltitudeType type)
544{
545 d->altType = type;
546}
547
548/*!
549 Returns the distance (in meters) from this coordinate to the coordinate
550 specified by \a other. Altitude is not used in the calculation.
551
552 This calculation returns the great-circle distance between the two
553 coordinates, with an assumption that the Earth is spherical for the
554 purpose of this calculation.
555
556 Returns 0 if the type of this coordinate or the type of \a other is
557 QGeoCoordinate::InvalidCoordinate.
558*/
559qreal QGeoCoordinate::distanceTo(const QGeoCoordinate &other) const
560{
561 if (type() == QGeoCoordinate::InvalidCoordinate
562 || other.type() == QGeoCoordinate::InvalidCoordinate) {
563 return 0;
564 }
565
566 // Haversine formula
567 double dlat = qDegreesToRadians(other.d->lat - d->lat);
568 double dlon = qDegreesToRadians(other.d->lng - d->lng);
569 double haversine_dlat = sin(dlat / 2.0);
570 haversine_dlat *= haversine_dlat;
571 double haversine_dlon = sin(dlon / 2.0);
572 haversine_dlon *= haversine_dlon;
573 double y = haversine_dlat
574 + cos(qDegreesToRadians(d->lat))
575 * cos(qDegreesToRadians(other.d->lat))
576 * haversine_dlon;
577 double x = 2 * asin(sqrt(y));
578 return qreal(x * qgeocoordinate_EARTH_MEAN_RADIUS * 1000);
579}
580
581/*!
582 Returns the azimuth (or bearing) in degrees from this coordinate to the
583 coordinate specified by \a other. Altitude is not used in the calculation.
584
585 The bearing returned is the bearing from the origin to \a other along the
586 great-circle between the two coordinates. There is an assumption that the
587 Earth is spherical for the purpose of this calculation.
588
589 Returns 0 if the type of this coordinate or the type of \a other is
590 QGeoCoordinate::InvalidCoordinate.
591*/
592qreal QGeoCoordinate::azimuthTo(const QGeoCoordinate &other) const
593{
594 if (type() == QGeoCoordinate::InvalidCoordinate
595 || other.type() == QGeoCoordinate::InvalidCoordinate) {
596 return 0;
597 }
598
599 double dlon = qDegreesToRadians(other.d->lng - d->lng);
600 double lat1Rad = qDegreesToRadians(d->lat);
601 double lat2Rad = qDegreesToRadians(other.d->lat);
602
603 double y = sin(dlon) * cos(lat2Rad);
604 double x = cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(dlon);
605
606 double azimuth = qRadiansToDegrees(atan2(y, x)) + 360.0;
607 double whole;
608 double fraction = modf(azimuth, &whole);
609 return qreal((int(whole + 360) % 360) + fraction);
610}
611
612void QGeoCoordinatePrivate::atDistanceAndAzimuth(const QGeoCoordinate &coord,
613 qreal distance, qreal azimuth,
614 double *lon, double *lat)
615{
616 double latRad = qDegreesToRadians(coord.d->lat);
617 double lonRad = qDegreesToRadians(coord.d->lng);
618 double cosLatRad = cos(latRad);
619 double sinLatRad = sin(latRad);
620
621 double azimuthRad = qDegreesToRadians(azimuth);
622
623 double ratio = (distance / (qgeocoordinate_EARTH_MEAN_RADIUS * 1000.0));
624 double cosRatio = cos(ratio);
625 double sinRatio = sin(ratio);
626
627 double resultLatRad = asin(sinLatRad * cosRatio
628 + cosLatRad * sinRatio * cos(azimuthRad));
629 double resultLonRad = lonRad + atan2(sin(azimuthRad) * sinRatio * cosLatRad,
630 cosRatio - sinLatRad * sin(resultLatRad));
631
632 *lat = qRadiansToDegrees(resultLatRad);
633 *lon = qRadiansToDegrees(resultLonRad);
634}
635
636/*!
637 Returns the coordinate that is reached by traveling \a distance meters
638 from the current coordinate at \a azimuth (or bearing) along a great-circle.
639 There is an assumption that the Earth is spherical for the purpose of this
640 calculation.
641
642 The altitude will have \a distanceUp added to it.
643
644 Returns an invalid coordinate if this coordinate is invalid.
645*/
646QGeoCoordinate QGeoCoordinate::atDistanceAndAzimuth(qreal distance, qreal azimuth, qreal distanceUp) const
647{
648 if (!isValid())
649 return QGeoCoordinate();
650
651 double resultLon, resultLat;
652 QGeoCoordinatePrivate::atDistanceAndAzimuth(*this, distance, azimuth,
653 &resultLon, &resultLat);
654 double resultAlt = d->alt + distanceUp;
655 QGeoCoordinate result(resultLat, QLocationUtils::wrapLong(resultLon), resultAlt);
656 result.d->altType = d->altType;
657 return result;
658}
659
660/*!
661 Returns this coordinate as a string in the specified \a format.
662
663 For example, if this coordinate has a latitude of -27.46758, a longitude
664 of 153.027892 and an altitude of 28.1, these are the strings
665 returned depending on \a format:
666
667 \table
668 \header
669 \li \a format value
670 \li Returned string
671 \row
672 \li \l Degrees
673 \li -27.46758\unicode{0xB0}, 153.02789\unicode{0xB0}, 28.1m
674 \row
675 \li \l DegreesWithHemisphere
676 \li 27.46758\unicode{0xB0} S, 153.02789\unicode{0xB0} E, 28.1m
677 \row
678 \li \l DegreesMinutes
679 \li -27\unicode{0xB0} 28.054', 153\unicode{0xB0} 1.673', 28.1m
680 \row
681 \li \l DegreesMinutesWithHemisphere
682 \li 27\unicode{0xB0} 28.054 S', 153\unicode{0xB0} 1.673' E, 28.1m
683 \row
684 \li \l DegreesMinutesSeconds
685 \li -27\unicode{0xB0} 28' 3.2", 153\unicode{0xB0} 1' 40.4", 28.1m
686 \row
687 \li \l DegreesMinutesSecondsWithHemisphere
688 \li 27\unicode{0xB0} 28' 3.2" S, 153\unicode{0xB0} 1' 40.4" E, 28.1m
689 \endtable
690
691 The altitude field is omitted if no altitude is set.
692
693 If the coordinate is invalid, an empty string is returned.
694*/
695QString QGeoCoordinate::toString(CoordinateFormat format) const
696{
697 if (type() == QGeoCoordinate::InvalidCoordinate)
698 return QString();
699
700 QString latStr;
701 QString longStr;
702
703 double absLat = qAbs(d->lat);
704 double absLng = qAbs(d->lng);
705
706 switch (format) {
707 case Degrees:
708 case DegreesWithHemisphere: {
709 latStr = QString::asprintf("%.5f°", absLat);
710 longStr = QString::asprintf("%.5f°", absLng);
711 break;
712 }
713 case DegreesMinutes:
714 case DegreesMinutesWithHemisphere: {
715 double latMin = (absLat - int(absLat)) * 60;
716 double lngMin = (absLng - int(absLng)) * 60;
717
718 // We use QString::number(val, 'f', 3) to represent minutes.
719 // It rounds up to the next integer in case the fraction > 0.9995.
720 // Such behavior should be handled specifically when the rounded
721 // value is 60, so that we overflow to degrees correctly.
722 // If we overflow, the minutes should unconditionally be 0.0.
723 if (latMin > 59.9995) {
724 absLat++;
725 latMin = 0.0f;
726 }
727 if (lngMin > 59.9995) {
728 absLng++;
729 lngMin = 0.0f;
730 }
731
732 latStr = QString::asprintf("%d° %.3f'", int(absLat), latMin);
733 longStr = QString::asprintf("%d° %.3f'", int(absLng), lngMin);
734 break;
735 }
736 case DegreesMinutesSeconds:
737 case DegreesMinutesSecondsWithHemisphere: {
738 double latMin = (absLat - int(absLat)) * 60;
739 double lngMin = (absLng - int(absLng)) * 60;
740 double latSec = (latMin - int(latMin)) * 60;
741 double lngSec = (lngMin - int(lngMin)) * 60;
742
743 // We use QString::number(val, 'f', 1) to represent seconds.
744 // It rounds up to the next integer in case the fraction >= 0.95.
745 // Such behavior should be handled specifically when the rounded
746 // value is 60, so that we overflow to minutes correctly.
747 // If we overflow, the seconds should unconditionally be 0.0.
748 if (latSec >= 59.95) {
749 latMin++;
750 latSec = 0.0f;
751 // We cast to int to represent minutes, so we can use qRound()
752 // to determine if we need to overflow to full degrees.
753 // If we overflow, the minutes will unconditionally be 0.0.
754 if (qRound(latMin) >= 60) {
755 absLat++;
756 latMin = 0.0f;
757 }
758 }
759 if (lngSec >= 59.95) {
760 lngMin++;
761 lngSec = 0.0f;
762 if (qRound(lngMin) >= 60) {
763 absLng++;
764 lngMin = 0.0f;
765 }
766 }
767
768 latStr = QString::asprintf("%d° %d' %.1f\"", int(absLat), int(latMin), latSec);
769 longStr = QString::asprintf("%d° %d' %.1f\"", int(absLng), int(lngMin), lngSec);
770 break;
771 }
772 }
773
774 // now add the "-" to the start, or append the hemisphere char
775 switch (format) {
776 case Degrees:
777 case DegreesMinutes:
778 case DegreesMinutesSeconds: {
779 if (d->lat < 0)
780 latStr.insert(0, QStringLiteral("-"));
781 if (d->lng < 0)
782 longStr.insert(0, QStringLiteral("-"));
783 break;
784 }
785 case DegreesWithHemisphere:
786 case DegreesMinutesWithHemisphere:
787 case DegreesMinutesSecondsWithHemisphere: {
788 if (d->lat < 0)
789 latStr.append(QString::fromLatin1(" S"));
790 else if (d->lat > 0)
791 latStr.append(QString::fromLatin1(" N"));
792 if (d->lng < 0)
793 longStr.append(QString::fromLatin1(" W"));
794 else if (d->lng > 0)
795 longStr.append(QString::fromLatin1(" E"));
796 break;
797 }
798 }
799
800 if (qIsNaN(d->alt))
801 return QString::fromLatin1("%1, %2").arg(latStr, longStr);
802 return QString::fromLatin1("%1, %2, %3m").arg(latStr, longStr, QString::number(d->alt));
803}
804
805bool QGeoCoordinate::equals(const QGeoCoordinate &lhs, const QGeoCoordinate &rhs)
806{
807 bool latEqual = (qIsNaN(lhs.d->lat) && qIsNaN(rhs.d->lat))
808 || QtPrivate::fuzzyCompare(lhs.d->lat, rhs.d->lat);
809 bool lngEqual = (qIsNaN(lhs.d->lng) && qIsNaN(rhs.d->lng))
810 || QtPrivate::fuzzyCompare(lhs.d->lng, rhs.d->lng);
811
812 const bool altitudesUndefined = qIsNaN(lhs.d->alt) && qIsNaN(rhs.d->alt);
813 bool altEqual = altitudesUndefined || QtPrivate::fuzzyCompare(lhs.d->alt, rhs.d->alt);
814
815 if (!qIsNaN(lhs.d->lat) && ((lhs.d->lat == 90.0) || (lhs.d->lat == -90.0)))
816 lngEqual = true;
817
818 // We do not compare altitude type when both altitudes are undefined.
819 bool altTypeEqual = altitudesUndefined || (lhs.d->altType == rhs.d->altType);
820
821 return (latEqual && lngEqual && altEqual && altTypeEqual);
822}
823
824QGeoCoordinate::QGeoCoordinate(QGeoCoordinatePrivate &dd):
825 d(&dd)
826{
827}
828
829#ifndef QT_NO_DEBUG_STREAM
830QDebug QGeoCoordinate::debugStreaming(QDebug dbg, const QGeoCoordinate &coord)
831{
832 QDebugStateSaver saver(dbg);
833 double lat = coord.latitude();
834 double lng = coord.longitude();
835
836 auto altTypeToStr = [](const QGeoCoordinate &c) {
837 quint64 type = static_cast<quint64>(c.altitudeType());
838 return QMetaEnum::fromType<QGeoCoordinate::AltitudeType>().valueToKey(type);
839 };
840
841 QTextStreamManipulator tsm = qSetRealNumberPrecision(11);
842 dbg << tsm;
843 dbg.nospace() << "QGeoCoordinate(";
844 if (qIsNaN(lat))
845 dbg << '?';
846 else
847 dbg << lat;
848 dbg << ", ";
849 if (qIsNaN(lng))
850 dbg << '?';
851 else
852 dbg << lng;
853 if (coord.type() == QGeoCoordinate::Coordinate3D) {
854 dbg << ", ";
855 dbg << coord.altitude();
856 // Print altitude type only when it's not Unknown, to make sure that
857 // the output is backwards-compatible
858 if (coord.altitudeType() != QGeoCoordinate::AltitudeType::Unknown)
859 dbg << " " << altTypeToStr(coord);
860 }
861 dbg << ')';
862 return dbg;
863}
864#endif
865
866#ifndef QT_NO_DATASTREAM
867/*!
868 \fn QDataStream &QGeoCoordinate::operator<<(QDataStream &stream, const QGeoCoordinate &coordinate)
869
870 Writes the given \a coordinate to the specified \a stream.
871
872 Since Qt 6.13, the \l {altitudeType()}{altitude type} is also written,
873 if the \l {QDataStream::version()}{version} of the \a stream is
874 QDataStream::Qt_6_13 or later.
875
876 \sa {Serializing Qt Data Types}
877*/
878
879QDataStream &QGeoCoordinate::dataStreamOut(QDataStream &stream, const QGeoCoordinate &coordinate)
880{
881 stream << coordinate.latitude();
882 stream << coordinate.longitude();
883 stream << coordinate.altitude();
884 if (stream.version() >= QDataStream::Qt_6_13)
885 stream << int(coordinate.altitudeType());
886 return stream;
887}
888#endif
889
890#ifndef QT_NO_DATASTREAM
891/*!
892 \fn QDataStream &QGeoCoordinate::operator>>(QDataStream &stream, QGeoCoordinate &coordinate)
893
894 Reads a coordinate from the specified \a stream into the given
895 \a coordinate.
896
897 Since Qt 6.13, the \l {altitudeType()}{altitude type} is also read,
898 if the \l {QDataStream::version()}{version} of the \a stream is
899 QDataStream::Qt_6_13 or later. For older stream versions the altitude type
900 of the \a coordinate is set to
901 \l {QGeoCoordinate::AltitudeType}{AltitudeType::Unknown}.
902
903 \sa {Serializing Qt Data Types}
904*/
905
906QDataStream &QGeoCoordinate::dataStreamIn(QDataStream &stream, QGeoCoordinate &coordinate)
907{
908 double value;
909 stream >> value;
910 coordinate.setLatitude(value);
911 stream >> value;
912 coordinate.setLongitude(value);
913 stream >> value;
914 coordinate.setAltitude(value);
915
916 AltitudeType altType = AltitudeType::Unknown;
917 if (stream.version() >= QDataStream::Qt_6_13) {
918 int rawType = 0;
919 stream >> rawType;
920 if (rawType < 0 || rawType > int(AltitudeType::WGS84)) {
921 stream.setStatus(QDataStream::ReadCorruptData);
922 rawType = int(AltitudeType::Unknown);
923 }
924 altType = AltitudeType(rawType);
925 }
926 coordinate.setAltitudeType(altType);
927 return stream;
928}
929#endif
930
931/*! \fn size_t qHash(const QGeoCoordinate &coordinate, size_t seed = 0)
932 \relates QHash
933
934 Returns a hash value for \a coordinate, using \a seed to seed the calculation.
935*/
936size_t qHash(const QGeoCoordinate &coordinate, size_t seed)
937{
938 QtPrivate::QHashCombine hash(seed);
939 // north and south pole are geographically equivalent (no matter the longitude)
940 if (coordinate.latitude() != 90.0 && coordinate.latitude() != -90.0)
941 seed = hash(seed, coordinate.longitude());
942 seed = hash(seed, coordinate.latitude());
943 seed = hash(seed, coordinate.altitude());
944 // hash the altitude type only if altitude is valid
945 if (!qIsNaN(coordinate.altitude()))
946 seed = hash(seed, coordinate.altitudeType());
947 return seed;
948}
949
950QT_END_NAMESPACE
951
952#include "moc_qgeocoordinate.cpp"
Combined button and popup list for selecting options.
constexpr size_t qHash(const QSize &s, size_t seed=0) noexcept
Definition qsize.h:192