Contents
- Namespace
- Location Positioning
- Requesting location data from data sources
- Controlling aspects of data sources
- Reading NMEA data
- Example: Creating a custom location data source
- Examples
- Flickr Demo
- Weather Info Demo
- Light Maps Demo
- Location classes
- Landmarks
- Landmark Examples
- Landmark classes
- Main Landmark Classes
- Landmark Selection classes
- Filters
- SortOrders
- Asynchronous Requests
- Implementing backends
- Maps and Navigation
- Common classes
- Mapping
- Map objects
- Routing
- Geocoding and searching for places
- The Nokia plugin
- Implementing plugins
Location
The Location API provides a library for location positioning, landmark management and mapping and navigation.
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.
Location Positioning
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.
Location classes
Represents an address | |
Enables the detection of proximity changes for a specified set of coordinates | |
Defines a geographical position on the surface of the Earth | |
Represents basic information about a place | |
Contains information gathered on a global position, direction and velocity at a particular point in time | |
Abstract base class for the distribution of positional updates | |
Contains basic information about a satellite | |
Abstract base class for the distribution of satellite information updates | |
Positional information using a NMEA data source |
Landmarks
The Landmarks portion of the Location API facilitates the creation, retrieval, updating and deletion of landmarks from arbitrary data stores.
A landmark is a location of some significance, also known as a point of interest and are represented as QLandmark objects. Related landmarks may be grouped into categories(QLandmarkCategory) such as restaurants or accommodation and each landmark can belong to more than one category.
A landmark datastore is represented by a QLandmarkManager. The QLandmarkManager may be used to save, fetch and remove both landmarks and categories. When fetching landmarks we can provide various filters and sort orders to define the searching criteria and the order in which landmarks are returned. The QLandmarkManager also provides functionality to import and export landmarks as well as provide notifications whenever changes are detected. It should be noted that the Landmarks API provides both synchronous and asynchronous mechanisms to perform the above operations. Synchronous operations are provided the QLandmarkManager itself while the asynchronous operations are provided by various request classes. It is generally recommended that the asynchronous request classes classes be used as they are not subject to blocking which can be an issue if a datastore contains a significantly large number of landmarks or if the datastore is being accessed over a network.
Landmark Examples
For more details see the Landmark Examples page.
Landmark classes
Main Landmark Classes
Represents a location or point of interest of some significance | |
Designates a grouping of landmarks of similar type | |
Unique identifier for a category | |
Miscellaneous hints to the manager when fetching landmarks | |
Unique identifier for a landmark | |
Interface for storage and retrieval of landmarks from a landmark store |
Landmark Selection classes
Landmark selection is facilitated by filter and sort order classes. The filter classes define what criteria that landmarks must match and the sort order classes specify how the returned landmarks are sorted. The filter and sort order classes are used with either the QLandmarkManager class (for synchronous landmark selection) or the request classes for (asynchronous landmark selection)
Filters
Filtering based on generic landmark attributes | |
Used to search for landmarks within a given bounding box | |
Used to search for landmarks that belong to a certain category | |
Serves as the base class for all filter classes. Also serves as the default filter which retrieves all landmarks | |
Used to search for landmarks based on a list of landmark identifiers | |
Filter which intersects the results of its constituent filters | |
Used to search for landmarks by name | |
Used to search for landmarks based on the radius around a given coordinate | |
Filter which unions the results of its constituent filters |
SortOrders
Used to sort landmarks by distance from a given coordinate | |
Used to sort landmarks by name | |
Serves as a base class for the different sort order types |
Asynchronous Requests
Asynchronous operations are facilitates by the request classes listed below:
The interface from which all asynchronous request classes inherit | |
Allows a client to asynchronously request a list of categories from a landmark manager | |
Allows a client to asynchronously request a list of category identifiers from a landmark manager | |
Allows a client to asynchronously request that certain categories be removed from a landmark manager | |
Allows a client to asynchronously request that certain categories be saved by a landmark manager | |
Allows a client to asynchronously request that a landmark manager export a set of landmarks | |
Allows a client to asynchronously request a list of landmarks from a landmark manager | |
Allows a client to asynchronously request a list of landmark identifiers from a landmark manager | |
Allows a client to asynchronously request that a landmark manager import a set of landmarks | |
Allows a client to asynchronously request that certain landmarks be removed from a landmark manager | |
Allows a client to asynchronously request that certain landmarks be saved by a landmark manager |
Implementing backends
A manager backend may be implemented by subclassing QLandmarkManagerEngine, and providing a QLandmarkManagerEngineFactory which can instantiate it when required.
The interface for all implementations of the landmark manager backend functionality | |
The interface for plugins that implement QLandmarkManagerEngine functionality |
Maps and Navigation
The Maps and Navigation API is based on plugins.
Since most providers of mapping, geocoding and routing information offer no guarantees that their data is interoperable with the data provided by other services, the plugins are used to group the functionality per service provider.
The plugins are accessed via QGeoServiceProvider, and a Nokia based plugin is part of Qt Mobility.
QGeoMappingManager *mappingManager = 0; QGeoRoutingManager *routingManager = 0; QGeoSearchManager *searchManager = 0; QGeoServiceProvider serviceProvider("nokia"); if (serviceProvider.error() == QGeoServiceProvider::NoError) { mappingManager = serviceProvider.mappingManager(); routingManager = serviceProvider.routingManager(); searchManager = serviceProvider.searchManager(); }
Common classes
Defines a rectangular geographic area | |
Aggregates access to services which provide geographical information |
Mapping
The QGeoMapWidget class is the main class used for displaying and interacting with maps. It is designed for use within the Graphics View Framework, and is a subclass of QGraphicsWidget.
The QGeoMappingManager provides most of the functionality required by QGeoMapWidget. The details of QGeoMappingManager are mostly only important to plugin implementers, as regular users should not need to make use of QGeoMappingManager outside of the QGeoMapWidget constructor:
QGeoMapWidget *widget = new QGeoMapWidget(mappingManager);
Used to display a map and manager the interactions between the user and the map | |
Support for displaying and interacting with maps |
Map objects
QGeoMapObject and its subclasses provide the ability to add graphics to the map specified in terms of coordinates and distances. QGeoMapObject instances can also be grouped into heirarchies in order to simplify the process of creating compound objects and managing groups of objects.
QGeoMapObject used to draw the region within a certain distance of a coordinate | |
Graphical item for display in QGeoMapWidget instancse, that is specified in terms of coordinates and distances |
Routing
QGeoRoutingManager handles requests for routing information.
The requests are created as QGeoRouteRequest instances, which are passed to QGeoRoutingManager::calculateRoute(). The returned QGeoRouteReply instance will contain the result of the request when it is completed.
The QGeoRoute class describes the resulting route. Each route is broken up into a number of QGeoRouteSegment instances, with the division usually occurring at either user specified waypoints or at changes in the mode of transport, like when changing from a train to a bus.
Each QGeoRouteSegment has a QGeoNavigationInstruction instance which describes the instructions that would be issued to a user attempting to follow a route. These instructions a location, which is typically somewhere near the end of the associated QGeoRouteSegment, and instruction text describing how the next QGeoRouteSegment should be reached.
Represents a navigation instruction | |
Represents a route between two points | |
Manages an operation started by an instance of QGeoRoutingManager | |
Represents the parameters and restrictions which define a request for routing information | |
Represents a segment of a route | |
Support for geographic routing operations |
Geocoding and searching for places
QGeoSearchManager handles geocoding, reverse geocoding and free-text search for places.
The free-text search will attempt to geocode text that looks like an address while simultaneously searching any landmark databases that the service pro. It is even possibly to add additional QLandmarkManager instances to the soures of data, so that users can search online databases alongside their personal offline landmarks store.
Support for searching operations related to geographic information | |
Manages an operation started by an instance of QGeoSearchManager |
The Nokia plugin
Qt Mobility comes with a plugin which makes use of the Nokia services relevant to the Maps and Navigation API.
The latest version has the plugin name "nokia" and has plugin version 1.
From the beta release onwards, the use of this plugin will be subject to terms and conditions that will be contained within or linked from this documentation.
Implementing plugins
A plugin implementer needs to subclass QGeoServiceProviderFactory and as many of the ManagerEngine classes as they want to provide implementations for.
Subclassing QGeoServiceProviderFactory will only involve exposing a name and a version by overriding QGeoServiceProviderFactory::providerName() and QGeoServiceProviderFactory::providerVersion(), and overriding QGeoServiceProviderFactory::createSearchManagerEngine(), QGeoServiceProviderFactory::createMappingManagerEngine() and QGeoServiceProviderFactory::createRoutingManagerEngine() as appropriate.
Are used as a bridge between QGeoMapWidget and QGeoMappingManager | |
Interface and convenience methods to implementors of QGeoServiceProvider plugins who want to provides support for displaying and interacting with maps | |
Interface and convenience methods to implementers of QGeoServiceProvider plugins who want to provide access to geographic routing information | |
Interface and convenience methods to implementers of QGeoServiceProvider plugins who want to provide support for searching operations related to geographic data | |
Factory class used as the plugin interface for services related to geographical information |