마커 이벤트 처리

이 예에서는 마커가 두 개 있는 지도를 표시합니다. 마커를 탭하면 카메라가 확대/축소 및 회전하여 선택한 마커에 초점을 맞춥니다.

시작하기

샘플 코드를 사용하기 전에 개발 환경을 구성해야 합니다. 자세한 내용은 iOS용 Maps SDK 코드 샘플을 참고하세요.

코드 보기

SwiftObjective-C
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
  }
}
      
#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 샘플 앱을 설치하고 사용해 보세요.

  1. git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git를 실행하여 샘플 저장소를 로컬 디렉터리에 클론합니다.
  2. 터미널 창을 열고 샘플 파일을 클론한 디렉터리로 이동한 다음 GoogleMaps 디렉터리로 드릴다운합니다.

    SwiftObjective-C
    cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift
    pod install
    open GoogleMapsSwiftDemos.xcworkspace
    cd maps-sdk-for-ios-samples-main/GoogleMaps
    pod install
    open GoogleMapsDemos.xcworkspace
  3. Xcode에서 컴파일 버튼을 눌러 현재 스키마로 앱을 빌드합니다. 빌드 오류가 발생하여 Swift의 경우 SDKConstants.swift 파일에, Objective-C의 경우 SDKDemoAPIKey.h 파일에 API 키를 입력하라는 메시지가 표시됩니다.
  4. 아직 API 키가 없는 경우 안내에 따라 Google Cloud 콘솔에서 프로젝트를 설정하고 API 키를 가져옵니다. Cloud 콘솔에서 키를 구성할 때 샘플 앱의 번들 식별자로 키를 제한하여 앱에서만 키를 사용할 수 있도록 할 수 있습니다. SDK 샘플 앱의 기본 번들 식별자는 com.example.GoogleMapsDemos입니다.
  5. Swift의 경우 SDKConstants.swift 파일을 수정하고 Objective-C의 경우 SDKDemoAPIKey.h 파일을 수정한 후 apiKey 또는 kAPIKey 상수의 정의에 API 키를 붙여넣습니다. 예를 들면 다음과 같습니다.
    SwiftObjective-C
    static let apiKey = "YOUR_API_KEY"
    static NSString *const kAPIKey = @"YOUR_API_KEY";
  6. SDKConstants.swift 파일 (Swift) 또는 SDKDemoAPIKey.h 파일 (Objective-C)에서 다음 줄을 삭제합니다. 이 줄은 사용자 정의 문제를 등록하는 데 사용됩니다.
    SwiftObjective-C
    #error (Register for API Key and insert here. Then delete this line.)
    #error Register for API Key and insert here.
  7. 프로젝트를 빌드하고 실행합니다. iOS 시뮬레이터 창이 표시되고 Maps SDK 데모 목록이 표시됩니다.
  8. 표시된 옵션 중 하나를 선택하여 iOS용 Maps SDK의 기능을 실험합니다.
  9. GoogleMapsDemos에서 내 위치에 액세스하도록 허용하라는 메시지가 표시되면 허용을 선택합니다.