Navigation SDK는 현재 일부 고객만 사용할 수 있습니다. 자세한 내용은 영업팀에 문의하세요.
새로운 지도 스타일 지정 기능이 곧 Google Maps Platform에 도입될 예정입니다. 이번 지도 스타일 지정 업데이트에는 새로운 기본 색상 팔레트가 추가되었으며 지도 환경 및 사용성이 개선되었습니다. 모든 지도 스타일은 2025년 3월에 자동으로 업데이트됩니다. 사용 가능 여부 및 이전에 선택한 방법에 대한 자세한 내용은 Google Maps Platform의 새 지도 스타일을 참고하세요.
/**Copyright2017GoogleInc.Allrightsreserved.**LicensedundertheApacheLicense,Version2.0(the"License");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan"AS IS"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/importGoogleNavigationimportUIKitclassViewController:UIViewController{varmapView:GMSMapView!varlocationManager:CLLocationManager!overridefuncloadView(){locationManager=CLLocationManager()//Setupthemapview.letcamera=GMSCameraPosition.camera(withLatitude:47.67,longitude:-122.20,zoom:14)mapView=GMSMapView.map(withFrame:.zero,camera:camera)//Showthetermsandconditions.letcompanyName="Ride Sharing Co."GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(withCompanyName:companyName){termsAcceptediniftermsAccepted{//Enablenavigationiftheuseracceptstheterms.self.mapView.isNavigationEnabled=trueself.mapView.settings.compassButton=true//Requestauthorizationtouselocationservices.self.locationManager.requestAlwaysAuthorization()//Requestauthorizationforalertnotificationswhichdeliverguidanceinstructions//inthebackground.UNUserNotificationCenter.current().requestAuthorization(options:[.alert]){granted,errorin//Handledeniedauthorizationtodisplaynotifications.if!granted||error!=nil{print("User rejected request to display notifications.")}}}else{//Handlerejectionoftermsandconditions.}}view=mapViewmakeButton()}//Createarouteandstartguidance.funcstartNav(){vardestinations=[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){routeStatusinguardrouteStatus==.OKelse{print("Handle route statuses that are not OK.")return}self.mapView.navigator?.isGuidanceActive=trueself.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()self.mapView.cameraMode=.following}}//Addabuttontotheview.funcmakeButton(){//Abuttontostartnavigation.letnavButton=UIButton(frame:CGRect(x:5,y:150,width:200,height:35))navButton.backgroundColor=.bluenavButton.alpha=0.5navButton.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"@importGoogleNavigation;@interfaceViewController()@end@implementationViewController{GMSMapView*_mapView;CLLocationManager*_locationManager;}-(void)loadView{_locationManager=[[CLLocationManageralloc]init];// Set up the map view.GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:47.67longitude:-122.20zoom:14];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];// Show the terms and conditions.NSString*companyName=@"Ride Sharing Co.";[GMSNavigationServicesshowTermsAndConditionsDialogIfNeededWithCompanyName:companyNamecallback:^(BOOLtermsAccepted){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.[_locationManagerrequestAlwaysAuthorization];// Request authorization for alert notifications which deliver guidance instructions// in the background.UNUserNotificationCenter*center=[UNUserNotificationCentercurrentNotificationCenter];UNAuthorizationOptionsoptions=UNAuthorizationOptionAlert;[centerrequestAuthorizationWithOptions:optionscompletionHandler:^(BOOLgranted,NSError*_Nullableerror){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;[selfmakeButton];}// Create a route and initiate navigation.-(void)startNav{NSArray<GMSNavigationWaypoint*>*destinations=@[[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJnUYTpNASkFQR_gSty5kyoUk"title:@"PCC Natural Market"],[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJJ326ROcSkFQRBfUzOL2DSbo"title:@"Marina Park"]];[_mapView.navigatorsetDestinations:destinationscallback:^(GMSRouteStatusrouteStatus){[_mapView.locationSimulatorsimulateLocationsAlongExistingRoute];_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=[UIButtonbuttonWithType:UIButtonTypeCustom];[navButtonaddTarget:selfaction:@selector(startNav)forControlEvents:UIControlEventTouchUpInside];[navButtonsetTitle:@"Navigate"forState:UIControlStateNormal];[navButtonsetBackgroundColor:[UIColorblueColor]];navButton.frame=CGRectMake(5.0,150.0,100.0,35.0);[_mapViewaddSubview:navButton];}@end
사용자에게 필요한 승인 메시지 표시
Navigation SDK를 사용하기 전에 사용자는 이용약관에 동의하고 탐색에 필요한 위치 서비스 사용을 승인해야 합니다. 앱이 백그라운드에서 실행되는 경우 사용자에게 안내 알림을 승인하라는 메시지도 표시해야 합니다. 이 섹션에서는 필요한 승인 메시지를 표시하는 방법을 보여줍니다.
위치 서비스 승인
Navigation SDK는 사용자 승인이 필요한 위치 서비스를 사용합니다. 위치 서비스를 사용 설정하고 승인 대화상자를 표시하려면 다음 단계를 따르세요.
값에는 앱에 위치 서비스가 필요한 이유를 간단히 설명합니다. 예: '이 앱은 세부 경로 내비게이션을 위해 위치 서비스를 사용하기 위한 권한이 필요합니다.'
승인 대화상자를 표시하려면 위치 관리자 인스턴스의 requestAlwaysAuthorization()를 호출합니다.
Swift
self.locationManager.requestAlwaysAuthorization()
Objective-C
[_locationManagerrequestAlwaysAuthorization];
백그라운드 안내를 위한 알림 승인
Navigation SDK는 앱이 백그라운드에서 실행 중일 때 알림을 제공하려면 사용자 권한이 필요합니다. 다음 코드를 추가하여 사용자에게 이러한 알림을 표시할 권한을 요청합니다.
Swift
UNUserNotificationCenter.current().requestAuthorization(options:[.alert]){granted,errorin// 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=[UNUserNotificationCentercurrentNotificationCenter];UNAuthorizationOptionsoptions=UNAuthorizationOptionAlert;[centerrequestAuthorizationWithOptions:optionscompletionHandler:^(BOOLgranted,NSError*_Nullableerror){if(!error && granted){NSLog(@"iOS Notification Permission: newly Granted");}else{NSLog(@"iOS Notification Permission: Failed or Denied");}}];
이용약관 동의
다음 코드를 사용하여 이용약관 대화상자를 표시하고 사용자가 약관에 동의하면 탐색을 사용 설정합니다. 이 예에는 위치 서비스 및 안내 알림 알림의 코드 (이전에 표시됨)가 포함되어 있습니다.
Swift
lettermsAndConditionsOptions=GMSNavigationTermsAndConditionsOptions(companyName:"Ride Sharing Co.")GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(with:termsAndConditionsOptions){termsAcceptediniftermsAccepted{// Enable navigation if the user accepts the terms.self.mapView.isNavigationEnabled=trueself.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,errorin// 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
GMSNavigationTermsAndConditionsOptions*termsAndConditionsOptions=[[GMSNavigationTermsAndConditionsOptionsalloc]initWithCompanyName:@"Ride Sharing Co."];[GMSNavigationServicesshowTermsAndConditionsDialogIfNeededWithOptions:termsAndConditionsOptionscallback:^(BOOLtermsAccepted){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.[_locationManagerrequestAlwaysAuthorization];// Request authorization for alert notifications which deliver guidance instructions// in the background.UNUserNotificationCenter*center=[UNUserNotificationCentercurrentNotificationCenter];UNAuthorizationOptionsoptions=UNAuthorizationOptionAlert;[centerrequestAuthorizationWithOptions:optionscompletionHandler:^(BOOLgranted,NSError*_Nullableerror){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로 설정합니다.
이동 모드는 가져올 경로 유형과 사용자의 경로가 결정되는 방식을 결정합니다. 경로에 운전, 자전거, 도보, 택시 등 4가지 이동 수단 중 하나를 설정할 수 있습니다. 운전 및 택시 모드에서는 사용자의 경로가 이동 방향을 기반으로 합니다. 자전거 및 도보 모드에서는 경로가 기기가 향하는 방향으로 표시됩니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-02-25(UTC)"],[[["This guide explains how to use the Navigation SDK for iOS to plot a route within your app to a single destination."],["Before using the SDK, ensure the user accepts the terms and conditions and authorizes location services and background notifications."],["Create a `GMSNavigator` and add destinations using `setDestinations` to define the route and initiate guidance by setting `isGuidanceActive` to `true`."],["Set the `travelMode` property of the map view to specify the preferred mode of transportation, such as driving, cycling, walking, or taxi."],["Optionally, configure route preferences like avoiding highways or tolls using the `avoidsHighways` and `avoidsTolls` properties."]]],["To integrate turn-by-turn navigation, first integrate the Navigation SDK and configure a `GMSMapView`. Then, prompt the user to accept terms, authorize location services, and background notifications. Create an array of destinations, using Place IDs if desired, and define a `GMSNavigator` to control navigation. Use `setDestinations` to add destinations, set `isGuidanceActive` to true to start. `simulateLocationsAlongExistingRoute` helps simulate travel along a given route. The user can also set the travel mode and roads to avoid. Finally, remember to disable the device's idle timer.\n"]]