이벤트

플랫폼 선택: Android iOS JavaScript

iOS용 Maps SDK를 사용하면 카메라 변경 이벤트 또는 마커 탭 이벤트 등 지도에서 발생하는 이벤트를 리슨할 수 있습니다.

소개

이벤트를 리슨하려면 GMSMapViewDelegate 프로토콜을 구현해야 합니다. 일반적으로 이 프로토콜은 지도를 표시하는 뷰 컨트롤러에 구현합니다. 아래 예시를 참조하세요.

Swift

import GoogleMaps

class Events: UIViewController, GMSMapViewDelegate {
  // ...
}
      

Objective-C

@import GoogleMaps;

@interface Events : UIViewController <GMSMapViewDelegate>

@end
      

GMSMapView가 생성되면 뷰 컨트롤러에 대리자를 설정할 수 있습니다. GMSMapViewDelegate는 선택적 메서드만 제공합니다. 특정 이벤트를 리슨하려면 관련 메서드를 구현해야 합니다.

Swift

override func loadView() {
  super.loadView()
  let camera = GMSCameraPosition.camera(
    withLatitude: 1.285,
    longitude: 103.848,
    zoom: 12
  )
  let options = GMSMapViewOptions()
  options.camera = camera
  let mapView = GMSMapView(options: options)
  mapView.delegate = self
  self.view = mapView
}

// MARK: GMSMapViewDelegate

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
  print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}
      

Objective-C

- (void)loadView {
  [super loadView];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:1.285
                                                          longitude:103.848
                                                               zoom:12];
  GMSMapViewOptions *options = [[GMSMapViewOptions alloc] init];
  options.camera = camera;
  GMSMapView *mapView = [[GMSMapView alloc] initWithOptions:options];
  mapView.delegate = self;
  self.view = mapView;
}

#pragma mark - GMSMapViewDelegate

- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
  NSLog(@"You tapped at %f,%f", coordinate.latitude, coordinate.longitude);
}
      

카메라 위치

GMSMapViewDelegate를 사용하면 지도를 렌더링하는 데 사용되는 카메라 위치의 변경사항을 리슨할 수 있습니다. 세 가지 고유한 이벤트가 있습니다.

  • mapView:willMove:: 카메라 위치가 변경되려고 함을 나타냅니다. gesture 인수가 YES로 설정된 경우 이는 사용자가 GMSMapView에서 이동 또는 기울이기와 같은 자연스러운 동작을 실행했기 때문입니다. 그렇지 않으면 NO는 프로그래매틱 변경의 일부임을 나타냅니다. 예를 들어 animateToCameraPosition:과 같은 메서드를 사용하거나 지도 레이어를 직접 업데이트하는 경우입니다. 사용자가 카메라를 변경하는 애니메이션을 생성하는 내 위치 또는 나침반 버튼을 탭한 경우에도 NO일 수 있습니다.

    이 메서드는 mapView:idleAtCameraPosition:이 호출되기 전에 여러 번 호출될 수 있지만 일반적으로 애니메이션과 동작이 동시에 발생하는 경우에만 발생합니다. 예를 들어 동작은 현재 애니메이션을 취소하고 mapView:willMove:를 두 번째로 호출합니다.

  • mapView:didChangeCameraPosition: : 동작 또는 애니메이션 중에 mapView:willMove: 호출 후 항상 반복적으로 호출됩니다. 중간 카메라 위치가 전달됩니다.

  • 마지막으로 GMSMapView의 카메라 위치가 유휴 상태가 되면 mapView:idleAtCameraPosition:이 호출되고 관련 카메라 위치를 지정합니다. 이 시점에서 모든 애니메이션과 제스처가 중단됩니다.

    애플리케이션은 예를 들어 카메라가 변경될 때마다 콘텐츠를 다시 로드하는 대신 이 이벤트를 사용하여 GMSMapView에 표시되는 마커 또는 기타 콘텐츠를 새로고침할 수 있습니다.

예를 들어 애플리케이션은 이동 시 GMSMapView를 지우고 카메라가 정지하는 위치를 역지오코딩할 수 있습니다.

Swift

let geocoder = GMSGeocoder()

func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
  mapView.clear()
}

func mapView(_ mapView: GMSMapView, idleAt cameraPosition: GMSCameraPosition) {
    geocoder.reverseGeocodeCoordinate(cameraPosition.target) { (response, error) in
      guard error == nil else {
        return
      }

      if let result = response?.firstResult() {
        let marker = GMSMarker()
        marker.position = cameraPosition.target
        marker.title = result.lines?[0]
        marker.snippet = result.lines?[1]
        marker.map = mapView
      }
    }
  }
      

Objective-C

static GMSGeocoder *geocoder;

- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
  [mapView clear];
}

- (void)mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)cameraPosition {
  id handler = ^(GMSReverseGeocodeResponse *response, NSError *error) {
    if (error != nil) {
      return;
    }
    GMSReverseGeocodeResult *result = response.firstResult;
    GMSMarker *marker = [GMSMarker markerWithPosition:cameraPosition.target];
    marker.title = result.lines[0];
    marker.snippet = result.lines[1];
    marker.map = mapView;
  };
  [geocoder reverseGeocodeCoordinate:cameraPosition.target completionHandler:handler];
}
      

비즈니스 및 기타 관심 장소의 이벤트

기본적으로, 관심 지점 (POI)은 해당 아이콘과 함께 기본 지도에 나타납니다. POI에는 공원, 학교, 정부 건물 등 뿐만 아니라 상점, 식당, 호텔 등의 사업체 POI가 포함됩니다.

관심 장소의 클릭 이벤트에 응답할 수 있습니다. 비즈니스 및 기타 관심 장소 가이드를 참고하세요.

기타 이벤트

GMSMapViewDelegate의 전체 메서드 목록을 알아보려면 참조 가이드를 참고하세요.