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  · 

Part 4 - Stopping for directions

To complete our tour of the Maps API, we're going to add some very basic support for finding transport routes across a map. There is much more functionality available in the routing and navigation API than we are going to use, though some backend plugins may place restrictions on its use to develop, for example, voice-aided navigation applications (such as the Nokia Ovi maps plugin).

We are going to add support for a simple dialog that can be used to search for a destination point and display a line on the map giving the route from the current GPS "My Location" (which we implemented in part 3) to that destination.

First, we implement the dialog along similar lines to the SearchDialog we created earlier:

 class NavigateDialog : public QDialog
 {
     Q_OBJECT
 public:
     NavigateDialog(QWidget *parent=0);
     ~NavigateDialog();

     QString destinationAddress() const;
     QGeoRouteRequest::TravelModes travelMode() const;

 private:
     QLineEdit *addressEdit;
     QComboBox *modeCombo;
 };

Once again we make use of a QFormLayout inside the dialog to align the widgets together. We have a QLineEdit for the address of the destination, and a QComboBox listing possible travel modes.

In MainWindow, we create a new slot for showing the navigate dialog:

 void MainWindow::showNavigateDialog()
 {
     NavigateDialog nd;
     if (nd.exec() == QDialog::Accepted) {
         if (markerManager) {
             // will fill this out later
         }
     }
 }

And we hook it up to a Menu action:

 MainWindow::MainWindow() :
     ...
 {
     ...
     QMenu *navigateMenu = new QMenu("Directions");
     mbar->addMenu(navigateMenu);

     navigateMenu->addAction("From here to address", this, SLOT(showNavigateDialog()));
     ....
 }

Now we need a new class to manage routing. Finding a route to an address is a two-stage process: first, a geocode search is performed on the address to get a lat/lon coordinate. Then this coordinate is used in a route request which finally returns the desired route.

Our new class is called Navigator, and includes private slots to handle each of these events:

 class Navigator : public QObject
 {
     Q_OBJECT
 public:
     Navigator(QGeoRoutingManager *routingManager, QGeoSearchManager *searchManager,
               MapsWidget *mapsWidget, const QString &address,
               const QGeoRouteRequest &requestTemplate);
     ~Navigator();

     void start();
     QGeoRoute route() const;

 signals:
     void finished();
     void searchError(QGeoSearchReply::Error error, QString errorString);
     void routingError(QGeoRouteReply::Error error, QString errorString);

 private slots:
     void on_addressSearchFinished();
     void on_routingFinished();

 private:
     QString address;
     QGeoRouteRequest request;

     QGeoRoutingManager *routingManager;
     QGeoSearchManager *searchManager;
     MapsWidget *mapsWidget;

     QGeoSearchReply *addressReply;
     QGeoRouteReply *routeReply;

     QGeoMapRouteObject *routeObject;
     Marker *endMarker;
     Marker *startMarker;

     QGeoRoute firstRoute;
 };

The intended lifecycle of a Navigator is to be created when the dialog is accepted, then start() is called to begin the requests. The requests will either error out or complete, emitting one of finished(), searchError(), or routingError() signals. If the request is successful, the Navigator creates the appropriate markers and draws the route on the map (using a QGeoMapRouteObject). It then owns these map objects and will remove them when deleted.

Now for the Navigator's implementation: first, the start() method, which begins the process by launching the search request.

A QGeoRouteRequest is specified first and foremost by the points the route must pass through (the waypoints). In our case we only wish two have two waypoints, the user's starting location, and the destination. We add the first of these in start() and the second after the search request returns.

 void Navigator::start()
 {
     QList<QGeoCoordinate> waypoints = request.waypoints();
     waypoints.append(mapsWidget->markerManager()->myLocation());
     request.setWaypoints(waypoints);

     startMarker = new Marker(Marker::StartMarker);
     startMarker->setCoordinate(mapsWidget->markerManager()->myLocation());
     startMarker->setName("Start point");
     mapsWidget->map()->addMapObject(startMarker);

     addressReply = searchManager->search(address);
     if (addressReply->isFinished()) {
         on_addressSearchFinished();
     } else {
         connect(addressReply, SIGNAL(error(QGeoSearchReply::Error,QString)),
                 this, SIGNAL(searchError(QGeoSearchReply::Error,QString)));
         connect(addressReply, SIGNAL(finished()),
                 this, SLOT(on_addressSearchFinished()));
     }
 }

