از این راهنما برای فعال کردن برنامه خود برای گوش دادن و پاسخ به رویدادهای مختلفی استفاده کنید که با حرکت کاربر در مسیر تغییر می کند. این راهنما تعریف مسیر را پوشش نمی دهد، فقط به رویدادهای یک مسیر پاسخ می دهد.
نمای کلی
Navigation SDK برای iOS شنوندگان مرتبط با موقعیت کاربر و شرایط در طول مسیر و داده های مهم زمان و مسافت را در اختیار شما قرار می دهد. در کنترلکننده نمای نقشه، برنامه شما باید پروتکلهایی را برای این شنوندگان بپذیرد: GMSRoadSnappedLocationProviderListener
و GMSNavigatorListener
.
این لیست روش های شنونده موجود برای رویدادهای ناوبری را نشان می دهد:
-
GMSNavigatorListener.didArriveAtWaypoint
، با رسیدن به مقصد فعال می شود. -
GMSNavigatorListener.navigatorDidChangeRoute
، با تغییر مسیر فعال می شود. -
GMSNavigatorListener.didUpdateRemainingTime
، به طور مکرر با تغییر زمان رسیدن به مقصد بعدی، در حالی که راهنما فعال است، فراخوانی می شود. -
GMSNavigatorListener.didUpdateRemainingDistance
، با تغییر فاصله تا مقصد بعدی، در حالی که راهنما فعال است، مکرراً فراخوانی می شود. -
GMSNavigatorListener.didUpdateDelayCategory
، زمانی که دسته تاخیر به مقصد بعدی تغییر می کند، در حالی که راهنما فعال است، فراخوانی می شود. -
GMSNavigatorListener.didChangeSuggestedLightingMode
، زمانی که شرایط نوری تخمینی بهروزرسانی میشود، فعال میشود. به عنوان مثال، هنگامی که شب در مکان فعلی کاربر فرا می رسد، نور تغییر می کند. -
GMSNavigatorListener.didUpdateSpeedingPercentage
، هنگامی که راننده از حد مجاز سرعت فراتر می رود فعال می شود. -
GMSRoadSnappedLocationProviderListener.didUpdateLocation
، با تغییر مکان کاربر به طور مکرر فراخوانی می شود.
کد را ببینید
نمایش/پنهان کردن کد سوئیفت برای شنونده رویداد.
/* * 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 GoogleNavigation import UIKit class ViewController: UIViewController, GMSNavigatorListener, GMSRoadSnappedLocationProviderListener { var mapView: GMSMapView! var locationManager: CLLocationManager! override func loadView() { locationManager = CLLocationManager() let camera = GMSCameraPosition.camera(withLatitude: 47.67, longitude: -122.20, zoom: 14) mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) // Add listeners for GMSNavigator and GMSRoadSnappedLocationProvider. mapView.navigator?.add(self) mapView.roadSnappedLocationProvider?.add(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. 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 // 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("Authorization to deliver notifications was rejected.") } } } else { // Handle the case when the user rejects the terms and conditions. } } view = mapView makeButton() } // Create a route and start guidance. @objc 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.cameraMode = .following self.mapView.locationSimulator?.simulateLocationsAlongExistingRoute() } mapView.roadSnappedLocationProvider?.startUpdatingLocation() } // Listener to handle continuous location updates. func locationProvider( _ locationProvider: GMSRoadSnappedLocationProvider, didUpdate location: CLLocation ) { print("Location: \(location.description)") } // Listener to handle speeding events. func navigator( _ navigator: GMSNavigator, didUpdateSpeedingPercentage percentageAboveLimit: CGFloat ) { print("Speed is \(percentageAboveLimit) above the limit.") } // Listener to handle arrival events. func navigator(_ navigator: GMSNavigator, didArriveAt waypoint: GMSNavigationWaypoint) { print("You have arrived at: \(waypoint.title)") mapView.navigator?.continueToNextDestination() mapView.navigator?.isGuidanceActive = true } // Listener for route change events. func navigatorDidChangeRoute(_ navigator: GMSNavigator) { print("The route has changed.") } // Listener for time to next destination. func navigator(_ navigator: GMSNavigator, didUpdateRemainingTime time: TimeInterval) { print("Time to next destination: \(time)") } // Delegate for distance to next destination. func navigator( _ navigator: GMSNavigator, didUpdateRemainingDistance distance: CLLocationDistance ) { let miles = distance * 0.00062137 print("Distance to next destination: \(miles) miles.") } // Delegate for traffic updates to next destination func navigator( _ navigator: GMSNavigator, didUpdate delayCategory: GMSNavigationDelayCategory ) { print("Delay category to next destination: \(String(describing: delayCategory)).") } // Delegate for suggested lighting mode changes. func navigator( _ navigator: GMSNavigator, didChangeSuggestedLightingMode lightingMode: GMSNavigationLightingMode ) { print("Suggested lighting mode has changed: \(String(describing: lightingMode))") // Change to the suggested lighting mode. mapView.lightingMode = lightingMode } // Add a button to the view. func makeButton() { // 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 برای شنونده رویداد.
/* * 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" @import GoogleNavigation; @interface ViewController () <GMSNavigatorListener, GMSRoadSnappedLocationProviderListener> @end @implementation ViewController { GMSMapView *_mapView; CLLocationManager *_locationManager; } - (void)loadView { _locationManager = [[CLLocationManager alloc] init]; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:47.67 longitude:-122.20 zoom:14]; _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera]; // Add listeners for GMSNavigator and GMSRoadSnappedLocationProvider. [_mapView.navigator addListener:self]; [_mapView.roadSnappedLocationProvider addListener: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."; [GMSNavigationServices showTermsAndConditionsDialogIfNeededWithCompanyName:companyName callback:^(BOOL termsAccepted) { if (termsAccepted) { // Enable navigation if the user accepts the terms. _mapView.navigationEnabled = YES; // Request authorization to use location services. [_locationManager requestAlwaysAuthorization]; } else { // Handle the case when the user rejects 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.navigator.guidanceActive = YES; _mapView.navigator.sendsBackgroundNotifications = YES; _mapView.cameraMode = GMSNavigationCameraModeFollowing; [_mapView.locationSimulator simulateLocationsAlongExistingRoute]; }]; [_mapView.roadSnappedLocationProvider startUpdatingLocation]; } #pragma mark - GMSNavigatorListener // Listener for continuous location updates. - (void)locationProvider:(GMSRoadSnappedLocationProvider *)locationProvider didUpdateLocation:(CLLocation *)location { NSLog(@"Location: %@", location.description); } // Listener to handle speeding events. - (void)navigator:(GMSNavigator *)navigator didUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit { NSLog(@"Speed is %f percent above the limit.", percentageAboveLimit); } // Listener to handle arrival events. - (void)navigator:(GMSNavigator *)navigator didArriveAtWaypoint:(GMSNavigationWaypoint *)waypoint { NSLog(@"You have arrived at: %@", waypoint.title); [_mapView.navigator continueToNextDestination]; _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 *)navigator didUpdateRemainingTime:(NSTimeInterval)time { NSLog(@"Time to next destination: %f", time); } // Listener for distance to next destination. - (void)navigator:(GMSNavigator *)navigator didUpdateRemainingDistance:(CLLocationDistance)distance { double miles = distance * 0.00062137; NSLog(@"%@", [NSString stringWithFormat:@"Distance to next destination: %.2f.", miles]); } // Listener for traffic updates for next destination - (void)navigator:(GMSNavigator *)navigator didUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory { NSLog(@"Delay category to next destination: %ld.", delayCategory); } // Listener for suggested lighting mode changes. -(void)navigator:(GMSNavigator *)navigator didChangeSuggestedLightingMode:(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 = [UIButton buttonWithType:UIButtonTypeCustom]; [navButton addTarget:self action:@selector(startNav) forControlEvents:UIControlEventTouchUpInside]; [navButton setTitle:@"Navigate" forState:UIControlStateNormal]; [navButton setBackgroundColor:[UIColor blueColor]]; [navButton setAlpha:0.5]; navButton.frame = CGRectMake(5.0, 150.0, 100.0, 35.0); [_mapView addSubview:navButton]; } @end
اعلام انطباق با پروتکل های مورد نیاز
قبل از اجرای روشهای ناوبری، کنترلکننده view باید پروتکلهای زیر را اتخاذ کند:
class ViewController: UIViewController, GMSNavigatorListener,
GMSRoadSnappedLocationProviderListener {
@interface ViewController () <GMSNavigatorListener,
GMSRoadSnappedLocationProviderListener>
@end
پس از اتخاذ پروتکل های ناوبری، شنوندگان را روی کنترلر View قرار دهید. برای مثال می توانید کد زیر را به متد viewDidLoad()
اضافه کنید.
mapView.navigator?.add(self) mapView.roadSnappedLocationProvider?.add(self)
[_mapView.navigator addListener:self]; [_mapView.roadSnappedLocationProvider
addListener:self];
دریافت یا توقف بهروزرسانیهای مکان
بهروزرسانیهای مکان برای نشان دادن پیشرفت کاربر روی نقشه مورد نیاز است.
نمونه location
ویژگی های زیر را نشان می دهد:
ملک موقعیت مکانی | توضیحات |
---|---|
ارتفاع | ارتفاع فعلی. |
مختصات. عرض جغرافیایی | مختصات عرض جغرافیایی کنونی شکسته شده در جاده. |
مختصات.طول جغرافیایی | مختصات طول جغرافیایی کنونی شکسته شده. |
دوره | بلبرینگ جریان بر حسب درجه |
سرعت | سرعت فعلی. |
مهر زمانی | تاریخ/زمان خواندن فعلی |
برای دریافت بهروزرسانیهای مستمر مکان، با mapView.roadSnappedLocationProvider.startUpdatingLocation
تماس بگیرید و از GMSRoadSnappedLocationProviderListener
برای مدیریت رویداد didUpdateLocation
استفاده کنید.
مثال زیر فراخوانی startUpdatingLocation
را نشان می دهد:
mapView.roadSnappedLocationProvider.startUpdatingLocation()
[_mapView.roadSnappedLocationProvider startUpdatingLocation];
کد زیر یک GMSRoadSnappedLocationProviderListener
ایجاد می کند که رویداد didUpdateLocation
مدیریت می کند.
func locationProvider(_ locationProvider: GMSRoadSnappedLocationProvider,
didUpdate location: CLLocation) { print("Location: \(location.description)") }
- (void)locationProvider:(GMSRoadSnappedLocationProvider *)locationProvider
didUpdateLocation:(CLLocation *)location { NSLog(@"Location: %@",
location.description); }
برای دریافت بهروزرسانیهای مکان زمانی که برنامه در پسزمینه است، allowsBackgroundLocationUpdates
روی true تنظیم کنید:
mapView.roadSnappedLocationProvider.allowsBackgroundLocationUpdates = true
_mapView.roadSnappedLocationProvider.allowsBackgroundLocationUpdates = YES;
تشخیص رویدادهای ورود
برنامه شما از رویداد didArriveAtWaypoint
برای تشخیص اینکه چه زمانی به مقصد رسیده است استفاده می کند. می توانید با فراخوانی continueToNextDestination()
و سپس فعال کردن مجدد راهنما، راهنمایی را از سر بگیرید و به ایستگاه بعدی بروید. برنامه شما باید پس از فراخوانی continueToNextDestination()
راهنما را دوباره فعال کند.
پس از تماس برنامه continueToNextDestination
، ناوبر دیگر اطلاعاتی درباره مقصد قبلی ندارد. اگر میخواهید اطلاعات مربوط به یک مسیر را تجزیه و تحلیل کنید، باید قبل از فراخوانی continueToNextDestination()
آن را از ناوبر بازیابی کنید.
مثال کد زیر روشی را برای مدیریت رویداد didArriveAtWaypoint
نشان می دهد:
func navigator(_ navigator: GMSNavigator, didArriveAt waypoint:
GMSNavigationWaypoint) { print("You have arrived at: \(waypoint.title)")
mapView.navigator?.continueToNextDestination()
mapView.navigator?.isGuidanceActive = true }
- (void)navigator:(GMSNavigator *)navigator
didArriveAtWaypoint:(GMSNavigationWaypoint *)waypoint { NSLog(@"You have
arrived at: %@", waypoint.title); [_mapView.navigator
continueToNextDestination]; _mapView.navigator.guidanceActive = YES; }
دریافت بهروزرسانیهای تغییر مسیر
برای دریافت اعلان هر زمان که مسیر تغییر کرد، روشی برای مدیریت رویداد navigatorDidChangeRoute
ایجاد کنید. با استفاده از ویژگی routeLegs
و currentRouteLeg
GMSNavigator
می توانید به مسیر جدید دسترسی پیدا کنید.
func navigatorDidChangeRoute(_ navigator: GMSNavigator) { print("The route has
changed.") }
- (void)navigatorDidChangeRoute:(GMSNavigator *)navigator { NSLog(@"The route
has changed."); }
دریافت زمان بهروزرسانیهای مقصد
برای دریافت زمان پیوسته بهروزرسانیهای مقصد، روشی برای مدیریت رویداد didUpdateRemainingTime
ایجاد کنید. پارامتر time
زمان تخمینی را در ثانیه تا رسیدن به مقصد بعدی ارائه می دهد.
func navigator(_ navigator: GMSNavigator, didUpdateRemainingTime time:
TimeInterval) { print("Time to next destination: \(time)") }
- (void)navigator:(GMSNavigator *)navigator
didUpdateRemainingTime:(NSTimeInterval)time { NSLog(@"Time to next
destination: %f", time); }
برای تنظیم حداقل تغییر در زمان تخمینی به مقصد بعدی، ویژگی timeUpdateThreshold
را در GMSNavigator
تنظیم کنید. مقدار در ثانیه مشخص می شود. اگر این ویژگی تنظیم نشده باشد، سرویس ها از مقدار پیش فرض یک ثانیه استفاده می کنند.
navigator?.timeUpdateThreshold = 10
navigator.timeUpdateThreshold = 10;
دریافت به روز رسانی فاصله تا مقصد
برای دریافت بهروزرسانیهای مسافت مداوم تا مقصد، روشی برای مدیریت رویداد didUpdateRemainingDistance
ایجاد کنید. پارامتر distance
، فاصله تخمین زده شده را تا مقصد بعدی بر حسب متر ارائه می کند.
func navigator(_ navigator: GMSNavigator, didUpdateRemainingDistance distance:
CLLocationDistance) { let miles = distance * 0.00062137 print("Distance to next
destination: \(miles) miles.") }
- (void)navigator:(GMSNavigator *)navigator
didUpdateRemainingDistance:(CLLocationDistance)distance { double miles =
distance * 0.00062137; NSLog(@"%@", [NSString stringWithFormat:@"Distance to
next destination: %.2f.", miles]); }
برای تنظیم حداقل تغییر در فاصله تخمینی تا مقصد بعدی، ویژگی distanceUpdateThreshold
را در GMSNavigator
تنظیم کنید (مقدار بر حسب متر مشخص شده است). اگر این ویژگی تنظیم نشده باشد، سرویس ها از مقدار پیش فرض یک متر استفاده می کنند.
navigator?.distanceUpdateThreshold = 100
navigator.distanceUpdateThreshold = 100;
دریافت به روز رسانی ترافیک
برای دریافت بهروزرسانیهای مداوم جریان ترافیک برای مسیر باقیمانده، روشی برای مدیریت رویداد didUpdateDelayCategory
ایجاد کنید. تماس با delayCategoryToNextDestination
GMSNavigationDelayCategory
را برمیگرداند که مقدار 0 تا 3 را ارائه میکند. بهروزرسانیهای دسته براساس موقعیت فعلی کاربر برنامه است. اگر داده های ترافیک در دسترس نباشد، GMSNavigationDelayCategory
0 را برمی گرداند. اعداد 1-3 نشان دهنده افزایش جریان از سبک به سنگین است.
func navigator(_ navigator: GMSNavigator, didUpdate delayCategory:
GMSNavigationDelayCategory) { print("Traffic flow to next destination:
\(delayCategory)") }
- (void)navigator:(GMSNavigator *)navigator
didUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory {
NSLog(@"Traffic flow to next destination: %ld", (long)delayCategory); }
ویژگی GMSNavigationDelayCategory
سطوح تاخیر زیر را نشان می دهد:
دسته تاخیر | توضیحات |
---|---|
GMSNavigationDelayCategoryNoData | 0 - در دسترس نیست، هیچ داده ای برای ترافیک یا: |
مسیر | |
GMSNavigationDelayCategoryHeavy | 1 - سنگین |
GMSNavigationDelayCategoryMedium | 2 - متوسط |
GMSNavigationDelayCategoryLight | 3 - نور. |
دریافت به روز رسانی سرعت
برای دریافت بهروزرسانیها وقتی راننده از حد مجاز فراتر میرود، روشی برای مدیریت رویداد didUpdateSpeedingPercentage
ایجاد کنید.
// Listener to handle speeding events. func navigator( _ navigator:
GMSNavigator, didUpdateSpeedingPercentage percentageAboveLimit: CGFloat ) {
print("Speed is \(percentageAboveLimit) above the limit.") }
// Listener to handle speeding events. - (void)navigator:(GMSNavigator
*)navigator didUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit {
NSLog(@"Speed is %f percent above the limit.", percentageAboveLimit); }
تغییر حالت نورپردازی پیشنهادی
برای دریافت بهروزرسانیها برای تغییرات تخمینی نور، روشی برای مدیریت رویداد didChangeSuggestedLightingMode
ایجاد کنید.
// Define a listener for suggested changes to lighting mode. func navigator(_
navigator: GMSNavigator, didChangeSuggestedLightingMode lightingMode:
GMSNavigationLightingMode) { print("Suggested lighting mode has changed:
\(String(describing: lightingMode))")
// Make the suggested change. mapView.lightingMode = lightingMode }
// Define a listener for suggested changes to lighting mode.
-(void)navigator:(GMSNavigator *)navigator didChangeSuggestedLightingMode:
(GMSNavigationLightingMode)lightingMode { NSLog(@"Suggested lighting mode has
changed: %ld", (long)lightingMode);
// Make the suggested change. _mapView.lightingMode = lightingMode; }