Getting the location in Qt
This code snippet demonstrates how to use the Qt Location API.
Article Metadata
Tested with
Devices(s): Nokia 5800 XpressMusic
Compatibility
Platform(s): S60 5th Edition, Maemo 5
Article
Created: tapla
(25 May 2010)
Last edited: hamishwillee
(11 Oct 2012)
Contents |
Qt project file
Link the Location module into the project:
CONFIG += mobility
MOBILITY = location
Using the Location module requires the Location capability:
symbian: {
TARGET.CAPABILITY = Location
}Header
#include <QGeoPositionInfo>
#include <QGeoPositionInfoSource>
#include <QDebug>
#include <QPointer>
// QtMobility namespace
QTM_USE_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public slots:
/**
* Called when the current position is updated.
*/
void positionUpdated(QGeoPositionInfo geoPositionInfo);
´
private:
/**
* Obtains the location data source and starts listening for position
* changes.
*/
void startGPS();
private:
QPointer<QGeoPositionInfoSource> locationDataSource;
QGeoPositionInfo myPositionInfo;
}
Source
#include <QGeoCoordinate>
void MainWindow::startGPS()
{
// Obtain the location data source if it is not obtained already
if (!locationDataSource)
{
locationDataSource =
QGeoPositionInfoSource::createDefaultSource(this);
// Whenever the location data source signals that the current
// position is updated, the positionUpdated function is called
connect(locationDataSource, SIGNAL(positionUpdated(QGeoPositionInfo)),
this, SLOT(positionUpdated(QGeoPositionInfo)));
// Start listening for position updates
locationDataSource->startUpdates();
}
}
void MainWindow::positionUpdated(QGeoPositionInfo geoPositionInfo)
{
if (geoPositionInfo.isValid())
{
// We've got the position. No need to continue the listening.
locationDataSource->stopUpdates();
// Save the position information into a member variable
myPositionInfo = geoPositionInfo;
// Get the current location as latitude and longitude
QGeoCoordinate geoCoordinate = geoPositionInfo.coordinate();
qreal latitude = geoCoordinate.latitude();
qreal longitude = geoCoordinate.longitude();
qDebug() << QString("Latitude: %1 Longitude: %2").arg(latitude).arg(longitude);
}
}
Postconditions
Current location is obtained and printed on the screen.