After the request finishes, the on_addressSearchFinished() slot will be invoked, which finishes off the routing request and sends it in a similar fashion:

 void Navigator::on_addressSearchFinished()
 {
     if (addressReply->places().size() <= 0) {
         addressReply->deleteLater();
         return;
     }

     QGeoPlace place = addressReply->places().at(0);

     QList<QGeoCoordinate> waypoints = request.waypoints();
     waypoints.append(place.coordinate());
     request.setWaypoints(waypoints);

     routeReply = routingManager->calculateRoute(request);
     if (routeReply->isFinished()) {
         on_routingFinished();
     } else {
         connect(routeReply, SIGNAL(error(QGeoRouteReply::Error,QString)),
                 this, SIGNAL(routingError(QGeoRouteReply::Error,QString)));
         connect(routeReply, SIGNAL(finished()),
                 this, SLOT(on_routingFinished()));
     }

     endMarker = new Marker(Marker::EndMarker);
     endMarker->setCoordinate(place.coordinate());
     endMarker->setAddress(place.address());
     endMarker->setName("Destination");
     mapsWidget->map()->addMapObject(endMarker);

     addressReply->deleteLater();
 }

And then finally, when the routing request returns we can create the route object on the map and emit finished():

 void Navigator::on_routingFinished()
 {
     if (routeReply->routes().size() <= 0) {
         emit routingError(QGeoRouteReply::NoError, "No valid routes returned");
         routeReply->deleteLater();
         return;
     }

     QGeoRoute route = routeReply->routes().at(0);
     firstRoute = route;

     routeObject = new QGeoMapRouteObject;
     routeObject->setRoute(route);
     routeObject->setPen(QPen(Qt::blue, 2.0));

     mapsWidget->map()->addMapObject(routeObject);

     emit finished();
     routeReply->deleteLater();
 }

Now in MainWindow we have to create a new Navigator instance after the dialog returns. We store the Navigator instance in a member variable so that we can delete the last one in order to remove its map objects before the new one is constructed:

 class MainWindow : public QMainWindow
 {
 private:
     Navigator *lastNavigator;
     ...
 };

 void MainWindow::showNavigateDialog()
 {
     NavigateDialog nd;
     if (nd.exec() == QDialog::Accepted) {
         if (markerManager) {
             QGeoRouteRequest req;

             req.setTravelModes(nd.travelMode());

             if (lastNavigator)
                 lastNavigator->deleteLater();

             Navigator *nvg = new Navigator(serviceProvider->routingManager(),
                                            serviceProvider->searchManager(),
                                            mapsWidget, nd.destinationAddress(),
                                            req);

             lastNavigator = nvg;

             connect(nvg, SIGNAL(searchError(QGeoSearchReply::Error,QString)),
                     this, SLOT(showErrorMessage(QGeoSearchReply::Error,QString)));
             connect(nvg, SIGNAL(routingError(QGeoRouteReply::Error,QString)),
                     this, SLOT(showErrorMessage(QGeoRouteReply::Error,QString)));

             mapsWidget->statusBar()->setText("Routing...");
             mapsWidget->statusBar()->show();

             nvg->start();

             connect(nvg, SIGNAL(finished()),
                     mapsWidget->statusBar(), SLOT(hide()));
         }
     }
 }

And now we have basic support for calculating and displaying routes on the map. In addition to this, we could quite easily use the QGeoRoute object to show a list of directions and overall statistics about the journey. For more information see the documentation about QGeoRoute.

In the final part of this tutorial, we will optimise the maps demo so far for mobile platforms in order to deploy it to a phone.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 23
  2. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 35
  3. Une nouvelle ère d'IHM 3D pour les automobiles, un concept proposé par Digia et implémenté avec Qt 3
  4. PySide devient un add-on Qt et rejoint le Qt Project et le modèle d'open gouvernance 1
  5. Qt Creator 2.5 est sorti en beta, l'EDI supporte maintenant plus de fonctionnalités de C++11 2
  6. Vingt sociétés montrent leurs décodeurs basés sur Qt au IPTV World Forum, en en exploitant diverses facettes (déclaratif, Web, widgets) 0
  7. Thread travailleur avec Qt en utilisant les signaux et les slots, un article de Christophe Dumez traduit par Thibaut Cuvelier 1
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 49
  4. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  5. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 23
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
Page suivante

Le Qt Labs au hasard

Logo

Améliorer les performances de Qt avec les chaînes de caractères avec SIMD... ou pas

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

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.2
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