האזנה לאירועי ניווט
קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
המדריך הזה יעזור לכם להפעיל באפליקציה את האפשרות להאזין למגוון אירועים ולהגיב להם. האירועים האלה משתנים כשהמשתמש עובר לאורך מסלול. המדריך הזה לא כולל הגדרה של מסלול, אלא רק תגובה לאירועים לאורך מסלול.
סקירה כללית
ערכת Navigation SDK ל-iOS מספקת לכם מאזינים שמשויכים למיקום של המשתמש ולתנאים לאורך המסלול, וגם נתונים חשובים על זמן ומרחק. בבקר התצוגה של המפה, האפליקציה צריכה להשתמש בפרוטוקולים של מאזינים אלה:
GMSRoadSnappedLocationProviderListener
ו-
GMSNavigatorListener.
ברשימה הזו מוצגות שיטות ה-listener שזמינות לאירועי ניווט:
הצגה או הסתרה של קוד Swift
של רכיב event listener.
/**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//Settheinitiallightingmodeonlaunchorsetup.mapView.lightingMode=mapView.navigator?.suggestedLightingMode??.normal//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)}}
הצגה או הסתרה של קוד Objective-C לרכיב event listener.
/* * 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;// Set the initial lighting mode on launch or setup._mapView.lightingMode=_mapView.navigator.suggestedLightingMode;// 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
הצהרה על עמידה בדרישות הפרוטוקולים
לפני שמטמיעים את שיטות הניווט, בקר התצוגה צריך לאמץ את הפרוטוקולים:
כדי להציג את ההתקדמות של המשתמש במפה, צריך לעדכן את המיקום.
מופע location חושף את המאפיינים הבאים:
מאפיין מיקום
תיאור
גובה
הגובה הנוכחי.
coordinate.latitude
קו הרוחב הנוכחי של הנקודה שמוצמדת לכביש.
coordinate.longitude
קואורדינטת קו האורך הנוכחית אחרי הצמדה לכביש.
קורס
הכיוון הנוכחי במעלות.
מהירות
המהירות הנוכחית.
חותמת זמן
התאריך והשעה של הקריאה הנוכחית.
כדי לקבל עדכוני מיקום רציפים, קוראים ל-mapView.roadSnappedLocationProvider.startUpdatingLocation ומשתמשים ב-GMSRoadSnappedLocationProviderListener כדי לטפל באירוע didUpdateLocation.
האפליקציה משתמשת באירוע didArriveAtWaypoint כדי לזהות מתי מגיעים ליעד. כדי להמשיך בהנחיות ולעבור לנקודת הציון הבאה, צריך להתקשר אל continueToNextDestinationWithCompletion() ולהפעיל מחדש את ההנחיות. האפליקציה צריכה להפעיל מחדש את ההנחיות אחרי ההתקשרות אל continueToNextDestinationWithCompletion().
אחרי שהאפליקציה קוראת ל-continueToNextDestinationWithCompletion, אין יותר נתונים על היעד הקודם. אם רוצים לנתח מידע על קטע מסלול, צריך לאחזר אותו מהניווט לפני שמבצעים קריאה ל-continueToNextDestinationWithCompletion().
בדוגמת הקוד הבאה מוצגת שיטה לטיפול באירוע didArriveAtWaypoint:
Swift
funcnavigator(_navigator:GMSNavigator,didArriveAtwaypoint:GMSNavigationWaypoint){print("You have arrived at: \(waypoint.title)")mapView.navigator?.continueToNextDestinationWithCompletion{_,_in}mapView.navigator?.isGuidanceActive=true}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidArriveAtWaypoint:(GMSNavigationWaypoint*)waypoint{NSLog(@"You have arrived at: %@",waypoint.title);[_mapView.navigatorcontinueToNextDestinationWithCompletion:^(GMSNavigationWaypoint*waypoint,GMSRouteStatusstatus){}];_mapView.navigator.guidanceActive=YES;}
קבלת עדכונים על שינויים במסלול
כדי לקבל התראה בכל פעם שהמסלול משתנה, צריך ליצור שיטה לטיפול באירוע navigatorDidChangeRoute. אפשר לגשת למסלול החדש באמצעות המאפיינים routeLegs ו-currentRouteLeg של GMSNavigator.
Swift
funcnavigatorDidChangeRoute(_navigator:GMSNavigator){print("The route has changed.")}
Objective-C
-(void)navigatorDidChangeRoute:(GMSNavigator*)navigator{NSLog(@"The route has changed.");}
קבלת עדכונים לגבי זמן ההגעה ליעד
כדי לקבל עדכונים שוטפים לגבי הזמן שייקח להגיע ליעד, צריך ליצור שיטה לטיפול באירוע didUpdateRemainingTime. הפרמטר time מספק את הזמן המשוער בשניות עד שמגיעים ליעד הבא.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingTimetime:TimeInterval){print("Time to next destination: \(time)")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingTime:(NSTimeInterval)time{NSLog(@"Time to next destination: %f",time);}
כדי להגדיר את השינוי המינימלי בזמן המשוער להגעה ליעד הבא, מגדירים את המאפיין timeUpdateThreshold ב-GMSNavigator. הערך מצוין בשניות. אם לא מגדירים את המאפיין הזה, השירותים משתמשים בערך ברירת המחדל של שנייה אחת.
Swift
navigator?.timeUpdateThreshold=10
Objective-C
navigator.timeUpdateThreshold=10;
קבלת עדכונים לגבי המרחק ליעד
כדי לקבל עדכונים שוטפים לגבי המרחק ליעד, צריך ליצור שיטה לטיפול באירוע didUpdateRemainingDistance. הפרמטר distance מספק את המרחק המשוער, במטרים, ליעד הבא.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingDistancedistance:CLLocationDistance){letmiles=distance*0.00062137print("Distance to next destination: \(miles) miles.")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingDistance:(CLLocationDistance)distance{doublemiles=distance*0.00062137;NSLog(@"%@",[NSStringstringWithFormat:@"Distance to next destination: %.2f.",miles]);}
כדי להגדיר את השינוי המינימלי במרחק המשוער ליעד הבא, מגדירים את המאפיין distanceUpdateThreshold ב-GMSNavigator (הערך מצוין במטרים). אם המאפיין הזה לא מוגדר, השירותים משתמשים בערך ברירת המחדל של מטר אחד.
Swift
navigator?.distanceUpdateThreshold=100
Objective-C
navigator.distanceUpdateThreshold=100;
קבלת עדכונים על מצב התנועה
כדי לקבל עדכונים שוטפים על זרימת התנועה במסלול שנותר, צריך ליצור שיטה לטיפול באירוע didUpdateDelayCategory. קריאה לפונקציה delayCategoryToNextDestination מחזירה את הערך GMSNavigationDelayCategory, שהוא מספר בין 0 ל-3. העדכונים לקטגוריה מבוססים על המיקום הנוכחי של משתמש האפליקציה. אם נתוני התנועה לא זמינים,
GMSNavigationDelayCategory מחזירה 0. המספרים 1-3 מציינים זרימה גדלה, מקלה לכבדה.
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);}
המאפיין GMSNavigationDelayCategory חושף את רמות העיכוב הבאות:
קטגוריית העיכוב
תיאור
GMSNavigationDelayCategoryNoData
0 – לא זמין, אין נתונים לגבי תנועת הגולשים או :
המסלול.
GMSNavigationDelayCategoryHeavy
1 – חזק.
GMSNavigationDelayCategoryMedium
2 – בינוני.
GMSNavigationDelayCategoryLight
3 – אור.
קבלת עדכונים על מהירות
כדי לקבל עדכונים כשהנהג או הנהגת חורגים מהמהירות המותרת, צריך ליצור שיטה לטיפול באירוע didUpdateSpeedingPercentage.
Swift
// Listener to handle speeding events.funcnavigator(_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);}
בדוגמה הבאה אפשר לראות איך מגדירים את מצב התאורה הראשוני ומאזינים לשינויים המוצעים במצב התאורה:
Swift
// Set the initial lighting mode on launch or setup.mapView.lightingMode=mapView.navigator?.suggestedLightingMode??.normal// Define a listener for suggested changes to lighting mode.funcnavigator(_navigator:GMSNavigator,didChangeSuggestedLightingModelightingMode:GMSNavigationLightingMode){print("Suggested lighting mode has changed: \(String(describing:lightingMode))")// Make the suggested change.mapView.lightingMode=lightingMode}
Objective-C
// Set the initial lighting mode on launch or setup._mapView.lightingMode=_mapView.navigator.suggestedLightingMode;// Define a listener for suggested changes to lighting mode.-(void)navigator:(GMSNavigator*)navigatordidChangeSuggestedLightingMode:(GMSNavigationLightingMode)lightingMode{NSLog(@"Suggested lighting mode has changed: %ld",(long)lightingMode);// Make the suggested change._mapView.lightingMode=lightingMode;}
[[["התוכן קל להבנה","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"]],["עדכון אחרון: 2026-09-29 (שעון UTC)."],[],[]]