Itinéraire

Suivez ce guide pour tracer un itinéraire vers une seule destination dans votre application à l'aide du SDK Navigation pour iOS.

Présentation

  1. Intégrez le SDK Navigation à votre application, comme décrit dans la section Configurer votre projet.
  2. Configurez un GMSMapView.
  3. Invitez l'utilisateur à accepter les conditions d'utilisation, et à autoriser les services de localisation et les notifications en arrière-plan.
  4. Créez un tableau contenant une ou plusieurs destinations.
  5. Définissez un GMSNavigator pour contrôler la navigation détaillée.

Voir le code

/*
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import GoogleNavigation
import UIKit

class ViewController: UIViewController {

  var mapView: GMSMapView!
  var locationManager: CLLocationManager!

  override func loadView() {

    locationManager = CLLocationManager()

    // Set up the map view.
    let camera = GMSCameraPosition.camera(withLatitude: 47.67, longitude: -122.20, zoom: 14)
    mapView = GMSMapView.map(withFrame: .zero, camera: camera)

    // Show the terms and conditions.
    let companyName = "Ride Sharing Co."
    GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(
      withCompanyName: companyName
    ) { termsAccepted in
      if termsAccepted {
        // Enable navigation if the user accepts the terms.
        self.mapView.isNavigationEnabled = true
        self.mapView.settings.compassButton = true

        // Request authorization to use location services.
        self.locationManager.requestAlwaysAuthorization()

        // Request authorization for alert notifications which deliver guidance instructions
        // in the background.
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) {
          granted, error in
          // Handle denied authorization to display notifications.
          if !granted || error != nil {
            print("User rejected request to display notifications.")
          }
        }
      } else {
        // Handle rejection of terms and conditions.
      }
    }

    view = mapView

    makeButton()
  }

  // Create a route and start guidance.
  func startNav() {
    var destinations = [GMSNavigationWaypoint]()
    destinations.append(
      GMSNavigationWaypoint.init(
        placeID: "ChIJnUYTpNASkFQR_gSty5kyoUk",
        title: "PCC Natural Market")!)
    destinations.append(
      GMSNavigationWaypoint.init(
        placeID: "ChIJJ326ROcSkFQRBfUzOL2DSbo",
        title: "Marina Park")!)

    mapView.navigator?.setDestinations(
      destinations
    ) { routeStatus in
      guard routeStatus == .OK else {
        print("Handle route statuses that are not OK.")
        return
      }
      self.mapView.navigator?.isGuidanceActive = true
      self.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()
      self.mapView.cameraMode = .following
    }
  }

  // Add a button to the view.
  func makeButton() {
    // A button to start navigation.
    let navButton = UIButton(frame: CGRect(x: 5, y: 150, width: 200, height: 35))
    navButton.backgroundColor = .blue
    navButton.alpha = 0.5
    navButton.setTitle("Start navigation", for: .normal)
    navButton.addTarget(self, action: #selector(startNav), for: .touchUpInside)
    self.mapView.addSubview(navButton)
  }

}
/*
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "ViewController.h"
@import GoogleNavigation;

@interface ViewController ()
@end

@implementation ViewController {
  GMSMapView *_mapView;
  CLLocationManager *_locationManager;
}

- (void)loadView {

  _locationManager = [[CLLocationManager alloc] init];

  // Set up the map view.
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:47.67
                                                          longitude:-122.20
                                                               zoom:14];
  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];

  // Show the terms and conditions.
  NSString *companyName = @"Ride Sharing Co.";
  [GMSNavigationServices
    showTermsAndConditionsDialogIfNeededWithCompanyName:companyName
                                               callback:^(BOOL termsAccepted) {
     if (termsAccepted) {
       // Enable navigation if the user accepts the terms.
       _mapView.navigationEnabled = YES;
       _mapView.settings.compassButton = YES;

       // Request authorization to use the current device location.
       [_locationManager requestAlwaysAuthorization];

       // Request authorization for alert notifications which deliver guidance instructions
       // in the background.
       UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
       UNAuthorizationOptions options = UNAuthorizationOptionAlert;
       [center requestAuthorizationWithOptions:options
                             completionHandler:^(BOOL granted, NSError *_Nullable error) {
                               if (!error && granted) {
                                 NSLog(@"iOS Notification Permission: newly Granted");
                               } else {
                                 NSLog(@"iOS Notification Permission: Failed or Denied");
                               }
                             }];
     } else {
       // Handle rejection of the terms and conditions.
     }
   }];

  self.view = _mapView;

  [self makeButton];
}

// Create a route and initiate navigation.
- (void)startNav {
  NSArray<GMSNavigationWaypoint *> *destinations =
  @[[[GMSNavigationWaypoint alloc] initWithPlaceID:@"ChIJnUYTpNASkFQR_gSty5kyoUk"
                                             title:@"PCC Natural Market"],
    [[GMSNavigationWaypoint alloc] initWithPlaceID:@"ChIJJ326ROcSkFQRBfUzOL2DSbo"
                                             title:@"Marina Park"]];

  [_mapView.navigator setDestinations:destinations
                             callback:^(GMSRouteStatus routeStatus){
                               [_mapView.locationSimulator simulateLocationsAlongExistingRoute];
                               _mapView.navigator.guidanceActive = YES;
                               _mapView.navigator.sendsBackgroundNotifications = YES;
                               _mapView.cameraMode = GMSNavigationCameraModeFollowing;
                             }];
}

// Add a button to the view.
- (void)makeButton {
  // A button to start navigation.
  UIButton *navButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [navButton addTarget:self
                action:@selector(startNav)
      forControlEvents:UIControlEventTouchUpInside];
  [navButton setTitle:@"Navigate" forState:UIControlStateNormal];
  [navButton setBackgroundColor:[UIColor blueColor]];
  navButton.frame = CGRectMake(5.0, 150.0, 100.0, 35.0);
  [_mapView addSubview:navButton];
}

@end

Demander à l'utilisateur les autorisations nécessaires

Avant d'utiliser le SDK Navigation, l'utilisateur doit accepter les conditions d'utilisation et autoriser l'utilisation des services de localisation, ce qui est nécessaire pour la navigation. Si votre application s'exécute en arrière-plan, elle doit également inviter l'utilisateur à autoriser les notifications d'alertes de guidage. Cette section explique comment afficher les invites d'autorisation requises.

Autoriser les services de localisation

Le SDK Navigation utilise les services de localisation, ce qui nécessite l'autorisation de l'utilisateur. Pour activer les services de localisation et afficher la boîte de dialogue d'autorisation, procédez comme suit:

  1. Ajoutez la clé NSLocationAlwaysUsageDescription à Info.plist.
  2. Pour la valeur, ajoutez une brève explication de la raison pour laquelle votre application nécessite des services de localisation. Par exemple: "Cette application a besoin d'une autorisation pour utiliser les services de localisation pour la navigation étape par étape."

  3. Pour afficher la boîte de dialogue d'autorisation, appelez requestAlwaysAuthorization() de l'instance du Gestionnaire de position.

self.locationManager.requestAlwaysAuthorization()

[_locationManager requestAlwaysAuthorization];

Autoriser les notifications d'alerte pour les instructions en arrière-plan

Le SDK Navigation a besoin de l'autorisation de l'utilisateur pour envoyer des notifications d'alerte lorsque l'application s'exécute en arrière-plan. Ajoutez le code suivant pour demander à l'utilisateur l'autorisation d'afficher ces notifications:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) {
  granted, error in
    // Handle denied authorization to display notifications.
    if !granted || error != nil {
      print("User rejected request to display notifications.")
    }
}

// Request authorization for alert notifications.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions options = UNAuthorizationOptionAlert;
[center requestAuthorizationWithOptions:options
                      completionHandler:
 ^(
   BOOL granted,
   NSError *_Nullable error) {
     if (!error && granted) {
       NSLog(@"iOS Notification Permission: newly Granted");
     } else {
       NSLog(@"iOS Notification Permission: Failed or Denied");
     }
   }];

Accepter les conditions d'utilisation

Utilisez le code suivant pour afficher la boîte de dialogue des conditions d'utilisation et activer la navigation lorsque l'utilisateur accepte les conditions. Notez que cet exemple inclut le code pour les services de localisation et les notifications d'alertes de guidage (illustré précédemment).

  let termsAndConditionsOptions = GMSNavigationTermsAndConditionsOptions(companyName: "Ride Sharing Co.")

  GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(
    with: termsAndConditionsOptions) { termsAccepted in
    if termsAccepted {
      // Enable navigation if the user accepts the terms.
      self.mapView.isNavigationEnabled = true
      self.mapView.settings.compassButton = true

      // Request authorization to use location services.
      self.locationManager.requestAlwaysAuthorization()

      // Request authorization for alert notifications which deliver guidance instructions
      // in the background.
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) {
      granted, error in
        // Handle rejection of notification authorization.
        if !granted || error != nil {
          print("Authorization to deliver notifications was rejected.")
        }
      }
    } else {
      // Handle rejection of terms and conditions.
    }
  }

GMSNavigationTermsAndConditionsOptions *termsAndConditionsOptions = [[GMSNavigationTermsAndConditionsOptions alloc] initWithCompanyName:@"Ride Sharing Co."];

[GMSNavigationServices
  showTermsAndConditionsDialogIfNeededWithOptions:termsAndConditionsOptions
  callback:^(BOOL termsAccepted) {
   if (termsAccepted) {
     // Enable navigation if the user accepts the terms.
     _mapView.navigationEnabled = YES;
     _mapView.settings.compassButton = YES;

     // Request authorization to use the current device location.
     [_locationManager requestAlwaysAuthorization];

     // Request authorization for alert notifications which deliver guidance instructions
     // in the background.
     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
     UNAuthorizationOptions options = UNAuthorizationOptionAlert;
     [center requestAuthorizationWithOptions:options
                           completionHandler:
     ^(
       BOOL granted,
       NSError *_Nullable error) {
         if (!error && granted) {
           NSLog(@"iOS Notification Permission: newly Granted");
         } else {
           NSLog(@"iOS Notification Permission: Failed or Denied");
         }
       }];
   } else {
     // Handle rejection of the terms and conditions.
   }
 }];

Créer un itinéraire et démarrer la navigation

Pour tracer un itinéraire, appelez la méthode setDestinations() du navigateur avec un tableau contenant une ou plusieurs destinations (GMSNavigationWaypoint) à visiter. Si le calcul aboutit, l'itinéraire s'affiche sur la carte. Pour démarrer la navigation sur l'itinéraire, en commençant par la première destination, définissez isGuidanceActive sur true dans le rappel.

L'exemple suivant montre :

  • Créer un itinéraire avec deux destinations
  • Conseils de départ.
  • Activer les notifications de guidage en arrière-plan
  • Simuler un trajet sur le parcours (facultatif)
  • Définir le mode de l'appareil photo sur "Suivre" (facultatif)

func startNav() {
  var destinations = [GMSNavigationWaypoint]()
  destinations.append(GMSNavigationWaypoint.init(placeID: "ChIJnUYTpNASkFQR_gSty5kyoUk",
                                                 title: "PCC Natural Market")!)
  destinations.append(GMSNavigationWaypoint.init(placeID:"ChIJJ326ROcSkFQRBfUzOL2DSbo",
                                                 title:"Marina Park")!)

  mapView.navigator?.setDestinations(destinations) { routeStatus in
    self.mapView.navigator?.isGuidanceActive = true
    self.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()
    self.mapView.cameraMode = .following
  }
}

- (void)startNav {
  NSArray<GMSNavigationWaypoint *> *destinations =
  @[[[GMSNavigationWaypoint alloc] initWithPlaceID:@"ChIJnUYTpNASkFQR_gSty5kyoUk"
                                             title:@"PCC Natural Market"],
    [[GMSNavigationWaypoint alloc] initWithPlaceID:@"ChIJJ326ROcSkFQRBfUzOL2DSbo"
                                             title:@"Marina Park"]];

  [_mapView.navigator setDestinations:destinations
                             callback:^(GMSRouteStatus routeStatus){
                               [_mapView.locationSimulator simulateLocationsAlongExistingRoute];
                               _mapView.navigator.guidanceActive = YES;
                               _mapView.cameraMode = GMSNavigationCameraModeFollowing;
                             }];
}

Pour en savoir plus sur les ID de lieu, consultez ID de lieu.

Définir le mode de transport

Le mode de déplacement détermine le type d'itinéraire qui sera extrait et la façon dont le parcours de l'utilisateur est déterminé. Vous pouvez définir l'un des quatre modes de transport pour un itinéraire: voiture, vélo, marche et taxi. En mode conduite et taxi, le parcours de l'utilisateur est basé sur la direction du trajet. En mode vélo et à pied, le parcours est représenté par la direction vers laquelle l'appareil est orienté.

Définissez la propriété travelMode de la vue de la carte, comme illustré dans l'exemple suivant:

self.mapView.travelMode = .cycling

_mapView.travelMode = GMSNavigationTravelModeCycling;

Définir des routes à éviter

Utilisez les propriétés BOOL avoidsHighways et avoidsTolls pour éviter les autoroutes et/ou les routes à péage sur un trajet.

self.mapView.navigator?.avoidsTolls = true

_mapView.navigator.avoidsTolls = YES;

Outil de recherche d'ID de lieu

Vous pouvez utiliser l'outil de recherche d'ID de lieu pour trouver les ID de lieu à utiliser pour les destinations de parcours. Ajoutez une destination à partir d'un placeID avec GMSNavigationWaypoint.

Texte flottant

Vous pouvez ajouter du texte flottant n'importe où dans votre application, à condition que l'attribution Google ne soit pas masquée. Le SDK Navigation n'est pas compatible avec l'ancrage du texte à une latitude/longitude sur la carte ni à un libellé. Pour en savoir plus, consultez la section Fenêtres d'informations.