소비자 SDK를 사용하여 주문형 차량 공유 및 배송 솔루션 백엔드 서비스와 통합된 기본 소비자 앱을 빌드하고 실행할 수 있습니다. 활성 상태의 이동을 표시하고, 경로 업데이트에 응답하며, 이동 오류를 처리할 수 있는 이동 및 주문 진행 앱을 만들 수 있습니다.
Consumer SDK에는 모듈식 아키텍처가 있으므로 특정 앱에 사용하려는 API 부분을 사용하여 자체 API, Fleet Engine에서 제공하는 백엔드 서비스, Google Maps Platform의 추가 API와 통합할 수 있습니다.
최소 시스템 요구사항
프로젝트 구성
CocoaPods를 사용하여 소비자 SDK를 구성할 수 있습니다.
CocoaPods 사용
CocoaPods를 사용하여 소비자 SDK를 구성하려면 다음 항목이 필요합니다.
- CocoaPods 도구: 이 도구를 설치하려면 터미널을 열고 다음 명령어를 실행합니다.
shell sudo gem install cocoapods
자세한 내용은 CocoaPods 시작 가이드를 참고하세요.
소비자 SDK용 Podfile을 만들고 이를 사용하여 API와 종속 항목을 설치합니다. 먼저 프로젝트 디렉터리에 Podfile이라는 파일을 만듭니다. 이 파일은 프로젝트의 종속 항목을 정의합니다. 그런 다음 Podfile을 수정하고 종속 항목을 추가합니다. 다음은 종속 항목이 포함된 예입니다.
source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingConsumer' end
Podfile을 저장합니다. 터미널을 열고 Podfile이 있는 디렉터리로 이동합니다.
cd <path-to-project>
pod 설치 명령어를 실행합니다. 그러면 Podfile에 지정된 API가 종속 항목과 함께 설치됩니다.
pod install
Xcode를 닫은 다음 프로젝트의 .xcworkspace 파일을 열고 (더블클릭하여) Xcode를 실행합니다. 나중에 프로젝트를 열려면 .xcworkspace 파일을 사용하세요.
알파/베타 SDK 버전
iOS용 CocoaPods를 사용하여 소비자 SDK의 알파 또는 베타 버전을 구성하려면 다음 항목이 필요합니다.
CocoaPods 도구: 이 도구를 설치하려면 터미널을 열고 다음 명령어를 실행합니다.
sudo gem install cocoapods
자세한 내용은 CocoaPods 시작 가이드를 참고하세요.
Google 액세스 목록에 있는 개발 계정 SDK 알파 및 베타 버전의 포드 저장소는 공개 소스가 아닙니다. 이러한 버전에 액세스하려면 Google 고객 엔지니어에게 문의하세요. 엔지니어가 개발 계정을 액세스 목록에 추가한 다음 인증을 위한 쿠키를 설정합니다.
프로젝트가 액세스 목록에 포함되면 포드에 액세스할 수 있습니다.
iOS용 소비자 SDK용 Podfile을 만들고 이를 사용하여 API 및 종속 항목을 설치합니다. 프로젝트 디렉터리에 Podfile이라는 파일을 만듭니다. 이 파일은 프로젝트의 종속 항목을 정의합니다. Podfile을 수정하고 종속 항목을 추가합니다. 다음은 종속 항목이 포함된 예입니다.
source "https://cpdc-eap.googlesource.com/ridesharing-consumer-sdk" source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingConsumer' end
Podfile을 저장합니다. 터미널을 열고 Podfile이 있는 디렉터리로 이동합니다.
cd <path-to-project>
pod 설치 명령어를 실행합니다. 그러면 Podfile에 지정된 API가 종속 항목과 함께 설치됩니다.
pod install
Xcode를 닫은 후 프로젝트의 .xcworkspace 파일을 (더블클릭) 열어 Xcode를 실행합니다. 지금부터는 .xcworkspace 파일을 사용하여 프로젝트를 열어야 합니다.
애플리케이션 통합
인증 토큰 제공
소비자 앱이 Fleet Engine에서 경로 업데이트를 요청하는 경우 요청에 유효한 액세스 토큰이 포함되어야 합니다. 이러한 요청을 승인하고 인증하기 위해 소비자 SDK는 GMTCAuthorization
프로토콜을 따라 객체를 호출합니다. 객체는 필요한 액세스 토큰을 제공합니다.
앱 개발자는 토큰 생성 방법을 선택할 수 있습니다. 구현을 통해 다음 작업을 할 수 있어야 합니다.
- HTTPS 서버에서 액세스 토큰을 가져옵니다(JSON 형식일 수도 있음).
- 토큰을 파싱하고 캐시합니다.
- 토큰이 만료되면 토큰을 새로고침합니다.
Fleet Engine 서버에서 예상하는 토큰에 대한 자세한 내용은 승인을 위한 JSON 웹 토큰 (JWT) 만들기를 참조하세요.
제공업체 ID는 Google Cloud 프로젝트 ID와 동일합니다. 자세한 내용은 Fleet Engine 시작하기를 참조하세요.
다음 예에서는 액세스 토큰 제공자를 구현합니다.
Swift
/*
* SampleAccessTokenProvider.swift
*/
import GoogleRidesharingConsumer
private let providerURL = "INSERT_YOUR_TOKEN_PROVIDER_URL"
class SampleAccessTokenProvider: NSObject, GMTCAuthorization {
private struct AuthToken {
// The cached trip token.
let token: String
// Keep track of when the token expires for caching.
let expiration: TimeInterval
// Keep track of the trip ID the cached token is for.
let tripID: String
}
enum AccessTokenError: Error {
case missingAuthorizationContext
case missingData
}
private var authToken: AuthToken?
func fetchToken(
with authorizationContext: GMTCAuthorizationContext?,
completion: @escaping GMTCAuthTokenFetchCompletionHandler
) {
// Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
guard let authorizationContext = authorizationContext else {
completion(nil, AccessTokenError.missingAuthorizationContext)
return
}
let tripID = authorizationContext.tripID
// If appropriate, use the cached token.
if let authToken = authToken,
authToken.expiration > Date.now.timeIntervalSince1970 && authToken.tripID == tripID
{
completion(authToken.token, nil)
return
}
// Otherwise, try to fetch a new token from your server.
let request = URLRequest(url: URL(string: providerURL))
let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in
guard let strongSelf = self else { return }
guard error == nil else {
completion(nil, error)
return
}
// Replace the following key values with the appropriate keys based on your
// server's expected response.
let tripTokenKey = "TRIP_TOKEN_KEY"
let tokenExpirationKey = "TOKEN_EXPIRATION"
guard let data = data,
let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let token = fetchData[tripTokenKey] as? String,
let expiration = fetchData[tokenExpirationKey] as? Double
else {
completion(nil, AccessTokenError.missingData)
return
}
strongSelf.authToken = AuthToken(token: token, expiration: expiration, tripID: tripID)
completion(token, nil)
}
task.resume()
}
}
Objective-C
/*
* SampleAccessTokenProvider.h
*/
#import <Foundation/Foundation.h>
#import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
NS_ASSUME_NONNULL_BEGIN
@interface SampleAccessTokenProvider : NSObject <GMTCAuthorization>
@end
NS_ASSUME_NONNULL_END
/*
* SampleAccessTokenProvider.m
*/
#import "SampleAccessTokenProvider.h"
#import "GoogleRidesharingConsumer/GoogleRidesharingConsumer.h"
static NSString *const PROVIDER_URL = @"INSERT_YOUR_TOKEN_PROVIDER_URL";
// SampleAccessTokenProvider.m
@implementation SampleAccessTokenProvider {
// The cached token with claims to the current trip.
NSString *_cachedTripToken;
// Keep track of the Trip ID the cached token is for.
NSString *_lastKnownTripID;
// Keep track of when tokens expire for caching.
NSTimeInterval _tokenExpiration;
}
- (void)fetchTokenWithContext:(nullable GMTCAuthorizationContext *)authorizationContext
completion:(nonnull GMTCAuthTokenFetchCompletionHandler)completion {
// Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
NSString *tripID = authorizationContext.tripID;
// Clear cached trip token if trip ID has changed.
if (![_lastKnownTripID isEqual:tripID]) {
_tokenExpiration = 0.0;
_cachedTripToken = nil;
}
_lastKnownTripID = tripID;
// Clear cached tripToken if it has expired.
if ([[NSDate date] timeIntervalSince1970] > _tokenExpiration) {
_cachedTripToken = nil;
}
// If appropriate, use the cached token.
if (_cachedTripToken) {
completion(_cachedTripToken, nil);
return;
}
// Otherwise, try to fetch a new token from your server.
NSURL *requestURL = [NSURL URLWithString:PROVIDER_URL];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:requestURL];
request.HTTPMethod = @"GET";
// Replace the following key values with the appropriate keys based on your
// server's expected response.
NSString *tripTokenKey = @"TRIP_TOKEN_KEY";
NSString *tokenExpirationKey = @"TOKEN_EXPIRATION";
__weak typeof(self) weakSelf = self;
void (^handler)(NSData *_Nullable data, NSURLResponse *_Nullable response,
NSError *_Nullable error) =
^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
typeof(self) strongSelf = weakSelf;
if (error) {
completion(nil, error);
return;
}
NSError *JSONError;
NSMutableDictionary *JSONResponse =
[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONError];
if (JSONError) {
completion(nil, JSONError);
return;
} else {
// Sample code only. No validation logic.
id expirationData = JSONResponse[tokenExpirationKey];
if ([expirationData isKindOfClass:[NSNumber class]]) {
NSTimeInterval expirationTime = ((NSNumber *)expirationData).doubleValue;
strongSelf->_tokenExpiration = [[NSDate date] timeIntervalSince1970] + expirationTime;
}
strongSelf->_cachedTripToken = JSONResponse[tripTokenKey];
completion(JSONResponse[tripTokenKey], nil);
}
};
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *mainQueueURLSession =
[NSURLSession sessionWithConfiguration:config delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [mainQueueURLSession dataTaskWithRequest:request completionHandler:handler];
[task resume];
}
@end
애플리케이션 초기화
Swift
/*
* AppDelegate.swift
*/
import GoogleRidesharingConsumer
import GoogleMaps
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Register your API key for GMSServices.
GMSServices.provideAPIKey(yourMapsAPIKey)
// Set the instance of the SampleAccessTokenProvider.
GMTCServices.setAccessTokenProvider(SampleAccessTokenProvider(), providerID: yourProviderID)
// Other initialization code ...
return true
}
}
Objective-C
/*
* AppDelegate.m
*/
#import <GoogleMaps/GoogleMaps.h>
#import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//Register your API key for GMSServices.
[GMSServices provideAPIKey:yourMapsAPIKey];
//Set the instance of the AccessTokenFactory.
[GMTCServices setAccessTokenProvider:[[SampleAccessTokenProvider alloc] init]
providerID:yourProviderID];
// Other initialization code ...
return YES;
}
@end
지도뷰 통합
지도뷰 초기화하기
다음 예는 GMTCMapView
를 초기화하는 방법을 보여줍니다.
Swift
/*
* MapViewController.swift
*/
class ViewController: UIViewController, GMTCMapViewDelegate {
private var rideSharingMap: GMTCMapView?
override func viewDidLoad() {
super.viewDidLoad()
self.rideSharingMap = GMTCMapView(frame: UIScreen.main.bounds)
self.rideSharingMap.delegate = self
self.rideSharingMap?.settings.myLocationButton = true
self.view.addSubview(self.rideSharingMap!)
...
}
Objective-C
/*
* MapViewController.h
*/
@interface MapViewController : UIViewController<GMTCMapViewDelegate>
...
@end
/*
* MapViewController.m
*/
@implementation MapViewController
- (void)viewDidLoad {
[super viewDidLoad];
...
self.mapView = [[GMTCMapView alloc] init];
self.mapView.settings.myLocationButton = YES;
self.mapView.delegate = self;
...
}
...
@end
지도뷰 이벤트 처리
다음 예는 대리자를 구현하여 고객 상태 이벤트를 처리하는 방법을 보여줍니다.
Swift
func mapViewDidInitialize(_ mapview: GMTCMapView) {
// Handle the update to the state of the map view to browsing.
}
func mapView(_ mapView: GMSMapView, didTapConsumerMarker mapMarker: GMSMarker, markerType: GMTCMapViewMarkerType) -> Bool {
// Handle the mapView marker was tapped.
}
Objective-C
/*
* MapViewController.m
*/
#pragma mark - GMTCMapViewDelegate implementation
// Handle state update of map view.
- (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview {
// Handle the update to the state of the map view to browsing.
}
- (void)mapView:(GMSMapView *)mapView
didTapConsumerMarker:(nonnull GMSMarker *)mapMarker
markerType:(GMTCMapViewMarkerType)markerType {
// Handle the mapView marker was tapped.
}
여정 공유
뷰가 로드되면 새 이동 시작
다음 예는 뷰가 로드된 직후 여정 공유를 시작하는 방법을 보여줍니다. ViewController
에서 하차 및 승차 위치와 같은 모든 사용자 입력을 수집한 후 새 ViewController
를 만들어 여정 공유를 바로 시작할 수 있습니다.
Swift
/*
* MapViewController.swift
*/
override func viewDidLoad() {
super.viewDidLoad()
...
self.mapView = GMTCMapView(frame: UIScreen.main.bounds)
self.mapView.delegate = self
self.view.addSubview(self.mapView)
}
func mapViewDidInitializeCustomerState(_: GMTCMapView) {
self.mapView.pickupLocation = self.selectedPickupLocation
self.mapView.dropoffLocation = self.selectedDropoffLocation
self.startConsumerMatchWithLocations(
pickupLocation: self.mapView.pickupLocation!,
dropoffLocation: self.mapView.dropoffLocation!
) { [weak self] (tripName, error) in
guard let strongSelf = self else { return }
if error != nil {
// print error message.
return
}
let tripService = GMTCServices.shared().tripService
// Create a tripModel instance for listening the update of the trip
// specified by this trip name.
let tripModel = tripService.tripModel(forTripName: tripName)
// Create a journeySharingSession instance based on the tripModel
let journeySharingSession = GMTCJourneySharingSession(tripModel: tripModel)
// Add the journeySharingSession instance on the mapView for UI updating.
strongSelf.mapView.show(journeySharingSession)
// Register for the trip update events.
tripModel.register(strongSelf)
strongSelf.currentTripModel = tripModel
strongSelf.currentJourneySharingSession = journeySharingSession
strongSelf.hideLoadingView()
}
self.showLoadingView()
}
Objective-C
/*
* MapViewController.m
*/
- (void)viewDidLoad {
[super viewDidLoad];
...
self.mapView = [[GMTCMapView alloc] init];
self.mapView.delegate = self;
[self.view addSubview:self.mapView];
}
// Handle the callback when the GMTCMapView did initialized.
- (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview {
self.mapView.pickupLocation = self.selectedPickupLocation;
self.mapView.dropoffLocation = self.selectedDropoffLocation;
__weak __typeof(self) weakSelf = self;
[self startTripBookingWithPickupLocation:self.selectedPickupLocation
dropoffLocation:self.selectedDropoffLocation
completion:^(NSString *tripName, NSError *error) {
__typeof(self) strongSelf = weakSelf;
GMTCTripService *tripService = [GMTCServices sharedServices].tripService;
// Create a tripModel instance for listening to updates to the trip specified by this trip name.
GMTCTripModel *tripModel = [tripService tripModelForTripName:tripName];
// Create a journeySharingSession instance based on the tripModel.
GMTCJourneySharingSession *journeySharingSession =
[[GMTCJourneySharingSession alloc] initWithTripModel:tripModel];
// Add the journeySharingSession instance on the mapView for updating the UI.
[strongSelf.mapView showMapViewSession:journeySharingSession];
// Register for trip update events.
[tripModel registerSubscriber:self];
strongSelf.currentTripModel = tripModel;
strongSelf.currentJourneySharingSession = journeySharingSession;
[strongSelf hideLoadingView];
}];
[self showLoadingView];
}
진행 중인 이동 취소
다음 예는 현재 활성화된 이동을 재설정하는 방법을 보여줍니다.
Swift
/*
* MapViewController.swift
*/
func cancelCurrentActiveTrip() {
// Stop the tripModel
self.currentTripModel.unregisterSubscriber(self)
// Remove the journey sharing session from the mapView's UI stack.
self.mapView.hide(journeySharingSession)
}
Objective-C
/*
* MapViewController.m
*/
- (void)cancelCurrentActiveTrip {
// Stop the tripModel
[self.currentTripModel unregisterSubscriber:self];
// Remove the journey sharing session from the mapView's UI stack.
[self.mapView hideMapViewSession:journeySharingSession];
}
경로 업데이트 수신
다음 예는 tripModel
콜백을 등록하는 방법을 보여줍니다.
Swift
/*
* MapViewController.swift
*/
override func viewDidLoad() {
super.viewDidLoad()
// Register for trip update events.
self.currentTripModel.register(self)
}
Objective-C
/*
* MapViewController.m
*/
- (void)viewDidLoad {
[super viewDidLoad];
// Register for trip update events.
[self.currentTripModel registerSubscriber:self];
...
}
다음 예는 tripModel
콜백 등록을 취소하는 방법을 보여줍니다.
Swift
/*
* MapViewController.swift
*/
deinit {
self.currentTripModel.unregisterSubscriber(self)
}
Objective-C
/*
* MapViewController.m
*/
- (void)dealloc {
[self.currentTripModel unregisterSubscriber:self];
...
}
다음 예는 이동 상태가 업데이트될 때 콜백을 처리하기 위해 GMTCTripModelSubscriber
프로토콜을 구현하는 방법을 보여줍니다.
Swift
/*
* MapViewController.swift
*/
func tripModel(_: GMTCTripModel, didUpdate trip: GMTSTrip?, updatedPropertyFields: GMTSTripPropertyFields) {
// Update the UI with the new `trip` data.
self.updateUI(with: trip)
}
func tripModel(_: GMTCTripModel, didUpdate tripStatus: GMTSTripStatus) {
// Handle trip status did change.
}
func tripModel(_: GMTCTripModel, didUpdateActiveRouteRemainingDistance activeRouteRemainingDistance: Int32) {
// Handle remaining distance of active route did update.
}
func tripModel(_: GMTCTripModel, didUpdateActiveRoute activeRoute: [GMTSLatLng]?) {
// Handle trip active route did update.
}
func tripModel(_: GMTCTripModel, didUpdate vehicleLocation: GMTSVehicleLocation?) {
// Handle vehicle location did update.
}
func tripModel(_: GMTCTripModel, didUpdatePickupLocation pickupLocation: GMTSTerminalLocation?) {
// Handle pickup location did update.
}
func tripModel(_: GMTCTripModel, didUpdateDropoffLocation dropoffLocation: GMTSTerminalLocation?) {
// Handle drop off location did update.
}
func tripModel(_: GMTCTripModel, didUpdatePickupETA pickupETA: TimeInterval) {
// Handle the pickup ETA did update.
}
func tripModel(_: GMTCTripModel, didUpdateDropoffETA dropoffETA: TimeInterval) {
// Handle the drop off ETA did update.
}
func tripModel(_: GMTCTripModel, didUpdateRemaining remainingWaypoints: [GMTSTripWaypoint]?) {
// Handle updates to the pickup, dropoff or intermediate destinations of the trip.
}
func tripModel(_: GMTCTripModel, didFailUpdateTripWithError error: Error?) {
// Handle the error.
}
func tripModel(_: GMTCTripModel, didUpdateIntermediateDestinations intermediateDestinations: [GMTSTerminalLocation]?) {
// Handle the intermediate destinations being updated.
}
func tripModel(_: GMTCTripModel, didUpdateActiveRouteTraffic activeRouteTraffic: GMTSTrafficData?) {
// Handle trip active route traffic being updated.
}
Objective-C
/*
* MapViewController.m
*/
#pragma mark - GMTCTripModelSubscriber implementation
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateTrip:(nullable GMTSTrip *)trip
updatedPropertyFields:(enum GMTSTripPropertyFields)updatedPropertyFields {
// Update the UI with the new `trip` data.
[self updateUIWithTrip:trip];
...
}
- (void)tripModel:(GMTCTripModel *)tripModel didUpdateTripStatus:(enum GMTSTripStatus)tripStatus {
// Handle trip status did change.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateActiveRouteRemainingDistance:(int32_t)activeRouteRemainingDistance {
// Handle remaining distance of active route did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateActiveRoute:(nullable NSArray<GMTSLatLng *> *)activeRoute {
// Handle trip active route did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateVehicleLocation:(nullable GMTSVehicleLocation *)vehicleLocation {
// Handle vehicle location did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdatePickupLocation:(nullable GMTSTerminalLocation *)pickupLocation {
// Handle pickup location did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateDropoffLocation:(nullable GMTSTerminalLocation *)dropoffLocation {
// Handle drop off location did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel didUpdatePickupETA:(NSTimeInterval)pickupETA {
// Handle the pickup ETA did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateRemainingWaypoints:(nullable NSArray<GMTSTripWaypoint *> *)remainingWaypoints {
// Handle updates to the pickup, dropoff or intermediate destinations of the trip.
}
- (void)tripModel:(GMTCTripModel *)tripModel didUpdateDropoffETA:(NSTimeInterval)dropoffETA {
// Handle the drop off ETA did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel didFailUpdateTripWithError:(nullable NSError *)error {
// Handle the error.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateIntermediateDestinations:
(nullable NSArray<GMTSTerminalLocation *> *)intermediateDestinations {
// Handle the intermediate destinations being updated.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateActiveRouteTraffic:(nullable GMTSTrafficData *)activeRouteTraffic {
// Handle trip active route traffic being updated.
}
오류 처리
tripModel을 구독했는데 오류가 발생한 경우 대리자 메서드 tripModel(_:didFailUpdateTripWithError:)
를 구현하여 tripModel의 콜백을 가져올 수 있습니다. Fleet Engine은 Google Cloud 오류 표준을 따르는 오류 메시지를 생성했습니다. 오류 메시지 정의 및 모든 오류 코드에 대한 자세한 내용은 Google Cloud 오류 문서를 참조하세요.
특히 이동 모니터링의 경우 유효한 인증 토큰을 제공해야 합니다. 토큰이 만료된 경우와 같이 유효한 인증 사용자 인증 정보가 없으면 401 UNAUTHENTICATED
가 발생합니다.호출자가 특정 API를 호출할 권한이 없거나 (예: 소비자 역할이 있는 사용자가 updateTrip을 호출하려고 함) 요청에 유효한 car_id/trip_id가 없는 경우 403 PERMISSION_DENIED
가 발생합니다.
자세한 내용은 소비자 SDK 오류 처리를 참고하세요.
UI 맞춤설정
맞춤 다중선 UI 옵션 가져오기/설정
다음 예에서는 다중선의 맞춤 UI 옵션을 설정하는 방법을 보여줍니다.
Swift
/** MapViewController.swift */
func updatePolylineUIOptions() {
// The polyline type that you would like to set custom UI options for.
let customizablePolylineType = GMTCPolylineType.activeRoute
let polylineStyleOptions = GMTCMutablePolylineStyleOptions()
polylineStyleOptions.strokeWidth = 8.0
polylineStyleOptions.strokeColor = .blue
polylineStyleOptions.isVisible = true
polylineStyleOptions.zIndex = 1000
polylineStyleOptions.isGeodesic = true
let coordinator = self.mapView.consumerMapStyleCoordinator
coordinator.setPolylineStyleOptions(polylineStyleOptions, polylineType:customizablePolylineType)
}
Objective-C
/** MapViewController.m */
- (void)updatePolylineUIOptions {
// The polyline type that you would like to set custom UI options for.
GMTCPolylineType customizablePolylineType = GMTCPolylineTypeActiveRoute;
GMTCMutablePolylineStyleOptions *polylineStyleOptions =
[[GMTCMutablePolylineStyleOptions alloc] init];
polylineStyleOptions.strokeWidth = 8.0;
polylineStyleOptions.strokeColor = [UIColor blueColor];
polylineStyleOptions.isVisible = YES;
polylineStyleOptions.zIndex = 1000;
polylineStyleOptions.isGeodesic = YES;
[[_mapView consumerMapStyleCoordinator] setPolylineStyleOptions:polylineStyleOptions
polylineType:customizablePolylineType];
}
맞춤 마커 UI 옵션 가져오기/설정
다음 예는 마커의 맞춤 UI 옵션을 설정하는 방법을 보여줍니다.
Swift
/** MapViewController.swift */
func updateMarkerUIOptions() {
let customizableMarkerType = GMTCCustomizableMarkerType.tripVehicle
let markerStyleOptions = GMTCMutableMarkerStyleOptions()
markerStyleOptions.groundAnchor = groundAnchor
markerStyleOptions.isVisible = true
markerStyleOptions.icon = icon
markerStyleOptions.zIndex = 100
markerStyleOptions.isFlat = false
let coordinator = self.mapView.consumerMapStyleCoordinator
coordinator.setMarkerStyleOptions(markerStyleOptions, markerType: customizableMarkerType)
}
Objective-C
/** MapViewController.m */
- (void)updateMarkerUIOptions {
// The marker type that you would like to set custom UI options for.
GMTCCustomizableMarkerType customizableMarkerType = GMTCCustomizableMarkerTypeTripVehicle;
GMTCMutableMarkerStyleOptions *markerStyleOptions =
[[GMTCMutableMarkerStyleOptions alloc] init];
markerStyleOptions.groundAnchor = groundAnchor;
markerStyleOptions.isVisible = YES;
markerStyleOptions.icon = icon;
markerStyleOptions.zIndex = 100;
markerStyleOptions.isFlat = NO;
[[_mapView consumerMapStyleCoordinator] setMarkerStyleOptions:markerStyleOptions markerType:customizableMarkerType];
}
카메라 확대/축소 조정
iOS용 Maps SDK의 내 위치 버튼은 카메라가 기기 위치의 중앙에 오도록 합니다.
활성 탐색 여정 공유 세션이 있는 경우 기기 위치뿐만 아니라 여정에 초점을 맞추도록 카메라를 설정할 수 있습니다.
소비자 SDK는 기본적으로 사용 설정된 자동 카메라 기능을 제공합니다. 카메라가 확대/축소하여 여정 공유 경로와 다음 경로 경유지에 초점을 맞춥니다.
카메라 동작을 더 세밀하게 제어해야 하는 경우 isAllowCameraAutoUpdate
속성을 사용하여 자동 카메라 기능을 사용 중지하거나 사용 설정할 수 있습니다.
카메라 맞춤설정에 대한 자세한 내용은 iOS용 Maps SDK 카메라 이동을 참고하세요.