ทำตามคู่มือนี้เพื่อวางเส้นทางภายในแอปไปยังปลายทางเดียวโดยใช้ Navigation SDK สำหรับ iOS
ภาพรวม
- ผสานรวม Navigation SDK เข้ากับแอปตามที่อธิบายไว้ในส่วนตั้งค่าโปรเจ็กต์
- กำหนดค่า
GMSMapView
- แจ้งให้ผู้ใช้ยอมรับข้อกำหนดและเงื่อนไข รวมถึงให้สิทธิ์บริการตำแหน่งและการแจ้งเตือนในเบื้องหลัง
- สร้างอาร์เรย์ที่มีปลายทางอย่างน้อย 1 รายการ
กำหนด
GMSNavigator
เพื่อควบคุมการนำทางแบบเลี้ยวต่อเลี้ยว- เพิ่มปลายทางโดยใช้
setDestinations
- ตั้งค่า
isGuidanceActive
เป็นtrue
เพื่อเริ่มการนำทาง - ใช้
simulateLocationsAlongExistingRoute
เพื่อจำลองความคืบหน้าของยานพาหนะตามเส้นทางสำหรับการทดสอบ การแก้ไขข้อบกพร่อง และการแสดงแอป
- เพิ่มปลายทางโดยใช้
ดูรหัส
แสดง/ซ่อนโค้ด Swift สำหรับตัวควบคุมมุมมองการนำทาง
/* * 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) } }
แสดง/ซ่อนโค้ด Objective-C สําหรับตัวควบคุมมุมมองการนําทาง
/* * 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 ใช้บริการตำแหน่ง ซึ่งต้องได้รับสิทธิ์จากผู้ใช้ หากต้องการเปิดใช้บริการหาตำแหน่งและแสดงกล่องโต้ตอบการให้สิทธิ์ ให้ทำตามขั้นตอนต่อไปนี้
- เพิ่มคีย์
NSLocationAlwaysUsageDescription
ลงในInfo.plist
สำหรับค่า ให้เพิ่มคำอธิบายสั้นๆ ว่าเหตุใดแอปของคุณจึงต้องใช้บริการตำแหน่ง เช่น "แอปนี้ต้องมีสิทธิ์ใช้บริการหาตำแหน่งเพื่อนำทางแบบเลี้ยวต่อเลี้ยว"
หากต้องการแสดงกล่องโต้ตอบการให้สิทธิ์ ให้เรียกใช้
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
) อย่างน้อย 1 แห่งที่จะไป หากคำนวณสำเร็จ เส้นทางจะแสดงบนแผนที่ หากต้องการเริ่มคำแนะนำตลอดเส้นทางโดยเริ่มจากจุดหมายแรก ให้ตั้งค่า isGuidanceActive
เป็น true
ใน callback
ตัวอย่างต่อไปนี้แสดงข้อมูลต่อไปนี้
- การสร้างเส้นทางใหม่ที่มีปลายทาง 2 แห่ง
- คำแนะนำในการเริ่มต้น
- การเปิดใช้การแจ้งเตือนคำแนะนำขณะขับรถ
- การจําลองการเดินทางไปตามเส้นทาง (ไม่บังคับ)
- การตั้งค่าโหมดกล้องเป็น "ติดตาม" (ไม่บังคับ)
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;
}];
}
ดูข้อมูลเกี่ยวกับรหัสสถานที่ได้ที่รหัสสถานที่
ตั้งค่าโหมดการเดินทาง
โหมดการเดินทางจะกำหนดประเภทเส้นทางที่จะดึงข้อมูล และวิธีกำหนดเส้นทางของผู้ใช้ คุณตั้งค่าโหมดการเดินทางได้ 1 ใน 4 โหมดสำหรับเส้นทาง ได้แก่ ขับรถ ปั่นจักรยาน เดิน และแท็กซี่ ในโหมดขับรถและแท็กซี่ เส้นทางของผู้ใช้จะอิงตามทิศทางการเดินทาง ส่วนในโหมดปั่นจักรยานและเดิน เส้นทางจะแสดงตามทิศทางที่อุปกรณ์หันไป
ตั้งค่าพร็อพเพอร์ตี้ 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 ไม่รองรับการเชื่อมโยงข้อความกับละติจูด/ลองจิจูดบนแผนที่หรือกับป้ายกำกับ ดูข้อมูลเพิ่มเติมได้ที่หน้าต่างข้อมูล