이 가이드를 따라 iOS용 Navigation SDK를 사용하여 앱 내에서 단일 목적지로의 경로를 표시하세요.
개요
- 프로젝트 설정 섹션에 설명된 대로 Navigation SDK를 앱에 통합합니다.
GMSMapView
를 구성합니다.- 사용자에게 이용약관에 동의하고 위치 서비스 및 백그라운드 알림을 승인하도록 메시지를 표시합니다.
- 하나 이상의 대상이 포함된 배열을 만듭니다.
세부 경로 안내를 제어하는
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는 사용자 승인이 필요한 위치 서비스를 사용합니다. 위치 서비스를 사용 설정하고 승인 대화상자를 표시하려면 다음 단계를 따르세요.
Info.plist
에NSLocationAlwaysUsageDescription
키를 추가합니다.값에는 앱에 위치 서비스가 필요한 이유를 간단히 설명합니다. 예: '이 앱은 세부 경로 내비게이션을 위해 위치 서비스를 사용하기 위한 권한이 필요합니다.'
승인 대화상자를 표시하려면 위치 관리자 인스턴스의
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.
}
}];
경로 만들기 및 안내 시작
경로를 표시하려면 방문할 하나 이상의 대상 (GMSNavigationWaypoint
)이 포함된 배열을 사용하여 Navigator의 setDestinations()
메서드를 호출합니다. 계산에 성공하면 경로가 지도에 표시됩니다. 경로를 따라 안내를 시작하려면 첫 번째 목적지부터 시작하여 콜백에서 isGuidanceActive
를 true
로 설정합니다.
다음 예시는 다음과 같은 기능을 보여줍니다.
- 두 개의 목적지가 있는 새 경로를 만듭니다.
- 시작 안내
- 백그라운드 안내 알림을 사용 설정합니다.
- 경로를 따라 이동을 시뮬레이션합니다 (선택사항).
- 카메라 모드를 '추적'으로 설정합니다(선택사항).
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;
}];
}
장소 ID에 대해 알아보려면 장소 ID를 참고하세요.
이동 수단 설정
이동 모드는 가져올 경로 유형과 사용자의 경로가 결정되는 방식을 결정합니다. 경로에 운전, 자전거, 도보, 택시 등 4가지 이동 수단 중 하나를 설정할 수 있습니다. 운전 및 택시 모드에서는 사용자의 경로가 이동 방향을 기반으로 합니다. 자전거 및 도보 모드에서는 경로가 기기가 향하는 방향으로 표시됩니다.
다음 예와 같이 지도 뷰의 travelMode
속성을 설정합니다.
self.mapView.travelMode = .cycling
_mapView.travelMode = GMSNavigationTravelModeCycling;
피할 도로 설정
avoidsHighways
및 avoidsTolls
BOOL
속성을 사용하여 경로에서 고속도로 또는 유료도로를 피합니다.
self.mapView.navigator?.avoidsTolls = true
_mapView.navigator.avoidsTolls = YES;
PlaceID 찾기
장소 ID 검색 도구를 사용하여 경로 대상에 사용할 장소 ID를 찾을 수 있습니다. GMSNavigationWaypoint
를 사용하여 placeID
에서 대상을 추가합니다.
플로팅 텍스트
Google 저작자 표시가 가려지지 않는 한 앱의 어느 위치에나 플로팅 텍스트를 추가할 수 있습니다. Navigation SDK는 지도의 위도/경도 또는 라벨에 텍스트를 고정하는 기능을 지원하지 않습니다. 자세한 내용은 정보 창을 참고하세요.