ניווט במסלול

תוכלו להיעזר במדריך הזה כדי להציג מסלול בתוך האפליקציה ליעד אחד באמצעות ה-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 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 rejection of notification authorization.
        if !granted || error != nil {
          print("Authorization to deliver notifications was rejected.")
        }
    }
  } else {
    // Handle rejection of terms and conditions.
  }
}

Objective-C

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

יצירת מסלול והתחלת ההנחיה

כדי לשרטט מסלול, מפעילים את השיטה 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;
                             }];
}

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

הגדרת מצב נסיעה

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

מגדירים את המאפיין 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 Finder כדי למצוא מזהי מקומות לשימוש ביעדי נתיבים. צריך להוסיף יעד מplaceID עם GMSNavigationWaypoint.

טקסט צף

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