Navigation SDK는 현재 일부 고객만 사용할 수 있습니다. 자세한 내용은 영업팀에 문의하세요.
새로운 지도 스타일 지정 기능이 곧 Google Maps Platform에 도입될 예정입니다. 이번 지도 스타일 지정 업데이트에는 새로운 기본 색상 팔레트가 추가되었으며 지도 환경 및 사용성이 개선되었습니다. 모든 지도 스타일은 2025년 3월에 자동으로 업데이트됩니다. 사용 가능 여부 및 이전에 선택한 방법에 대한 자세한 내용은 Google Maps Platform의 새 지도 스타일을 참고하세요.
/**Copyright2020GoogleInc.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,GMSNavigatorListener,GMSRoadSnappedLocationProviderListener{varmapView:GMSMapView!varlocationManager:CLLocationManager!overridefuncloadView(){locationManager=CLLocationManager()letcamera=GMSCameraPosition.camera(withLatitude:47.67,longitude:-122.20,zoom:14)mapView=GMSMapView.map(withFrame:CGRect.zero,camera:camera)//AddlistenersforGMSNavigatorandGMSRoadSnappedLocationProvider.mapView.navigator?.add(self)mapView.roadSnappedLocationProvider?.add(self)//Setthetimeupdatethreshold(seconds)anddistanceupdatethreshold(meters).mapView.navigator?.timeUpdateThreshold=10mapView.navigator?.distanceUpdateThreshold=100//Showthetermsandconditions.letcompanyName="Ride Sharing Co."GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(withCompanyName:companyName){termsAcceptediniftermsAccepted{//Enablenavigationiftheuseracceptstheterms.self.mapView.isNavigationEnabled=true//Requestauthorizationtouselocationservices.self.locationManager.requestAlwaysAuthorization()//Requestauthorizationforalertnotificationswhichdeliverguidanceinstructions//inthebackground.UNUserNotificationCenter.current().requestAuthorization(options:[.alert]){granted,errorin//Handledeniedauthorizationtodisplaynotifications.if!granted||error!=nil{print("Authorization to deliver notifications was rejected.")}}}else{//Handlethecasewhentheuserrejectsthetermsandconditions.}}view=mapViewmakeButton()}//Createarouteandstartguidance.@objcfuncstartNav(){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.cameraMode=.followingself.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()}mapView.roadSnappedLocationProvider?.startUpdatingLocation()}//Listenertohandlecontinuouslocationupdates.funclocationProvider(_locationProvider:GMSRoadSnappedLocationProvider,didUpdatelocation:CLLocation){print("Location: \(location.description)")}//Listenertohandlespeedingevents.funcnavigator(_navigator:GMSNavigator,didUpdateSpeedingPercentagepercentageAboveLimit:CGFloat){print("Speed is \(percentageAboveLimit) above the limit.")}//Listenertohandlearrivalevents.funcnavigator(_navigator:GMSNavigator,didArriveAtwaypoint:GMSNavigationWaypoint){print("You have arrived at: \(waypoint.title)")mapView.navigator?.continueToNextDestination()mapView.navigator?.isGuidanceActive=true}//Listenerforroutechangeevents.funcnavigatorDidChangeRoute(_navigator:GMSNavigator){print("The route has changed.")}//Listenerfortimetonextdestination.funcnavigator(_navigator:GMSNavigator,didUpdateRemainingTimetime:TimeInterval){print("Time to next destination: \(time)")}//Delegatefordistancetonextdestination.funcnavigator(_navigator:GMSNavigator,didUpdateRemainingDistancedistance:CLLocationDistance){letmiles=distance*0.00062137print("Distance to next destination: \(miles) miles.")}//Delegatefortrafficupdatestonextdestinationfuncnavigator(_navigator:GMSNavigator,didUpdatedelayCategory:GMSNavigationDelayCategory){print("Delay category to next destination: \(String(describing: delayCategory)).")}//Delegateforsuggestedlightingmodechanges.funcnavigator(_navigator:GMSNavigator,didChangeSuggestedLightingModelightingMode:GMSNavigationLightingMode){print("Suggested lighting mode has changed: \(String(describing: lightingMode))")//Changetothesuggestedlightingmode.mapView.lightingMode=lightingMode}//Addabuttontotheview.funcmakeButton(){//Startnavigation.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 2020 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()<GMSNavigatorListener,GMSRoadSnappedLocationProviderListener>
@end@implementationViewController{GMSMapView*_mapView;CLLocationManager*_locationManager;}-(void)loadView{_locationManager=[[CLLocationManageralloc]init];GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:47.67longitude:-122.20zoom:14];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];// Add listeners for GMSNavigator and GMSRoadSnappedLocationProvider.[_mapView.navigatoraddListener:self];[_mapView.roadSnappedLocationProvideraddListener:self];// Set the time update threshold (seconds) and distance update threshold (meters)._mapView.navigator.timeUpdateThreshold=10;_mapView.navigator.distanceUpdateThreshold=100;// 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;// Request authorization to use location services.[_locationManagerrequestAlwaysAuthorization];}else{// Handle the case when the user rejects 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.navigator.guidanceActive=YES;_mapView.navigator.sendsBackgroundNotifications=YES;_mapView.cameraMode=GMSNavigationCameraModeFollowing;[_mapView.locationSimulatorsimulateLocationsAlongExistingRoute];}];[_mapView.roadSnappedLocationProviderstartUpdatingLocation];}#pragma mark - GMSNavigatorListener// Listener for continuous location updates.-(void)locationProvider:(GMSRoadSnappedLocationProvider*)locationProviderdidUpdateLocation:(CLLocation*)location{NSLog(@"Location: %@",location.description);}// Listener to handle speeding events.-(void)navigator:(GMSNavigator*)navigatordidUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit{NSLog(@"Speed is %f percent above the limit.",percentageAboveLimit);}// Listener to handle arrival events.-(void)navigator:(GMSNavigator*)navigatordidArriveAtWaypoint:(GMSNavigationWaypoint*)waypoint{NSLog(@"You have arrived at: %@",waypoint.title);[_mapView.navigatorcontinueToNextDestination];_mapView.navigator.guidanceActive=YES;}// Listener for route change events.-(void)navigatorDidChangeRoute:(GMSNavigator*)navigator{NSLog(@"The route has changed.");}// Listener for time to next destination.-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingTime:(NSTimeInterval)time{NSLog(@"Time to next destination: %f",time);}// Listener for distance to next destination.-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingDistance:(CLLocationDistance)distance{doublemiles=distance*0.00062137;NSLog(@"%@",[NSStringstringWithFormat:@"Distance to next destination: %.2f.",miles]);}// Listener for traffic updates for next destination-(void)navigator:(GMSNavigator*)navigatordidUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory{NSLog(@"Delay category to next destination: %ld.",delayCategory);}// Listener for suggested lighting mode changes.-(void)navigator:(GMSNavigator*)navigatordidChangeSuggestedLightingMode:(GMSNavigationLightingMode)lightingMode{NSLog(@"Suggested lighting mode has changed: %ld",(long)lightingMode);// Change to the suggested lighting mode._mapView.lightingMode=lightingMode;}#pragma mark - Programmatic UI elements// Add a button to the view.-(void)makeButton{// Start navigation.UIButton*navButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[navButtonaddTarget:selfaction:@selector(startNav)forControlEvents:UIControlEventTouchUpInside];[navButtonsetTitle:@"Navigate"forState:UIControlStateNormal];[navButtonsetBackgroundColor:[UIColorblueColor]];[navButtonsetAlpha:0.5];navButton.frame=CGRectMake(5.0,150.0,100.0,35.0);[_mapViewaddSubview:navButton];}@end
앱은 didArriveAtWaypoint 이벤트를 사용하여 대상에 도달했을 때 이를 감지합니다. continueToNextDestination()를 호출한 다음 안내를 다시 사용 설정하여 안내를 재개하고 다음 중간 지점으로 이동할 수 있습니다. 앱은 continueToNextDestination()를 호출한 후에 안내를 다시 사용 설정해야 합니다.
앱이 continueToNextDestination를 호출하면 더 이상 이전 대상에 관한 데이터가 내비게이터에 없습니다. 경로 구간에 관한 정보를 분석하려면 continueToNextDestination()를 호출하기 전에 탐색기에서 이를 가져와야 합니다.
다음 코드 예는 didArriveAtWaypoint 이벤트를 처리하는 메서드를 보여줍니다.
Swift
funcnavigator(_navigator:GMSNavigator,didArriveAtwaypoint:GMSNavigationWaypoint){print("You have arrived at: \(waypoint.title)")mapView.navigator?.continueToNextDestination()mapView.navigator?.isGuidanceActive=true}
목적지까지의 시간 업데이트를 연속으로 수신하려면 didUpdateRemainingTime 이벤트를 처리하는 메서드를 만듭니다. time 매개변수는 다음 대상에 도달할 때까지의 예상 시간을 초 단위로 제공합니다.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingTimetime:TimeInterval){print("Time to next destination: \(time)")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingTime:(NSTimeInterval)time{NSLog(@"Time to nextdestination:%f", time); }
다음 도착지에 도착하는 데 걸리는 예상 시간의 최소 변경 값을 설정하려면 GMSNavigator에서 timeUpdateThreshold 속성을 설정하세요. 값은 초 단위로 지정됩니다. 이 속성을 설정하지 않으면 서비스는 기본값인 1초를 사용합니다.
Swift
navigator?.timeUpdateThreshold=10
Objective-C
navigator.timeUpdateThreshold=10;
도착지까지의 거리 업데이트 수신
목적지까지의 거리 업데이트를 지속적으로 수신하려면 didUpdateRemainingDistance 이벤트를 처리하는 메서드를 만듭니다. distance 매개변수는 다음 목적지까지의 예상 거리(단위: 미터)를 제공합니다.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingDistancedistance:CLLocationDistance){letmiles=distance*0.00062137print("Distance to nextdestination: \(miles) miles.")}
다음 도착지에 대한 예상 거리의 최소 변경사항을 설정하려면 GMSNavigator에서 distanceUpdateThreshold 속성을 설정합니다 (값은 미터로 지정됨). 이 속성을 설정하지 않으면 서비스는 기본값인 1미터를 사용합니다.
Swift
navigator?.distanceUpdateThreshold=100
Objective-C
navigator.distanceUpdateThreshold=100;
교통정보 업데이트 받기
나머지 경로의 교통 흐름에 대한 지속적인 업데이트를 수신하려면 didUpdateDelayCategory 이벤트를 처리하는 메서드를 만듭니다. delayCategoryToNextDestination를 호출하면 0~3의 값을 제공하는 GMSNavigationDelayCategory가 반환됩니다. 카테고리 업데이트는 앱 사용자의 현재 위치를 기반으로 합니다. 트래픽 데이터를 사용할 수 없는 경우 GMSNavigationDelayCategory는 0을 반환합니다. 숫자 1~3은 흐름이 약에서 강으로 증가함을 나타냅니다.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdatedelayCategory:GMSNavigationDelayCategory){print("Traffic flow to next destination:\(delayCategory)")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory{NSLog(@"Traffic flow to next destination: %ld",(long)delayCategory);}
GMSNavigationDelayCategory 속성은 다음과 같은 지연 수준을 노출합니다.
지연 카테고리
설명
GMSNavigationDelayCategoryNoData
0 - 사용 불가, 트래픽 데이터 없음 또는 :
경로를 확인할 수 있습니다.
GMSNavigationDelayCategoryHeavy
1 - 심각함
GMSNavigationDelayCategoryMedium
2 - 중간
GMSNavigationDelayCategoryLight
3 - 밝음
속도 위반 업데이트 수신
운전자가 속도 제한을 초과할 때 업데이트를 수신하려면 didUpdateSpeedingPercentage 이벤트를 처리하는 메서드를 만듭니다.
Swift
// Listener to handle speeding events. func navigator( _ navigator:GMSNavigator,didUpdateSpeedingPercentagepercentageAboveLimit:CGFloat){print("Speed is \(percentageAboveLimit) above the limit.")}
Objective-C
// Listener to handle speeding events. - (void)navigator:(GMSNavigator*)navigatordidUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit{NSLog(@"Speed is %f percent above the limit.",percentageAboveLimit);}
추천 조명 모드 변경
예상되는 조명 변경사항에 관한 업데이트를 수신하려면 didChangeSuggestedLightingMode 이벤트를 처리하는 메서드를 만듭니다.
Swift
// Define a listener for suggested changes to lighting mode. func navigator(_navigator:GMSNavigator,didChangeSuggestedLightingModelightingMode:GMSNavigationLightingMode){print("Suggested lighting mode has changed:\(String(describing:lightingMode))")// Make the suggested change. mapView.lightingMode = lightingMode }
Objective-C
// Define a listener for suggested changes to lighting mode.-(void)navigator:(GMSNavigator*)navigatordidChangeSuggestedLightingMode:(GMSNavigationLightingMode)lightingMode{NSLog(@"Suggested lighting mode haschanged:%ld", (long)lightingMode);// Make the suggested change. _mapView.lightingMode = lightingMode; }