مسیری را پیمایش کنید

این راهنما را دنبال کنید تا با استفاده از Navigation SDK برای iOS مسیری را در برنامه خود به سمت یک مقصد مشخص کنید.

نمای کلی

  1. همانطور که در بخش Setup your project توضیح داده شده است، Navigation SDK را در برنامه خود ادغام کنید.
  2. یک GMSMapView را پیکربندی کنید.
  3. از کاربر بخواهید که شرایط و ضوابط را بپذیرد و خدمات مکان و اعلان‌های پس‌زمینه را مجاز کند.
  4. یک آرایه حاوی یک یا چند مقصد ایجاد کنید.
  5. یک GMSNavigator برای کنترل ناوبری گام به گام تعریف کنید.

    • با استفاده از setDestinations مقصدها را اضافه کنید.
    • برای شروع ناوبری isGuidanceActive روی true تنظیم کنید.
    • از simulateLocationsAlongExistingRoute برای شبیه سازی پیشرفت وسیله نقلیه در طول مسیر، برای آزمایش، اشکال زدایی و نمایش برنامه خود استفاده کنید.

کد را ببینید

/*
 * 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)
  }

}
/*
 * 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

از کاربر بخواهید مجوزهای لازم را دریافت کند

قبل از استفاده از Navigation SDK، کاربر باید با شرایط و ضوابط موافقت کند و اجازه استفاده از خدمات مکان را که برای ناوبری لازم است، بدهد. اگر برنامه شما در پس‌زمینه اجرا شود، باید از کاربر بخواهد تا اعلان‌های هشدار راهنمایی را تأیید کند. این بخش نحوه نمایش درخواست های مجوز مورد نیاز را نشان می دهد.

مجوز خدمات مکان یابی

Navigation SDK از خدمات مکان استفاده می کند که به مجوز کاربر نیاز دارد. برای فعال کردن خدمات مکان و نمایش کادر گفتگوی مجوز، این مراحل را انجام دهید:

  1. کلید NSLocationAlwaysUsageDescription را به Info.plist اضافه کنید.
  2. برای ارزش، توضیح کوتاهی در مورد اینکه چرا برنامه شما به خدمات مکان نیاز دارد اضافه کنید. به عنوان مثال: "این برنامه برای استفاده از خدمات مکان برای پیمایش گام به گام به مجوز نیاز دارد."

  3. برای نمایش کادر گفتگوی مجوز، requestAlwaysAuthorization() نمونه مدیریت مکان را فراخوانی کنید.

self.locationManager.requestAlwaysAuthorization()

[_locationManager requestAlwaysAuthorization];

اعلان‌های هشدار را برای راهنمایی پس‌زمینه مجاز کنید

Navigation SDK برای ارائه اعلان‌های هشدار زمانی که برنامه در پس‌زمینه اجرا می‌شود به مجوز کاربر نیاز دارد. کد زیر را اضافه کنید تا از کاربر اجازه نمایش این اعلان ها را بخواهید:

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");
     }
   }];

شرایط و ضوابط را بپذیرید

از کد زیر برای نشان دادن گفتگوی شرایط و ضوابط استفاده کنید و وقتی کاربر شرایط را پذیرفت، ناوبری را فعال کنید. توجه داشته باشید که این مثال شامل کد خدمات مکان و اعلان‌های هشدار راهنمایی (نشان داده شده قبلی) است.

  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.
   }
 }];

یک مسیر ایجاد کنید و راهنمایی را شروع کنید

برای ترسیم یک مسیر، متد setDestinations() Navigator را با یک آرایه حاوی یک یا چند مقصد ( GMSNavigationWaypoint ) برای بازدید فراخوانی کنید. اگر محاسبه با موفقیت انجام شود، مسیر روی نقشه نشان داده می شود. برای شروع راهنمایی در طول مسیر، که از مقصد اول شروع می شود، isGuidanceActive در پاسخ به تماس روی true تنظیم کنید.

مثال زیر نشان می دهد:

  • ایجاد یک مسیر جدید با دو مقصد.
  • شروع راهنمایی
  • فعال کردن اعلان‌های راهنمایی پس‌زمینه
  • شبیه سازی سفر در طول مسیر (اختیاری).
  • تنظیم حالت دوربین روی "follow" (اختیاری).

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;
                             }];
}

برای آشنایی با شناسه‌های مکان، لطفاً به شناسه‌های مکان مراجعه کنید.

حالت سفر را تنظیم کنید

حالت سفر تعیین می‌کند که کدام مسیر واکشی می‌شود، و روشی که مسیر کاربر تعیین می‌شود. می توانید یکی از چهار حالت سفر را برای یک مسیر تنظیم کنید: رانندگی، دوچرخه سواری، پیاده روی و تاکسی. در حالت رانندگی و تاکسی، دوره کاربر بر اساس جهت حرکت است. در حالت دوچرخه سواری و پیاده روی مسیر با جهتی که دستگاه رو به رو است نشان داده می شود.

همانطور که در مثال زیر نشان داده شده است، ویژگی travelMode نمای نقشه را تنظیم کنید:

self.mapView.travelMode = .cycling

_mapView.travelMode = GMSNavigationTravelModeCycling;

جاده هایی را برای اجتناب تعیین کنید

برای اجتناب از بزرگراه‌ها و/یا جاده‌های عوارضی در طول یک مسیر، از ویژگی‌های avoidsHighways و avoidsTolls BOOL استفاده کنید.

self.mapView.navigator?.avoidsTolls = true

_mapView.navigator.avoidsTolls = YES;

مکان یاب

می توانید از مکان یاب برای یافتن شناسه های مکان برای استفاده در مقصدهای مسیر استفاده کنید. یک مقصد از یک placeID با GMSNavigationWaypoint اضافه کنید.

متن شناور

می‌توانید متن شناور را در هر جایی از برنامه خود اضافه کنید، تا زمانی که منبع Google پوشش داده نشود. Navigation SDK از اتصال متن به طول/طول جغرافیایی روی نقشه یا برچسب پشتیبانی نمی‌کند. برای اطلاعات بیشتر، پنجره اطلاعات را ببینید.