이 예시에서는 마커가 두 개 있는 지도를 표시합니다. 마커를 탭하면 카메라가 확대되고 회전하여 선택한 마커에 초점을 맞춥니다.
시작하기
샘플 코드를 사용하기 전에 개발 환경을 구성해야 합니다. 자세한 내용은 iOS용 Maps SDK 코드 샘플을 참고하세요.
코드 보기
Swift
import GoogleMaps import UIKit final class MarkerEventsViewController: UIViewController { private lazy var mapView: GMSMapView = { let camera = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4) return GMSMapView(frame: .zero, camera: camera) }() private var melbourneMarker = GMSMarker( position: CLLocationCoordinate2D(latitude: -37.81969, longitude: 144.966085)) override func loadView() { let sydneyMarker = GMSMarker( position: CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086)) sydneyMarker.map = mapView melbourneMarker.map = mapView mapView.delegate = self view = mapView } } extension MarkerEventsViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? { if marker == melbourneMarker { return UIImageView(image: UIImage(named: "Icon")) } return nil } func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { // Animate to the marker CATransaction.begin() CATransaction.setAnimationDuration(3) let camera = GMSCameraPosition(target: marker.position, zoom: 8, bearing: 50, viewingAngle: 60) mapView.animate(to: camera) CATransaction.commit() // Melbourne marker has a InfoWindow so return false to allow markerInfoWindow to // fire. Also check that the marker isn't already selected so that the InfoWindow // doesn't close. if marker == melbourneMarker && mapView.selectedMarker != melbourneMarker { return false } return true } }
Objective-C
#import "GoogleMapsDemos/Samples/MarkerEventsViewController.h" #import <QuartzCore/QuartzCore.h> #import <GoogleMaps/GoogleMaps.h> @implementation MarkerEventsViewController { GMSMapView *_mapView; GMSMarker *_melbourneMarker; BOOL _rotating; } - (void)viewDidLoad { [super viewDidLoad]; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-37.81969 longitude:144.966085 zoom:4]; _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera]; GMSMarker *sydneyMarker = [[GMSMarker alloc] init]; sydneyMarker.position = CLLocationCoordinate2DMake(-33.8683, 151.2086); sydneyMarker.map = _mapView; _melbourneMarker = [[GMSMarker alloc] init]; _melbourneMarker.position = CLLocationCoordinate2DMake(-37.81969, 144.966085); _melbourneMarker.map = _mapView; _mapView.delegate = self; self.view = _mapView; } #pragma mark - GMSMapViewDelegate - (UIView *)mapView:(GMSMapView *)mapView markerInfoWindow:(GMSMarker *)marker { if (marker == _melbourneMarker) { return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Icon"]]; } return nil; } - (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker { GMSCameraPosition *camera = [[GMSCameraPosition alloc] initWithTarget:marker.position zoom:8 bearing:50 viewingAngle:60]; // Animate to the marker [CATransaction begin]; [CATransaction setAnimationDuration:3.f]; // 3 second animation [CATransaction setCompletionBlock:^{ if (_rotating) { // Animation was interrupted by orientation change. [CATransaction setDisableActions:true]; // Disable animation to avoid interruption from rotation. [_mapView animateToCameraPosition:camera]; } }]; [mapView animateToCameraPosition:camera]; [CATransaction commit]; // Melbourne marker has a InfoWindow so return NO to allow markerInfoWindow to fire. Also check // that the marker isn't already selected so that the InfoWindow doesn't close. if (marker == _melbourneMarker && mapView.selectedMarker != _melbourneMarker) { return NO; } // The Tap has been handled so return YES return YES; } - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { _rotating = true; [coordinator animateAlongsideTransition:nil completion:^( id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { _rotating = false; }]; [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; } @end
로컬에서 전체 샘플 앱 실행
iOS용 Maps SDK 샘플 앱은 GitHub에서 다운로드 아카이브로 제공됩니다. 다음 단계에 따라 iOS용 Maps SDK 샘플 앱을 설치하고 사용해 보세요.
git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git를 실행하여 샘플 저장소를 로컬 디렉터리에 클론합니다.터미널 창을 열고 샘플 파일을 클론한 디렉터리로 이동한 후 GoogleMaps 디렉터리로 이동합니다.
Swift
cd maps-sdk-for-ios-samples/GoogleMaps-Swift
open GoogleMapsSwiftXCFrameworkDemos.xcodeprojObjective-C
cd maps-sdk-for-ios-samples-main/GoogleMaps
open GoogleMapsDemos.xcodeproj- Xcode 프로젝트에서 File(파일) > Add Package Dependencies(패키지 종속 항목 추가)로 이동합니다.
URL로
https://github.com/googlemaps/ios-maps-sdk를 입력하고 Enter를 눌러 패키지를 가져온 다음 패키지 추가를 클릭합니다. - Xcode에서 컴파일 버튼을 눌러 현재 스키마로 앱을 빌드합니다. 빌드에서 오류가 발생하여 Swift의 경우
SDKConstants.swift파일에, Objective-C의 경우SDKDemoAPIKey.h파일에 API 키를 입력하라는 메시지가 표시됩니다. - iOS용 Maps SDK가 사용 설정된 프로젝트에서 API 키를 가져옵니다.
- Swift의 경우
SDKConstants.swift파일을, Objective-C의 경우SDKDemoAPIKey.h파일을 수정하고apiKey또는kAPIKey상수의 정의에 API 키를 붙여넣습니다. 예를 들면 다음과 같습니다.Swift
static let apiKey = "YOUR_API_KEY"
Objective-C
static NSString *const kAPIKey = @"YOUR_API_KEY";
SDKConstants.swift파일(Swift) 또는SDKDemoAPIKey.h파일(Objective-C)에서 다음 줄을 삭제합니다. 이 줄은 사용자 정의 문제를 등록하는 데 사용되기 때문입니다.Swift
#error (Register for API Key and insert here. Then delete this line.)
Objective-C
#error Register for API Key and insert here.- 프로젝트를 빌드하고 실행합니다. iOS 시뮬레이터 창이 표시되고 Maps SDK Demos 목록이 표시됩니다.
- 표시된 옵션 중 하나를 선택하여 iOS용 Maps SDK의 기능을 실험해 봅니다.
- GoogleMapsDemos에서 내 위치에 액세스하도록 허용하라는 메시지가 표시되면 허용을 선택합니다.