Ikuti panduan ini untuk memetakan rute dalam aplikasi Anda ke satu tujuan, menggunakan Navigation SDK untuk iOS.
Ringkasan
- Integrasikan Navigation SDK ke dalam aplikasi Anda, seperti yang dijelaskan di bagian Menyiapkan project.
- Konfigurasikan
GMSMapView
. - Minta pengguna untuk menyetujui persyaratan dan ketentuan, serta mengizinkan layanan lokasi dan notifikasi latar belakang.
- Buat array yang berisi satu atau beberapa tujuan.
Tentukan
GMSNavigator
untuk mengontrol navigasi belokan demi belokan.- Tambahkan tujuan menggunakan
setDestinations
. - Tetapkan
isGuidanceActive
ketrue
untuk memulai navigasi. - Gunakan
simulateLocationsAlongExistingRoute
untuk menyimulasikan progres kendaraan di sepanjang rute, untuk pengujian, proses debug, dan mendemonstrasikan aplikasi Anda.
- Tambahkan tujuan menggunakan
Melihat kode
Tampilkan/Sembunyikan kode Swift untuk pengontrol tampilan navigasi.
/* * 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) } }
Menampilkan/Menyembunyikan kode Objective-C untuk pengontrol tampilan navigasi.
/* * 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
Meminta otorisasi yang diperlukan kepada pengguna
Sebelum menggunakan Navigation SDK, pengguna harus menyetujui persyaratan dan ketentuan, serta mengizinkan penggunaan layanan lokasi, yang diperlukan untuk navigasi. Jika aplikasi Anda akan berjalan di latar belakang, aplikasi juga harus meminta pengguna untuk mengizinkan notifikasi pemberitahuan panduan. Bagian ini menunjukkan cara menampilkan perintah otorisasi yang diperlukan.
Mengizinkan layanan lokasi
Navigation SDK menggunakan layanan lokasi, yang memerlukan otorisasi pengguna. Untuk mengaktifkan layanan lokasi dan menampilkan dialog otorisasi, lakukan langkah-langkah berikut:
- Tambahkan kunci
NSLocationAlwaysUsageDescription
keInfo.plist
. Untuk nilai, tambahkan penjelasan singkat tentang alasan aplikasi Anda memerlukan layanan lokasi. Misalnya: "Aplikasi ini memerlukan izin untuk menggunakan layanan lokasi untuk navigasi belokan demi belokan".
Untuk menampilkan dialog otorisasi, panggil
requestAlwaysAuthorization()
dari instance pengelola lokasi.
self.locationManager.requestAlwaysAuthorization()
[_locationManager requestAlwaysAuthorization];
Memberi otorisasi notifikasi pemberitahuan untuk panduan latar belakang
Navigation SDK memerlukan izin pengguna untuk memberikan notifikasi pemberitahuan saat aplikasi berjalan di latar belakang. Tambahkan kode berikut untuk meminta izin kepada pengguna untuk menampilkan notifikasi ini:
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");
}
}];
Setujui persyaratan dan ketentuan
Gunakan kode berikut untuk menampilkan dialog persyaratan dan ketentuan, dan aktifkan navigasi saat pengguna menyetujui persyaratan. Perhatikan bahwa contoh ini menyertakan kode untuk layanan lokasi dan notifikasi pemberitahuan panduan (ditampilkan sebelumnya).
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.
}
}];
Membuat rute dan memulai panduan
Untuk merencanakan rute, panggil metode setDestinations()
Navigator dengan array
yang berisi satu atau beberapa tujuan (GMSNavigationWaypoint
) yang akan dikunjungi. Jika berhasil
dihitung, rute akan ditampilkan di peta. Untuk memulai panduan di sepanjang rute,
mulai dari tujuan pertama, tetapkan isGuidanceActive
ke true
dalam
callback.
Contoh berikut menampilkan:
- Membuat rute baru dengan dua tujuan.
- Memulai panduan.
- Mengaktifkan notifikasi panduan latar belakang.
- Menyimulasikan perjalanan di sepanjang rute (opsional).
- Menyetel mode kamera ke "ikuti" (opsional).
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;
}];
}
Untuk mempelajari ID Tempat, lihat ID Tempat.
Menetapkan mode perjalanan
Mode perjalanan menentukan jenis rute yang akan diambil, dan cara jalur pengguna ditentukan. Anda dapat menetapkan salah satu dari empat mode perjalanan untuk rute: mengemudi, bersepeda, berjalan kaki, dan taksi. Dalam mode mengemudi dan taksi, rute pengguna berdasarkan arah perjalanan; dalam mode bersepeda dan berjalan kaki, rute diwakili oleh arah yang dihadapi perangkat.
Tetapkan properti travelMode
tampilan peta, seperti yang ditunjukkan pada contoh berikut:
self.mapView.travelMode = .cycling
_mapView.travelMode = GMSNavigationTravelModeCycling;
Menetapkan jalan yang akan dihindari
Gunakan properti avoidsHighways
dan avoidsTolls
BOOL
untuk menghindari jalan raya dan/atau jalan tol di sepanjang rute.
self.mapView.navigator?.avoidsTolls = true
_mapView.navigator.avoidsTolls = YES;
Pencari PlaceID
Anda dapat menggunakan PlaceID Finder
untuk menemukan ID tempat yang akan digunakan untuk tujuan rute. Tambahkan tujuan dari placeID
dengan GMSNavigationWaypoint
.
Teks mengambang
Anda dapat menambahkan teks mengambang di mana saja di aplikasi, selama atribusi Google tidak tertutup. Navigation SDK tidak mendukung anchor teks ke lintang/bujur pada peta, atau ke label. Untuk informasi selengkapnya, lihat Jendela info.