ניווט במסלול

במדריך הזה מוסבר איך להשתמש ב-Navigation SDK ל-iOS כדי לתכנן באפליקציה מסלול ליעד יחיד.

סקירה כללית

  1. משלבים את Navigation SDK באפליקציה, כמו שמתואר בקטע הגדרת הפרויקט.
  2. מגדירים GMSMapView.
  3. מבקשים מהמשתמש לאשר את התנאים וההגבלות, ולאשר את שירותי המיקום וההתראות ברקע.
  4. יוצרים מערך שמכיל יעד אחד או יותר.
  5. מגדירים GMSNavigator כדי לשלוט בניווט מפורט.

    • מוסיפים יעדים באמצעות setDestinations.
    • מגדירים את isGuidanceActive ל-true כדי להתחיל בניווט.
    • אפשר להשתמש ב-simulateLocationsAlongExistingRoute כדי לדמות את התקדמות הרכב לאורך המסלול, לצורך בדיקה, ניפוי באגים והדגמה של האפליקציה.

הצגת הקוד

הצגת בקשה למשתמש לקבלת ההרשאות הנדרשות

לפני שמשתמשים ב-Navigation SDK, המשתמשים צריכים להסכים לתנאים ולהגבלות ולאשר את השימוש בשירותי המיקום, שנדרשים לניווט. אם האפליקציה תפעל ברקע, היא גם צריכה לבקש מהמשתמשים הרשאה לקבל התראות על הדרכה. בקטע הזה מוסבר איך להציג את הנחיות ההרשאה הנדרשות.

אישור שירותי המיקום

‫Navigation SDK משתמש בשירותי מיקום, ולכן נדרשת הרשאת משתמש. כדי להפעיל את שירותי המיקום ולהציג את תיבת הדו-שיח של ההרשאה, מבצעים את השלבים הבאים:

  1. מוסיפים את המפתח NSLocationAlwaysUsageDescription אל Info.plist.
  2. במקום הערך, מוסיפים הסבר קצר למה האפליקציה דורשת שירותי מיקום. לדוגמה: "האפליקציה הזו צריכה הרשאה להשתמש בשירותי מיקום כדי לספק ניווט מנקודה לנקודה".

  3. כדי להציג את תיבת הדו-שיח של ההרשאה, קוראים ל-requestAlwaysAuthorization() של מופע מנהל המיקום.

Swift

self.locationManager.requestAlwaysAuthorization()

Objective-C

[_locationManager requestAlwaysAuthorization];

אישור לקבלת התראות על הנחיות ברקע

כדי ש-Navigation SDK יוכל לספק התראות כשהאפליקציה פועלת ברקע, הוא צריך הרשאה מהמשתמש. מוסיפים את הקוד הבא כדי לבקש מהמשתמש הרשאה להציג את ההתראות האלה:

Swift

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.")
    }
}

Objective-C

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

מאשרים את התנאים וההגבלות.

משתמשים בקוד הבא כדי להציג את תיבת הדו-שיח של התנאים וההגבלות, ומאפשרים ניווט כשהמשתמש מאשר את התנאים. שימו לב שהדוגמה הזו כוללת את הקוד של שירותי המיקום ושל ההתראות על הנחיות (כפי שמוצג למעלה).

Swift

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

Objective-C

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 בקריאה החוזרת.

בדוגמה הבאה מוצג:

  • יצירת מסלול חדש עם שני יעדים.
  • התחלת ההנחיה.
  • הפעלת התראות להדרכה ברקע.
  • הדמיית נסיעה לאורך המסלול (אופציונלי).
  • הגדרת מצב המצלמה ל'מעקב' (אופציונלי).

Swift

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

Objective-C

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

מידע נוסף על מזהי מקומות זמין במאמר מזהי מקומות.

הגדרת אמצעי תחבורה

מצב הנסיעה קובע איזה סוג מסלול יאוחזר, ואיך נקבע המסלול של המשתמש. אפשר להגדיר אחד מ-4 אמצעי תחבורה למסלול: נהיגה, רכיבה על אופניים, הליכה ומונית. במצב נהיגה ובמצב נסיעה במונית, המסלול של המשתמש מבוסס על כיוון הנסיעה. במצב רכיבה על אופניים ובמצב הליכה, המסלול מיוצג על ידי הכיוון שאליו המכשיר פונה (למעלה במכשיר במצב לרוחב).

מגדירים את המאפיין travelMode של תצוגת המפה, כמו בדוגמה הבאה:

Swift

self.mapView.travelMode = .cycling

Objective-C

_mapView.travelMode = GMSNavigationTravelModeCycling;

הגדרת כבישים להימנעות

כדי להימנע מכבישים מהירים או מכבישי אגרה לאורך מסלול, משתמשים במאפיינים avoidsHighways ו-avoidsTolls BOOL.

Swift

self.mapView.navigator?.avoidsTolls = true

Objective-C

_mapView.navigator.avoidsTolls = YES;

כלי למציאת מזהה מקום

אתם יכולים להשתמש בכלי לחיפוש מזהה מקום כדי למצוא מזהי מקומות לשימוש כיעדים במסלול. מוסיפים יעד מplaceID באמצעות GMSNavigationWaypoint.

טקסט צף

אפשר להוסיף טקסט צף בכל מקום באפליקציה, כל עוד הוא לא מסתיר את השיוך ל-Google. ‫Navigation SDK לא תומך בהצמדת הטקסט לקו רוחב או לקו אורך במפה, או לתווית. מידע נוסף זמין במאמר בנושא חלונות מידע.