/**Copyright2017GoogleInc.Allrightsreserved.**LicensedundertheApacheLicense,Version2.0(the"License");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan"AS IS"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/importGoogleNavigationimportUIKitclassViewController:UIViewController{varmapView:GMSMapView!varlocationManager:CLLocationManager!overridefuncloadView(){locationManager=CLLocationManager()//Setupthemapview.letcamera=GMSCameraPosition.camera(withLatitude:47.67,longitude:-122.20,zoom:14)mapView=GMSMapView.map(withFrame:.zero,camera:camera)//Showthetermsandconditions.letcompanyName="Ride Sharing Co."GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(withCompanyName:companyName){termsAcceptediniftermsAccepted{//Enablenavigationiftheuseracceptstheterms.self.mapView.isNavigationEnabled=trueself.mapView.settings.compassButton=true//Requestauthorizationtouselocationservices.self.locationManager.requestAlwaysAuthorization()//Requestauthorizationforalertnotificationswhichdeliverguidanceinstructions//inthebackground.UNUserNotificationCenter.current().requestAuthorization(options:[.alert]){granted,errorin//Handledeniedauthorizationtodisplaynotifications.if!granted||error!=nil{print("User rejected request to display notifications.")}}}else{//Handlerejectionoftermsandconditions.}}view=mapViewmakeButton()}//Createarouteandstartguidance.funcstartNav(){vardestinations=[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){routeStatusinguardrouteStatus==.OKelse{print("Handle route statuses that are not OK.")return}self.mapView.navigator?.isGuidanceActive=trueself.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()self.mapView.cameraMode=.following}}//Addabuttontotheview.funcmakeButton(){//Abuttontostartnavigation.letnavButton=UIButton(frame:CGRect(x:5,y:150,width:200,height:35))navButton.backgroundColor=.bluenavButton.alpha=0.5navButton.setTitle("Start navigation",for:.normal)navButton.addTarget(self,action:#selector(startNav), for: .touchUpInside)self.mapView.addSubview(navButton)}}
顯示/隱藏導覽畫面檢視控制器的 Objective-C 程式碼。
/* * 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"@importGoogleNavigation;@interfaceViewController()@end@implementationViewController{GMSMapView*_mapView;CLLocationManager*_locationManager;}-(void)loadView{_locationManager=[[CLLocationManageralloc]init];// Set up the map view.GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:47.67longitude:-122.20zoom:14];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];// Show the terms and conditions.NSString*companyName=@"Ride Sharing Co.";[GMSNavigationServicesshowTermsAndConditionsDialogIfNeededWithCompanyName:companyNamecallback:^(BOOLtermsAccepted){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.[_locationManagerrequestAlwaysAuthorization];// Request authorization for alert notifications which deliver guidance instructions// in the background.UNUserNotificationCenter*center=[UNUserNotificationCentercurrentNotificationCenter];UNAuthorizationOptionsoptions=UNAuthorizationOptionAlert;[centerrequestAuthorizationWithOptions:optionscompletionHandler:^(BOOLgranted,NSError*_Nullableerror){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;[selfmakeButton];}// Create a route and initiate navigation.-(void)startNav{NSArray<GMSNavigationWaypoint*>*destinations=@[[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJnUYTpNASkFQR_gSty5kyoUk"title:@"PCC Natural Market"],[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJJ326ROcSkFQRBfUzOL2DSbo"title:@"Marina Park"]];[_mapView.navigatorsetDestinations:destinationscallback:^(GMSRouteStatusrouteStatus){[_mapView.locationSimulatorsimulateLocationsAlongExistingRoute];_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=[UIButtonbuttonWithType:UIButtonTypeCustom];[navButtonaddTarget:selfaction:@selector(startNav)forControlEvents:UIControlEventTouchUpInside];[navButtonsetTitle:@"Navigate"forState:UIControlStateNormal];[navButtonsetBackgroundColor:[UIColorblueColor]];navButton.frame=CGRectMake(5.0,150.0,100.0,35.0);[_mapViewaddSubview:navButton];}@end
lettermsAndConditionsOptions=GMSNavigationTermsAndConditionsOptions(companyName:"Ride Sharing Co.")GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(with:termsAndConditionsOptions){termsAcceptediniftermsAccepted{// Enable navigation if the user accepts the terms.self.mapView.isNavigationEnabled=trueself.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,errorin// Handle rejection of notification authorization.if!granted||error!=nil{print("Authorization to deliver notifications was rejected.")}}}else{// Handle rejection of terms and conditions.}}
Objective-C
GMSNavigationTermsAndConditionsOptions*termsAndConditionsOptions=[[GMSNavigationTermsAndConditionsOptionsalloc]initWithCompanyName:@"Ride Sharing Co."];[GMSNavigationServicesshowTermsAndConditionsDialogIfNeededWithOptions:termsAndConditionsOptionscallback:^(BOOLtermsAccepted){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.[_locationManagerrequestAlwaysAuthorization];// Request authorization for alert notifications which deliver guidance instructions// in the background.UNUserNotificationCenter*center=[UNUserNotificationCentercurrentNotificationCenter];UNAuthorizationOptionsoptions=UNAuthorizationOptionAlert;[centerrequestAuthorizationWithOptions:optionscompletionHandler:^(BOOLgranted,NSError*_Nullableerror){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.}}];
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-01-14 (世界標準時間)。"],[[["This guide explains how to use the Navigation SDK for iOS to plot a route within your app to a single destination."],["Before using the SDK, ensure the user accepts the terms and conditions and authorizes location services and background notifications."],["Create a `GMSNavigator` and add destinations using `setDestinations` to define the route and initiate guidance by setting `isGuidanceActive` to `true`."],["Set the `travelMode` property of the map view to specify the preferred mode of transportation, such as driving, cycling, walking, or taxi."],["Optionally, configure route preferences like avoiding highways or tolls using the `avoidsHighways` and `avoidsTolls` properties."]]],[]]