Poruszanie się po trasie

Aby wyznaczyć w aplikacji trasę do jednego miejsca docelowego za pomocą pakietu SDK do nawigacji na iOS, postępuj zgodnie z tym przewodnikiem.

Omówienie

  1. Zintegruj pakiet SDK Nawigacji ze swoją aplikacją zgodnie z instrukcjami podanymi w sekcji Konfigurowanie projektu.
  2. Skonfiguruj GMSMapView.
  3. Zapytaj użytkownika o zaakceptowanie warunków korzystania z usługi i zezwolenie na usługi lokalizacyjne oraz powiadomienia w tle.
  4. Utwórz tablicę zawierającą co najmniej 1 miejsce docelowe.
  5. Określ GMSNavigator, aby sterować nawigacją zakręt po zakręcie.

Wyświetlanie kodu

/*
 * 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

Zapytaj użytkownika o wymagane uprawnienia

Zanim zacznie korzystać z pakietu SDK nawigacji, użytkownik musi zaakceptować warunki korzystania z usługi i zezwolić na korzystanie z usług lokalizacyjnych, które są wymagane do nawigacji. Jeśli aplikacja będzie działać w tle, musi też poprosić użytkownika o autoryzację powiadomień z instrukcjami. W tej sekcji dowiesz się, jak wyświetlić wymagane prośby o autoryzację.

Autoryzowanie usług lokalizacyjnych

Pakiet SDK Nawigacji korzysta z usług lokalizacyjnych, które wymagają autoryzacji użytkownika. Aby włączyć usługi lokalizacyjne i wyświetlić okno autoryzacji:

  1. Dodaj klucz NSLocationAlwaysUsageDescription do Info.plist.
  2. W polu wartości dodaj krótkie wyjaśnienie, dlaczego Twoja aplikacja wymaga dostępu do usług lokalizacyjnych. Na przykład: „Ta aplikacja potrzebuje uprawnienia do korzystania z usług lokalizacyjnych na potrzeby nawigacji krok po kroku”.

  3. Aby wyświetlić okno autoryzacji, wywołaj funkcję requestAlwaysAuthorization() instancji menedżera lokalizacji.

self.locationManager.requestAlwaysAuthorization()

[_locationManager requestAlwaysAuthorization];

Autoryzowanie powiadomień o alertach w przypadku wskazówek w tle

Pakiet SDK nawigacji wymaga zgody użytkownika na wyświetlanie alertów i powiadomień, gdy aplikacja działa w tle. Dodaj ten kod, aby poprosić użytkownika o zezwolenie na wyświetlanie tych powiadomień:

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");
     }
   }];

Zaakceptuj warunki korzystania z usługi.

Użyj tego kodu, aby wyświetlić okno warunków korzystania z usługi i zezwolić na nawigację po zaakceptowaniu warunków przez użytkownika. Pamiętaj, że ten przykład zawiera kod dla usług lokalizacyjnych i powiadomień o alertach (pokazanych wcześniej).

  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.
   }
 }];

Tworzenie trasy i rozpoczynanie wskazówek

Aby wyznaczyć trasę, wywołaj metodę setDestinations() klasy Navigator z tablicą zawierającą co najmniej jeden punkt docelowy (GMSNavigationWaypoint). Jeśli obliczenia się powiodą, trasa zostanie wyświetlona na mapie. Aby rozpocząć nawigację po trasie, zaczynając od pierwszego miejsca docelowego, w funkcji wywołania zwrotnego ustaw wartość isGuidanceActive na true.

Ten przykład pokazuje:

  • Tworzenie nowej trasy z 2 miejscami docelowymi.
  • Wskazówki dotyczące rozpoczęcia.
  • Włączanie powiadomień o przewodniku w tle.
  • symulowanie przejazdu po trasie (opcjonalnie).
  • Ustawienie trybu aparatu na „śledzenie” (opcjonalnie).

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;
                             }];
}

Więcej informacji o identyfikatorach miejsca znajdziesz w artykule Identyfikatory miejsca.

Wybierz środek transportu

Tryb podróży określa, jaki typ trasy zostanie pobrany, oraz sposób określenia trasy użytkownika. Na trasie możesz ustawić jeden z 4 rodzajów przejazdu: samochodem, rowerem, pieszo lub taksówką. W trybie jazdy samochodem i taksówką trasa użytkownika jest ustalana na podstawie kierunku jazdy. W trybie jazdy na rowerze i chodzenia trasa jest ustalana na podstawie kierunku, w którym skierowane jest urządzenie.

Ustaw właściwość travelMode widoku mapy, jak w tym przykładzie:

self.mapView.travelMode = .cycling

_mapView.travelMode = GMSNavigationTravelModeCycling;

Ustawianie dróg do unikania

Użyj właściwości avoidsHighwaysavoidsTolls BOOL, aby uniknąć autostrad lub dróg płatnych na trasie.

self.mapView.navigator?.avoidsTolls = true

_mapView.navigator.avoidsTolls = YES;

Wyszukiwarka identyfikatorów PlaceID

Za pomocą wyszukiwarki identyfikatorów miejsc możesz znaleźć identyfikatory miejsc, które możesz wykorzystać jako miejsca docelowe na trasie. Dodaj miejsce docelowe z placeID za pomocą GMSNavigationWaypoint.

tekst pływający,

Możesz dodawać tekst unoszący się nad innymi elementami w dowolnym miejscu w aplikacji, o ile nie wpływa to na atrybucję Google. Pakiet SDK Nawigacji nie obsługuje zakotwiczenia tekstu do współrzędnych geograficznych na mapie ani do etykiety. Więcej informacji znajdziesz w oknach informacji.