处理标记事件

此示例显示了一个包含两个标记的地图。点按某个标记后,相机会缩放和旋转,以聚焦于所选标记。

开始使用

您必须先配置开发环境,然后才能试用该示例代码。如需了解详情,请参阅 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
      

在本地运行完整示例应用

Maps SDK for iOS 示例应用以 GitHub 上的下载归档文件的形式提供。请按照以下步骤安装并试用 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 中,按 compile 按钮使用当前架构构建应用。构建引发错误,提示您在 Swift 的 SDKConstants.swift 文件或 Objective-C 的 SDKDemoAPIKey.h 文件中输入 API 密钥。
  4. 如果您尚未获得 API 密钥,请按照说明在 Google Cloud 控制台中设置项目并获取 API 密钥。在 Cloud 控制台中配置密钥时,您可以将密钥限制为示例应用的软件包标识符,以确保只有您的应用可以使用该密钥。SDK 示例应用的默认 bundle 标识符为 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 获取您的位置信息,请选择允许