Using location data and web maps in QML
In this wiki article I describe how you can use web maps and location data in your Qt Quick application. We also see how to integrate CPP and QML code and QML Code and JS code running in webkit. We also see how easy it is to use web APIs. Image below shows the application UI.
You can find the application's latest source code from Nokia Projects (https://projects.forum.nokia.com/qmlwebmap)
Application code consists of three major parts:
- CPP part (Provides Qt application environment and gets location updates from GPS sensors, sone parts of the UI are also here.)
- QML part (Implements major part of the UI by using WebVew element)
- HTML part (HTML files used with maps)
C++ code part has one class and main function. I have also included one UI form that has only combobox for map provder selection. Here's the definition of the class:
class Widget : public QWidget
explicit Widget(QWidget *parent = 0);
Q_PROPERTY(QString mapProvider READ mapProvider WRITE setMapProvider NOTIFY mapProviderChanged)
void setMapProvider(QString newMapProvider);
void posUpdated(double lat, double lon);
We have a class that inherits QWidget. The instance of this class will be our top-level widget. In the public section we define one property (mapProvider) that is used from QML side. It contains html file name that is used in webView.
Then we define two slots. First one is used when user selects map provider from combo box and second one is connected to QGeoPositionInfoSources' signal positionUpdated. This signal is emitted when device's location changes.
In the signal section we define own signals for map provider change & location update.
As member data we have our ui form, QDeclarativeView (runs QML), QGeoPositionInfoSource for location updates and a string for storing map provider.
Widget::Widget(QWidget *parent) :
m_mapProvider = "init.html";
m_view = new QDeclarativeView(this);
ui->comboBox->addItem("Select Map Provider", QVariant("init.html"));
ui->comboBox->addItem("OVI Maps", QVariant("ovimaps.html"));
ui->comboBox->addItem("Google Maps", QVariant("gmaps.html"));
ui->comboBox->addItem("Bing Maps", QVariant("bingmaps.html"));
m_geoSource = QGeoPositionInfoSource::createDefaultSource(this);
connect(m_geoSource, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo)));
In constructor we create application UI and load qml file to QDeclarativeView. We also publish instance of this class (setContextProperty) to QML side, because we want to use signals, slots and properties of this class there. We also set resize mode to SizeRootObjectToView and our root element will automatically have a maximum size. We also create geo position info source and start to listen location updates.