Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Hãy sử dụng hướng dẫn này để cho phép ứng dụng của bạn lắng nghe và phản hồi nhiều sự kiện thay đổi khi người dùng di chuyển dọc theo một tuyến đường. Hướng dẫn này không đề cập đến việc xác định một tuyến đường, mà chỉ đề cập đến việc phản hồi các sự kiện dọc theo một tuyến đường.
Tổng quan
Navigation SDK cho iOS cung cấp cho bạn các trình nghe được liên kết với vị trí của người dùng và các điều kiện dọc theo tuyến đường, cũng như dữ liệu quan trọng về thời gian và khoảng cách. Trên trình điều khiển khung hiển thị của bản đồ, ứng dụng của bạn cần áp dụng các giao thức cho những trình nghe này: GMSRoadSnappedLocationProviderListener và GMSNavigatorListener.
Danh sách này cho biết các phương thức trình nghe có sẵn cho sự kiện điều hướng:
/**Copyright2020GoogleInc.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,GMSNavigatorListener,GMSRoadSnappedLocationProviderListener{varmapView:GMSMapView!varlocationManager:CLLocationManager!overridefuncloadView(){locationManager=CLLocationManager()letcamera=GMSCameraPosition.camera(withLatitude:47.67,longitude:-122.20,zoom:14)mapView=GMSMapView.map(withFrame:CGRect.zero,camera:camera)//AddlistenersforGMSNavigatorandGMSRoadSnappedLocationProvider.mapView.navigator?.add(self)mapView.roadSnappedLocationProvider?.add(self)//Setthetimeupdatethreshold(seconds)anddistanceupdatethreshold(meters).mapView.navigator?.timeUpdateThreshold=10mapView.navigator?.distanceUpdateThreshold=100//Showthetermsandconditions.letcompanyName="Ride Sharing Co."GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(withCompanyName:companyName){termsAcceptediniftermsAccepted{//Enablenavigationiftheuseracceptstheterms.self.mapView.isNavigationEnabled=true//Requestauthorizationtouselocationservices.self.locationManager.requestAlwaysAuthorization()//Requestauthorizationforalertnotificationswhichdeliverguidanceinstructions//inthebackground.UNUserNotificationCenter.current().requestAuthorization(options:[.alert]){granted,errorin//Handledeniedauthorizationtodisplaynotifications.if!granted||error!=nil{print("Authorization to deliver notifications was rejected.")}}}else{//Handlethecasewhentheuserrejectsthetermsandconditions.}}view=mapViewmakeButton()}//Createarouteandstartguidance.@objcfuncstartNav(){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.cameraMode=.followingself.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()}mapView.roadSnappedLocationProvider?.startUpdatingLocation()}//Listenertohandlecontinuouslocationupdates.funclocationProvider(_locationProvider:GMSRoadSnappedLocationProvider,didUpdatelocation:CLLocation){print("Location: \(location.description)")}//Listenertohandlespeedingevents.funcnavigator(_navigator:GMSNavigator,didUpdateSpeedingPercentagepercentageAboveLimit:CGFloat){print("Speed is \(percentageAboveLimit) above the limit.")}//Listenertohandlearrivalevents.funcnavigator(_navigator:GMSNavigator,didArriveAtwaypoint:GMSNavigationWaypoint){print("You have arrived at: \(waypoint.title)")mapView.navigator?.continueToNextDestination()mapView.navigator?.isGuidanceActive=true}//Listenerforroutechangeevents.funcnavigatorDidChangeRoute(_navigator:GMSNavigator){print("The route has changed.")}//Listenerfortimetonextdestination.funcnavigator(_navigator:GMSNavigator,didUpdateRemainingTimetime:TimeInterval){print("Time to next destination: \(time)")}//Delegatefordistancetonextdestination.funcnavigator(_navigator:GMSNavigator,didUpdateRemainingDistancedistance:CLLocationDistance){letmiles=distance*0.00062137print("Distance to next destination: \(miles) miles.")}//Delegatefortrafficupdatestonextdestinationfuncnavigator(_navigator:GMSNavigator,didUpdatedelayCategory:GMSNavigationDelayCategory){print("Delay category to next destination: \(String(describing: delayCategory)).")}//Delegateforsuggestedlightingmodechanges.funcnavigator(_navigator:GMSNavigator,didChangeSuggestedLightingModelightingMode:GMSNavigationLightingMode){print("Suggested lighting mode has changed: \(String(describing: lightingMode))")//Changetothesuggestedlightingmode.mapView.lightingMode=lightingMode}//Addabuttontotheview.funcmakeButton(){//Startnavigation.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)}}
Hiện/Ẩn mã Objective-C cho một trình nghe sự kiện.
/* * Copyright 2020 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()<GMSNavigatorListener,GMSRoadSnappedLocationProviderListener>
@end@implementationViewController{GMSMapView*_mapView;CLLocationManager*_locationManager;}-(void)loadView{_locationManager=[[CLLocationManageralloc]init];GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:47.67longitude:-122.20zoom:14];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];// Add listeners for GMSNavigator and GMSRoadSnappedLocationProvider.[_mapView.navigatoraddListener:self];[_mapView.roadSnappedLocationProvideraddListener:self];// Set the time update threshold (seconds) and distance update threshold (meters)._mapView.navigator.timeUpdateThreshold=10;_mapView.navigator.distanceUpdateThreshold=100;// 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;// Request authorization to use location services.[_locationManagerrequestAlwaysAuthorization];}else{// Handle the case when the user rejects 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.navigator.guidanceActive=YES;_mapView.navigator.sendsBackgroundNotifications=YES;_mapView.cameraMode=GMSNavigationCameraModeFollowing;[_mapView.locationSimulatorsimulateLocationsAlongExistingRoute];}];[_mapView.roadSnappedLocationProviderstartUpdatingLocation];}#pragma mark - GMSNavigatorListener// Listener for continuous location updates.-(void)locationProvider:(GMSRoadSnappedLocationProvider*)locationProviderdidUpdateLocation:(CLLocation*)location{NSLog(@"Location: %@",location.description);}// Listener to handle speeding events.-(void)navigator:(GMSNavigator*)navigatordidUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit{NSLog(@"Speed is %f percent above the limit.",percentageAboveLimit);}// Listener to handle arrival events.-(void)navigator:(GMSNavigator*)navigatordidArriveAtWaypoint:(GMSNavigationWaypoint*)waypoint{NSLog(@"You have arrived at: %@",waypoint.title);[_mapView.navigatorcontinueToNextDestination];_mapView.navigator.guidanceActive=YES;}// Listener for route change events.-(void)navigatorDidChangeRoute:(GMSNavigator*)navigator{NSLog(@"The route has changed.");}// Listener for time to next destination.-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingTime:(NSTimeInterval)time{NSLog(@"Time to next destination: %f",time);}// Listener for distance to next destination.-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingDistance:(CLLocationDistance)distance{doublemiles=distance*0.00062137;NSLog(@"%@",[NSStringstringWithFormat:@"Distance to next destination: %.2f.",miles]);}// Listener for traffic updates for next destination-(void)navigator:(GMSNavigator*)navigatordidUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory{NSLog(@"Delay category to next destination: %ld.",delayCategory);}// Listener for suggested lighting mode changes.-(void)navigator:(GMSNavigator*)navigatordidChangeSuggestedLightingMode:(GMSNavigationLightingMode)lightingMode{NSLog(@"Suggested lighting mode has changed: %ld",(long)lightingMode);// Change to the suggested lighting mode._mapView.lightingMode=lightingMode;}#pragma mark - Programmatic UI elements// Add a button to the view.-(void)makeButton{// Start navigation.UIButton*navButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[navButtonaddTarget:selfaction:@selector(startNav)forControlEvents:UIControlEventTouchUpInside];[navButtonsetTitle:@"Navigate"forState:UIControlStateNormal];[navButtonsetBackgroundColor:[UIColorblueColor]];[navButtonsetAlpha:0.5];navButton.frame=CGRectMake(5.0,150.0,100.0,35.0);[_mapViewaddSubview:navButton];}@end
Khai báo sự tuân thủ các giao thức bắt buộc
Trước khi triển khai các phương thức điều hướng, bộ điều khiển khung hiển thị phải áp dụng các giao thức:
Sau khi áp dụng các giao thức điều hướng, hãy đặt trình nghe cho trình điều khiển khung hiển thị. Ví dụ: bạn có thể thêm mã sau vào phương thức viewDidLoad().
Bạn cần cập nhật vị trí để cho người dùng thấy tiến trình của họ trên bản đồ.
Đối tượng location hiển thị các thuộc tính sau:
Thuộc tính vị trí
Mô tả
độ cao
Độ cao hiện tại.
coordinate.latitude
Toạ độ theo vĩ độ hiện tại được gắn vào đường.
coordinate.longitude
Toạ độ kinh độ hiện tại được gắn vào đường.
khoá học
Góc phương vị hiện tại tính bằng độ.
tốc độ
Tốc độ hiện tại.
dấu thời gian
Ngày/giờ của chỉ số hiện tại.
Để nhận thông tin cập nhật liên tục về vị trí, hãy gọi mapView.roadSnappedLocationProvider.startUpdatingLocation và dùng GMSRoadSnappedLocationProviderListener để xử lý sự kiện didUpdateLocation.
Ví dụ sau đây minh hoạ cách gọi startUpdatingLocation:
Ứng dụng của bạn sử dụng sự kiện didArriveAtWaypoint để phát hiện thời điểm đạt đến một đích đến. Bạn có thể tiếp tục chỉ dẫn và chuyển sang điểm tham chiếu tiếp theo bằng cách gọi continueToNextDestination(), sau đó bật lại chỉ dẫn. Ứng dụng của bạn phải bật lại chỉ dẫn sau khi gọi continueToNextDestination().
Sau khi ứng dụng gọi continueToNextDestination, trình điều hướng sẽ không còn dữ liệu về đích đến trước đó nữa. Nếu muốn phân tích thông tin về một đoạn đường, bạn phải truy xuất thông tin này từ trình điều hướng trước khi gọi continueToNextDestination().
Ví dụ về mã sau đây cho thấy một phương thức xử lý sự kiện didArriveAtWaypoint:
Swift
funcnavigator(_navigator:GMSNavigator,didArriveAtwaypoint:GMSNavigationWaypoint){print("You have arrived at: \(waypoint.title)")mapView.navigator?.continueToNextDestination()mapView.navigator?.isGuidanceActive=true}
Để nhận thông báo mỗi khi tuyến đường thay đổi, hãy tạo một phương thức để xử lý sự kiện navigatorDidChangeRoute. Bạn có thể truy cập vào tuyến đường mới bằng cách sử dụng các thuộc tính routeLegs và currentRouteLeg của GMSNavigator.
Để nhận thông tin cập nhật liên tục về thời gian đến đích đến, hãy tạo một phương thức để xử lý sự kiện didUpdateRemainingTime. Tham số time cung cấp thời gian ước tính (tính bằng giây) cho đến khi đạt được đích đến tiếp theo.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingTimetime:TimeInterval){print("Time to next destination: \(time)")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingTime:(NSTimeInterval)time{NSLog(@"Time to nextdestination:%f", time); }
Để đặt mức thay đổi tối thiểu về thời gian ước tính đến điểm đến tiếp theo, hãy đặt thuộc tính timeUpdateThreshold trên GMSNavigator. Giá trị được chỉ định bằng giây. Nếu bạn không đặt thuộc tính này, các dịch vụ sẽ sử dụng giá trị mặc định là một giây.
Swift
navigator?.timeUpdateThreshold=10
Objective-C
navigator.timeUpdateThreshold=10;
Nhận thông tin cập nhật về khoảng cách đến điểm đến
Để nhận thông tin cập nhật liên tục về khoảng cách đến đích đến, hãy tạo một phương thức để xử lý sự kiện didUpdateRemainingDistance. Tham số distance cung cấp khoảng cách ước tính (tính bằng mét) đến đích đến tiếp theo.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingDistancedistance:CLLocationDistance){letmiles=distance*0.00062137print("Distance to nextdestination: \(miles) miles.")}
Để đặt mức thay đổi tối thiểu về khoảng cách ước tính đến đích đến tiếp theo, hãy đặt thuộc tính distanceUpdateThreshold trên GMSNavigator (giá trị được chỉ định bằng mét). Nếu bạn không đặt thuộc tính này, các dịch vụ sẽ sử dụng giá trị mặc định là 1 mét.
Swift
navigator?.distanceUpdateThreshold=100
Objective-C
navigator.distanceUpdateThreshold=100;
Nhận thông tin cập nhật về tình hình giao thông
Để nhận thông tin cập nhật liên tục về lưu lượng giao thông cho tuyến đường còn lại, hãy tạo một phương thức để xử lý sự kiện didUpdateDelayCategory. Lệnh gọi đến delayCategoryToNextDestination sẽ trả về GMSNavigationDelayCategory cung cấp giá trị từ 0 đến 3. Thông tin cập nhật về danh mục dựa trên vị trí hiện tại của người dùng ứng dụng. Nếu không có dữ liệu lưu lượng truy cập, GMSNavigationDelayCategory sẽ trả về 0. Các số từ 1 đến 3 cho biết lượng kinh nguyệt tăng dần từ ít đến nhiều.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdatedelayCategory:GMSNavigationDelayCategory){print("Traffic flow to next destination:\(delayCategory)")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory{NSLog(@"Traffic flow to next destination: %ld",(long)delayCategory);}
Thuộc tính GMSNavigationDelayCategory cho thấy các mức độ trễ sau:
Danh mục trì hoãn
Mô tả
GMSNavigationDelayCategoryNoData
0 – Không có sẵn, không có dữ liệu về lưu lượng truy cập hoặc :
tuyến đường.
GMSNavigationDelayCategoryHeavy
1 – Nặng.
GMSNavigationDelayCategoryMedium
2 – Trung bình.
GMSNavigationDelayCategoryLight
3 – Nhẹ.
Nhận thông tin cập nhật về tốc độ
Để nhận thông tin cập nhật khi một người lái xe vượt quá giới hạn tốc độ, hãy tạo một phương thức để xử lý sự kiện didUpdateSpeedingPercentage.
Swift
// Listener to handle speeding events. func navigator( _ navigator:GMSNavigator,didUpdateSpeedingPercentagepercentageAboveLimit:CGFloat){print("Speed is \(percentageAboveLimit) above the limit.")}
Objective-C
// Listener to handle speeding events. - (void)navigator:(GMSNavigator*)navigatordidUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit{NSLog(@"Speed is %f percent above the limit.",percentageAboveLimit);}
Thay đổi chế độ chiếu sáng được đề xuất
Để nhận thông tin cập nhật về các thay đổi ước tính về ánh sáng, hãy tạo một phương thức để xử lý sự kiện didChangeSuggestedLightingMode.
Swift
// Define a listener for suggested changes to lighting mode. func navigator(_navigator:GMSNavigator,didChangeSuggestedLightingModelightingMode:GMSNavigationLightingMode){print("Suggested lighting mode has changed:\(String(describing:lightingMode))")// Make the suggested change. mapView.lightingMode = lightingMode }
Objective-C
// Define a listener for suggested changes to lighting mode.-(void)navigator:(GMSNavigator*)navigatordidChangeSuggestedLightingMode:(GMSNavigationLightingMode)lightingMode{NSLog(@"Suggested lighting mode haschanged:%ld", (long)lightingMode);// Make the suggested change. _mapView.lightingMode = lightingMode; }
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\u003cp\u003eThe Navigation SDK for iOS allows you to respond to real-time navigation events like route changes, arrival, and location updates using listeners.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eGMSRoadSnappedLocationProviderListener\u003c/code\u003e and \u003ccode\u003eGMSNavigatorListener\u003c/code\u003e protocols handle events like location updates, speeding, and destination arrival.\u003c/p\u003e\n"],["\u003cp\u003eLocation updates can be managed for real-time tracking and background operation, impacting battery life.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eGMSNavigator\u003c/code\u003e provides methods to track and respond to waypoint arrivals, route changes, time and distance to destination, traffic flow, speeding percentage, and suggested lighting mode.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eGMSNavigatorDelegate\u003c/code\u003e and \u003ccode\u003eGMSRoadSnappedLocationProviderDelegate\u003c/code\u003e are deprecated and replaced by \u003ccode\u003eGMSRoadSnappedLocationProviderListener\u003c/code\u003e and \u003ccode\u003eGMSNavigatorListener\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,[]]