iOS için Navigasyon SDK'sını kullanarak uygulamanızda tek bir hedefe giden bir rota çizmek için bu kılavuzu uygulayın.
Genel Bakış
- Navigasyon SDK'sını Projenizi ayarlama bölümünde açıklandığı şekilde uygulamanıza entegre edin.
GMSMapView
yapılandırın.- Kullanıcıdan hükümler ve koşulları kabul etmesini, konum hizmetlerini ve arka plan bildirimlerini yetkilendirmesini isteyin.
- Bir veya daha fazla hedef içeren bir dizi oluşturun.
Adım adım navigasyonu kontrol etmek için bir
GMSNavigator
tanımlayın.setDestinations
simgesini kullanarak hedef ekleyin.- Navigasyonu başlatmak için
isGuidanceActive
simgesinitrue
olarak ayarlayın. - Aracın rota üzerindeki ilerlemesini simüle etmek, uygulamanızı test etmek, hata ayıklamak ve uygulamanızı göstermek için
simulateLocationsAlongExistingRoute
simgesini kullanın.
Kodu görme
Gezinme görünümü denetleyicisi için Swift kodunu göster/gizle
/* * 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) } }
Gezinme görünümü denetleyicisinin Objective-C kodunu gösterin/gizleyin.
/* * 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
Kullanıcıdan gerekli yetkilendirmeleri iste
Kullanıcı, Navigasyon SDK'sını kullanmadan önce hükümler ve koşulları kabul etmeli ve navigasyon için gerekli olan konum hizmetlerinin kullanımını yetkilendirmelidir. Uygulamanız arka planda çalışacaksa kullanıcıdan rehberlik uyarısı bildirimlerini yetkilendirmesini de istemesi gerekir. Bu bölümde, gerekli yetkilendirme istemlerinin nasıl gösterileceği gösterilmektedir.
Konum hizmetlerini yetkilendirme
Navigasyon SDK'sı, kullanıcı yetkilendirmesi gerektiren konum hizmetlerini kullanır. Konum hizmetlerini etkinleştirmek ve yetkilendirme iletişim kutusunu görüntülemek için aşağıdaki adımları uygulayın:
NSLocationAlwaysUsageDescription
anahtarınıInfo.plist
'a ekleyin.Değer için, uygulamanızın neden konum hizmetlerine ihtiyaç duyduğuna dair kısa bir açıklama ekleyin. Örneğin: "Bu uygulamanın, adım adım yol tarifi için konum hizmetlerini kullanması gerekiyor."
Yetkilendirme iletişim kutusunu görüntülemek için konum yöneticisi örneğinin
requestAlwaysAuthorization()
işlevini çağırın.
self.locationManager.requestAlwaysAuthorization()
[_locationManager requestAlwaysAuthorization];
Arka planda rehberlik için uyarı bildirimlerine yetki verme
Navigasyon SDK'sının, uygulama arka planda çalışırken uyarı bildirimleri göndermesi için kullanıcı izni gerekir. Kullanıcıdan bu bildirimleri gösterme izni istemek için aşağıdaki kodu ekleyin:
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");
}
}];
Hükümler ve koşulları kabul etme
Şartlar ve koşullar iletişim kutusunu göstermek ve kullanıcı şartları kabul ettiğinde gezinmeyi etkinleştirmek için aşağıdaki kodu kullanın. Bu örnekte, konum hizmetleri ve yol tarifi uyarısı bildirimlerinin (daha önce gösterilmiştir) kodunun yer aldığını unutmayın.
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.
}
}];
Rota oluşturma ve rehberliği başlatma
Rota oluşturmak için Gezgin'in setDestinations()
yöntemini, ziyaret edilecek bir veya daha fazla hedef (GMSNavigationWaypoint
) içeren bir dizi ile çağırın. Hesaplama başarılı olursa rota haritada gösterilir. İlk hedeften başlayarak rota boyunca rehberliği başlatmak için geri çağırma işlevinde isGuidanceActive
değerini true
olarak ayarlayın.
Aşağıdaki örnekte şunlar gösterilmektedir:
- İki hedef içeren yeni bir rota oluşturma.
- Başlangıç kılavuzu.
- Arka planda rehberlik bildirimlerini etkinleştirme.
- Rota üzerinde seyahat simülasyonu (isteğe bağlı).
- Kamera modunu "takip et" olarak ayarlama (isteğe bağlı).
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;
}];
}
Mekan kimlikleri hakkında bilgi edinmek için lütfen Mekan kimlikleri başlıklı makaleyi inceleyin.
Ulaşım şeklini ayarla
Seyahat modu, hangi rota türünün getirileceğini ve kullanıcının rotasının nasıl belirleneceğini belirler. Bir rota için dört ulaşım şeklinden birini ayarlayabilirsiniz: araba, bisiklet, yürüyüş ve taksi. Sürüş ve taksi modunda kullanıcının rotası seyahat yönüne göre belirlenir. Bisiklet ve yürüyüş modunda ise rota, cihazın baktığı yönle gösterilir.
Aşağıdaki örnekte gösterildiği gibi harita görünümünün travelMode
özelliğini ayarlayın:
self.mapView.travelMode = .cycling
_mapView.travelMode = GMSNavigationTravelModeCycling;
Kaçınılacak yolları ayarlama
Bir rotadaki otoyolları ve/veya ücretli yolları kullanmaktan kaçınmak için avoidsHighways
ve avoidsTolls
BOOL
mülklerini kullanın.
self.mapView.navigator?.avoidsTolls = true
_mapView.navigator.avoidsTolls = YES;
PlaceID bulucu
Rota hedefleri için kullanılacak yer kimliklerini bulmak üzere PlaceID Finder'ı kullanabilirsiniz. GMSNavigationWaypoint
ile placeID
'ten hedef ekleyin.
Yüzen metin
Google ilişkilendirmesi kapsam dışında olduğu sürece uygulamanızın herhangi bir yerine yüzen metin ekleyebilirsiniz. Navigasyon SDK'sı, metnin haritada bir enlem/boylam veya etikete sabitlenmesini desteklemez. Daha fazla bilgi için Bilgi pencereleri bölümüne bakın.