Folgen Sie dieser Anleitung, um mit dem Navigation SDK for iOS eine Route zu einem einzelnen Ziel in Ihrer App zu planen.
Übersicht
- Binden Sie das Navigation SDK wie im Abschnitt Projekt einrichten beschrieben in Ihre App ein.
- Konfigurieren Sie eine
GMSMapView
. - Bitten Sie den Nutzer, die Nutzungsbedingungen zu akzeptieren und Standortdienste und Benachrichtigungen im Hintergrund zu autorisieren.
- Erstellen Sie ein Array mit einem oder mehreren Zielen.
Definieren Sie eine
GMSNavigator
, um die detaillierte Routenführung zu steuern.- Fügen Sie Ziele mit
setDestinations
hinzu. - Stellen Sie
isGuidanceActive
auftrue
, um die Navigation zu starten. - Mit
simulateLocationsAlongExistingRoute
können Sie den Fortschritt des Fahrzeugs auf der Route simulieren, um Ihre App zu testen, zu debuggen und zu demonstrieren.
- Fügen Sie Ziele mit
Code
Swift-Code für den Navigations-Viewcontroller ein- oder ausblenden
/* * 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) } }
Objective-C-Code für den Navigations-View-Controller anzeigen/ausblenden
/* * 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
Nutzer um die erforderlichen Autorisierungen bitten
Bevor Nutzer das Navigations-SDK verwenden können, müssen sie den Nutzungsbedingungen zustimmen und die Verwendung von Standortdiensten autorisieren, was für die Navigation erforderlich ist. Wenn Ihre App im Hintergrund ausgeführt wird, muss sie den Nutzer auch auffordern, Benachrichtigungen zu Wegbeschreibungen zu autorisieren. In diesem Abschnitt wird gezeigt, wie Sie die erforderlichen Autorisierungsaufforderungen anzeigen.
Standortdienste autorisieren
Das Navigation SDK verwendet Standortdienste, für die eine Nutzerautorisierung erforderlich ist. So aktivieren Sie die Standortdienste und rufen den Autorisierungsdialog auf:
- Fügen Sie den Schlüssel
NSLocationAlwaysUsageDescription
zuInfo.plist
hinzu. Geben Sie als Wert eine kurze Erklärung dafür an, warum Ihre App Standortdienste benötigt. Beispiel: „Diese App benötigt die Berechtigung zur Nutzung von Standortdiensten für die detaillierte Navigation.“
Wenn Sie das Autorisierungsdialogfeld anzeigen möchten, rufen Sie
requestAlwaysAuthorization()
der Standortmanagerinstanz auf.
self.locationManager.requestAlwaysAuthorization()
[_locationManager requestAlwaysAuthorization];
Benachrichtigungen für die Hintergrundnavigation autorisieren
Das Navigations-SDK benötigt die Nutzerberechtigung, um Benachrichtigungen zu senden, wenn die App im Hintergrund ausgeführt wird. Fügen Sie den folgenden Code hinzu, um den Nutzer um Erlaubnis zum Anzeigen dieser Benachrichtigungen zu bitten:
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");
}
}];
Nutzungsbedingungen akzeptieren
Mit dem folgenden Code wird das Dialogfeld mit den Nutzungsbedingungen angezeigt und die Navigation aktiviert, wenn der Nutzer die Nutzungsbedingungen akzeptiert. Dieses Beispiel enthält den Code für Standortdienste und Benachrichtigungen zu Wegbeschreibungen (siehe oben).
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.
}
}];
Route erstellen und Navigation starten
Wenn Sie eine Route planen möchten, rufen Sie die setDestinations()
-Methode des Navigationstools mit einem Array auf, das ein oder mehrere Ziele (GMSNavigationWaypoint
) enthält, die besucht werden sollen. Wenn die Route erfolgreich berechnet wurde, wird sie auf der Karte angezeigt. Wenn Sie die Navigation entlang der Route starten möchten, beginnend mit dem ersten Ziel, setzen Sie im Rückruf isGuidanceActive
auf true
.
Im folgenden Beispiel wird gezeigt:
- Erstellen einer neuen Route mit zwei Zielen
- Startleitfaden
- Benachrichtigungen für die Hintergrundnavigation aktivieren
- Fahrt entlang der Route simulieren (optional)
- Kameramodus auf „Folgen“ stellen (optional)
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;
}];
}
Weitere Informationen zu Orts-IDs finden Sie unter Orts-IDs.
Mobilitätsform?
Mit dem Mobilitätsmodus wird festgelegt, welche Art von Route abgerufen wird und wie der Kurs des Nutzers bestimmt wird. Sie können für eine Route einen von vier Verkehrsmitteln festlegen: Auto, Fahrrad, Fußgänger oder Taxi. Im Auto- und Taximodus basiert der Kurs des Nutzers auf der Fahrtrichtung. Im Fahrrad- und Fußgängermodus wird der Kurs durch die Richtung dargestellt, in die das Gerät zeigt.
Legen Sie die Eigenschaft travelMode
der Kartenansicht fest, wie im folgenden Beispiel gezeigt:
self.mapView.travelMode = .cycling
_mapView.travelMode = GMSNavigationTravelModeCycling;
Zu vermeidende Straßen festlegen
Verwenden Sie die Properties avoidsHighways
und avoidsTolls
BOOL
, um Autobahnen und/oder Mautstraßen entlang einer Route zu vermeiden.
self.mapView.navigator?.avoidsTolls = true
_mapView.navigator.avoidsTolls = YES;
PlaceID-Suche
Mit dem PlaceID Finder können Sie Orts-IDs für Routenziele ermitteln. Fügen Sie mit GMSNavigationWaypoint
ein Ziel aus einer placeID
hinzu.
Schwebender Text
Sie können Textfelder überall in Ihrer App einfügen, solange die Google-Attribution nicht verdeckt wird. Das Navigation SDK unterstützt nicht das Anpinnen von Text an einen Breiten-/Längengrad auf der Karte oder an ein Label. Weitere Informationen finden Sie unter Infofenster.