Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Location

The Location API provides a library for distributing and receiving location data using arbitrary data sources.

Namespace

The QtMobility APIs are placed into the QtMobility namespace. This is done to facilitate the future migration of Mobility APIs into Qt. See the Quickstart guide for an example on how the namespace impacts on application development.

Overview

Location data involves a precisely specified position on the Earth's surface — as provided by a latitude-longitude coordinate — along with associated data, such as:

  • The date and time at which the position was reported
  • The velocity of the device that reported the position
  • The altitude of the reported position (height above sea level)
  • The bearing of the device in degrees, relative to true north

This data can be extracted through a variety of methods. One of the most well known methods of positioning is GPS (Global Positioning System), a publicly available system that uses radiowave signals received from Earth-orbiting satellites to calculate the precise position and time of the receiver. Another popular method is Cell ID positioning, which uses the cell ID of the cell site that is currently serving the receiving device to calculate its approximate location. These and other positioning methods can all be used with the Location API; the only requirement for a location data source within the API is that it provides a latitude-longitude coordinate with a date/time value, with the option of providing the other attributes listed above.

Location data sources are created by subclassing QGeoPositionInfoSource and providing QGeoPositionInfo objects through the QGeoPositionInfoSource::positionUpdated() signal. Clients that require location data can connect to the positionUpdated() signal and call startUpdates() or requestUpdate() to trigger the distribution of location data.

A default position source may be available on some platforms. Call QGeoPositionInfoSource::createDefaultSource() to create an instance of the default position source; the method returns 0 if no default source is available for the platform.

The QGeoAreaMonitor class enables client applications to be notified when the receiving device has moved in or out of a particular area, as specified by a coordinate and radius. If the platform provides built-in support for area monitoring, QGeoAreaMonitor::createDefaultMonitor() returns an instance of the default area monitor.

Satellite information can also be distributed through the QGeoSatelliteInfoSource class. Call QGeoSatelliteInfoSource::createDefaultSource() to create an instance of the default satellite data source for the platform, if one is available. Alternatively, clients can subclass it to provide a custom satellite data source.

Requesting location data from data sources

To receive data from a source, connect to its positionUpdated() signal, then call either startUpdates() or requestUpdate() to begin.

Here is an example of a client that receives data from the default location data source, as returned by QGeoPositionInfoSource::createDefaultSource():

    class MyClass : public QObject
    {
        Q_OBJECT
    public:
        MyClass(QObject *parent = 0)
            : QObject(parent)
        {
            QGeoPositionInfoSource *source = QGeoPositionInfoSource::createDefaultSource(this);
            if (source) {
                connect(source, SIGNAL(positionUpdated(QGeoPositionInfo)),
                        this, SLOT(positionUpdated(QGeoPositionInfo)));
                source->startUpdates();
            }
        }

    private slots:
        void positionUpdated(const QGeoPositionInfo &info)
        {
            qDebug() << "Position updated:" << info;
        }
    };

Controlling aspects of data sources

The QGeoPositionInfoSource::setUpdateInterval() method can be used to control the rate at which position updates are received. For example, if the client application only requires updates once every 30 seconds, it can call setUpdateInterval(30000). (If no update interval is set, or setUpdateInterval() is called with a value of 0, the source uses a default interval or some other internal logic to determine when updates should be provided.)

QGeoPositionInfoSource::setPreferredPositioningMethods() enables client applications to request that a certain type of positioning method be used. For example, if the application prefers to use only satellite positioning, which offers fairly precise outdoor positioning but can be a heavy user of power resources, it can call this method with the QGeoPositionInfoSource::SatellitePositioningMethods value. However, this method should only be used in specialized client applications; in most cases, the default positioning methods should not be changed, as a source may internally use a variety of positioning methods that can be useful to the application.

Reading NMEA data

NMEA is a common text-based protocol for specifying navigational data. For convenience, the QNmeaPositionInfoSource is provided to enable client applications to read and distribute NMEA data in either real-time mode (for example, when streaming from a GPS device) or simulation mode (for example, when reading from a NMEA log file). In simulation mode, the source will emit updates according to the time stamp of each NMEA sentence to produce a "replay" of the recorded data.

Example: Creating a custom location data source

Generally, the capabilities provided by the default position source as returned by QGeoPositionInfoSource::createDefaultSource(), along with the QNmeaPositionInfoSource class, are sufficient for retrieving location data. However, in some cases developers may wish to write their own custom location data sources.

The LogFilePositionSource class in examples/logfilepositionsource shows how to subclass QGeoPositionInfoSource to create a custom location data source.

