處理標記事件

這個範例會顯示含有兩個標記的地圖。輕觸標記時,相機會縮放及旋轉,將焦點放在所選標記上。

開始使用

請務必先設定開發環境,再試用程式碼範例。詳情請參閱 Maps SDK for iOS 程式碼範例

查看程式碼

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
      

在本機執行完整的範例應用程式

您可以從 GitHub 下載封存檔,取得 Maps SDK for iOS 範例應用程式。請按照下列步驟安裝及試用 Maps SDK for iOS 範例應用程式。

  1. 執行 git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git 將範例存放區複製到本機目錄。
  2. 開啟終端機視窗,前往複製範例檔案的目錄,然後深入 GoogleMaps 目錄:

    Swift

    cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift
    pod install
    open GoogleMapsSwiftDemos.xcworkspace

    Objective-C

    cd maps-sdk-for-ios-samples-main/GoogleMaps
    pod install
    open GoogleMapsDemos.xcworkspace
  3. 在 Xcode 中按下編譯按鈕,即可使用目前的配置建構應用程式。建構作業會產生錯誤,提示您在 SDKConstants.swift 檔案 (Swift) 或 SDKDemoAPIKey.h 檔案 (Objective-C) 中輸入 API 金鑰。
  4. 如果您尚未取得 API 金鑰,請按照操作說明在 Google Cloud 控制台中設定專案並取得 API 金鑰。在 Cloud 控制台中設定金鑰時,您可以限制金鑰,僅允許範例應用程式的軟體包 ID 使用金鑰,確保只有您的應用程式可以使用金鑰。SDK 範例應用程式的預設套件 ID 為 com.example.GoogleMapsDemos
  5. 編輯 Swift 的 SDKConstants.swift 檔案或 Objective-C 的 SDKDemoAPIKey.h 檔案,然後將 API 金鑰貼到 apiKeykAPIKey 常數的定義中。例如:

    Swift

    static let apiKey = "YOUR_API_KEY"

    Objective-C

    static NSString *const kAPIKey = @"YOUR_API_KEY";
  6. 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.
  7. 建構並執行專案。iOS 模擬器視窗隨即顯示 Maps SDK 示範清單。
  8. 選擇其中一個顯示的選項,即可試用 Maps SDK for iOS 的功能。
  9. 如果系統提示您允許 GoogleMapsDemos 存取您的位置,請選擇「允許」