This example class reads location data from a text file, log.txt. The file specifies location data using a simple text format: it contains one location update per line, where each line contains a date/time, a latitude and a longitude, separated by spaces. The date/time is in ISO 8601 format and the latitude and longitude are in degrees decimal format. Here is an excerpt from log.txt:

        2009-08-24T22:25:01 -27.576082 153.092415
        2009-08-24T22:25:02 -27.576223 153.092530
        2009-08-24T22:25:03 -27.576364 153.092648

The class reads this data and distributes it via the positionUpdated() signal.

Here is the definition of the LogFilePositionSource class:

    class LogFilePositionSource : public QGeoPositionInfoSource
    {
        Q_OBJECT
    public:
        LogFilePositionSource(QObject *parent = 0);

        QGeoPositionInfo lastKnownPosition(bool fromSatellitePositioningMethodsOnly = false) const;

        PositioningMethods supportedPositioningMethods() const;
        int minimumUpdateInterval() const;

    public slots:
        virtual void startUpdates();
        virtual void stopUpdates();

        virtual void requestUpdate(int timeout = 5000);

    private slots:
        void readNextPosition();

    private:
        QFile *logFile;
        QTimer *timer;
        QGeoPositionInfo lastPosition;
    };

The main methods overrided by the subclass are:

  • startUpdates(): called by client applications to start regular position updates
  • stopUpdates(): called by client applications to stop regular position updates
  • requestUpdate(): called by client applications to request a single update, with a specified timeout

When a position update is available, the subclass emits the positionUpdated() signal.

Here are the key methods in the class implementation:

    LogFilePositionSource::LogFilePositionSource(QObject *parent)
        : QGeoPositionInfoSource(parent),
          logFile(new QFile(this)),
          timer(new QTimer(this))
    {
        connect(timer, SIGNAL(timeout()), this, SLOT(readNextPosition()));

        logFile->setFileName(QCoreApplication::applicationDirPath()
                + QDir::separator() + "simplelog.txt");
        if (!logFile->open(QIODevice::ReadOnly))
            qWarning() << "Error: cannot open source file" << logFile->fileName();
    }

    void LogFilePositionSource::startUpdates()
    {
        int interval = updateInterval();
        if (interval < minimumUpdateInterval())
            interval = minimumUpdateInterval();

        timer->start(interval);
    }

    void LogFilePositionSource::stopUpdates()
    {
        timer->stop();
    }

    void LogFilePositionSource::requestUpdate(int /*timeout*/)
    {
        // For simplicity, ignore timeout - assume that if data is not available
        // now, no data will be added to the file later
        if (logFile->canReadLine())
            readNextPosition();
        else
            emit updateTimeout();
    }

    void LogFilePositionSource::readNextPosition()
    {
        QByteArray line = logFile->readLine().trimmed();
        if (!line.isEmpty()) {
            QList<QByteArray> data = line.split(' ');
            double latitude;
            double longitude;
            bool hasLatitude = false;
            bool hasLongitude = false;
            QDateTime timestamp = QDateTime::fromString(QString(data.value(0)), Qt::ISODate);
            latitude = data.value(1).toDouble(&hasLatitude);
            longitude = data.value(2).toDouble(&hasLongitude);

            if (hasLatitude && hasLongitude && timestamp.isValid()) {
                QGeoCoordinate coordinate(latitude, longitude);
                QGeoPositionInfo info(coordinate, timestamp);
                if (info.isValid()) {
                    lastPosition = info;
                    emit positionUpdated(info);
                }
            }
        }
    }

The example includes a ClientApplication class that requests updates from the LogFilePositionSource class. Run the example to see the data that is received by ClientApplication.

Before running the example, make sure you have done both make and make install.

Examples

Flickr Demo

The Flickr Demo uses the Location to download thumbnail images from Flickr relevant to the current location.

Weather Info Demo

The Weather Info demo uses Location display data about the weather for the current location.

Light Maps Demo

The Light Maps demo uses Location display a street map for the current location.

Classes

QGeoAreaMonitorEnables the detection of proximity changes for a specified set of coordinates
QGeoCoordinateDefines a geographical position on the surface of the Earth
QGeoPositionInfoContains information gathered on a global position, direction and velocity at a particular point in time
QGeoPositionInfoSourceAbstract base class for the distribution of positional updates
QGeoSatelliteInfoContains basic information about a satellite
QGeoSatelliteInfoSourceAbstract base class for the distribution of satellite information updates
QNmeaPositionInfoSourcePositional information using a NMEA data source

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt qtmobility-1.0
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web