在地图上绘制多段线

显示南太平洋地图,其中红色和绿色多段线的动画会更改其位置和大小。

开始使用

您必须先配置开发环境,然后才能试用该示例代码。如需了解详情,请参阅 Maps SDK for iOS 代码示例

查看代码

Swift

import GoogleMaps
import UIKit

final class PolylinesViewController: UIViewController {
  private lazy var styles: [GMSStrokeStyle] = {
    let greenStyle = GMSStrokeStyle.gradient(from: .green, to: UIColor.green.withAlphaComponent(0))
    let redStyle = GMSStrokeStyle.gradient(from: UIColor.red.withAlphaComponent(0), to: .red)
    return [greenStyle, redStyle, GMSStrokeStyle.solidColor(UIColor(white: 0, alpha: 0))]
  }()
  private var pathLength: Double = 0
  private var pos: Double = 0
  private var polylines: [GMSPolyline] = []

  private lazy var mapView: GMSMapView = {
    let camera = GMSCameraPosition(latitude: -30, longitude: -175, zoom: 3)
    return GMSMapView(frame: .zero, camera: camera)
  }()

  override func loadView() {
    view = mapView
    mapView.accessibilityElementsHidden = true
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    var path = GMSMutablePath()
    path.addLatitude(-33.866901, longitude: 151.195988)
    path.addLatitude(-18, longitude: 179)
    path.addLatitude(21.291982, longitude: -157.821856)
    path.addLatitude(37.423802, longitude: -122.091859)
    path.addLatitude(-12, longitude: -77)
    path.addLatitude(-33.866901, longitude: 151.195988)
    path = path.pathOffset(byLatitude: -30, longitude: 0)
    pathLength = path.length(of: .geodesic) / 21
    for i in 0..<30 {
      let polyline = GMSPolyline(path: path.pathOffset(byLatitude: Double(i) * 1.5, longitude: 0))
      polyline.strokeWidth = 8
      polyline.geodesic = true
      polyline.map = mapView
      polylines.append(polyline)
    }
    animatePath()
  }

  // Updates the path style every 0.1 seconds.
  private func animatePath() {
    polylines.forEach {
      if let path = $0.path {
        $0.spans = GMSStyleSpansOffset(path, styles, [NSNumber(value: pathLength)], .geodesic, pos)
      }
    }
    pos -= 50000

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
      self.animatePath()
    }
  }
}
      

Objective-C

#import "GoogleMapsDemos/Samples/PolylinesViewController.h"

#import <GoogleMaps/GoogleMaps.h>

static CLLocationCoordinate2D kSydneyAustralia = {-33.866901, 151.195988};
static CLLocationCoordinate2D kHawaiiUSA = {21.291982, -157.821856};
static CLLocationCoordinate2D kFiji = {-18, 179};
static CLLocationCoordinate2D kMountainViewUSA = {37.423802, -122.091859};
static CLLocationCoordinate2D kLimaPeru = {-12, -77};
static bool kAnimate = true;

@implementation PolylinesViewController {
  NSArray *_styles;
  NSArray *_lengths;
  NSArray *_polys;
  double _pos, _step;
  GMSMapView *_mapView;
}

- (void)tick {
  for (GMSPolyline *poly in _polys) {
    poly.spans = GMSStyleSpansOffset(poly.path, _styles, _lengths, kGMSLengthGeodesic, _pos);
  }
  _pos -= _step;
  if (kAnimate) {
    __weak id weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 10), dispatch_get_main_queue(),
                   ^{
                     [weakSelf tick];
                   });
  }
}

- (void)initLines {
  if (!_polys) {
    NSMutableArray *polys = [NSMutableArray array];
    GMSMutablePath *path = [GMSMutablePath path];
    [path addCoordinate:kSydneyAustralia];
    [path addCoordinate:kFiji];
    [path addCoordinate:kHawaiiUSA];
    [path addCoordinate:kMountainViewUSA];
    [path addCoordinate:kLimaPeru];
    [path addCoordinate:kSydneyAustralia];
    path = [path pathOffsetByLatitude:-30 longitude:0];
    _lengths = @[ @([path lengthOfKind:kGMSLengthGeodesic] / 21) ];
    for (int i = 0; i < 30; ++i) {
      GMSPolyline *poly = [[GMSPolyline alloc] init];
      poly.path = [path pathOffsetByLatitude:(i * 1.5) longitude:0];
      poly.strokeWidth = 8;
      poly.geodesic = YES;
      poly.map = _mapView;
      [polys addObject:poly];
    }
    _polys = polys;
  }
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-30 longitude:-175 zoom:3];
  GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  mapView.accessibilityElementsHidden = YES;
  self.view = mapView;
  _mapView = mapView;

  CGFloat alpha = 1;
  UIColor *green = [UIColor colorWithRed:0 green:1 blue:0 alpha:alpha];
  UIColor *greenTransp = [UIColor colorWithRed:0 green:1 blue:0 alpha:0];
  UIColor *red = [UIColor colorWithRed:1 green:0 blue:0 alpha:alpha];
  UIColor *redTransp = [UIColor colorWithRed:1 green:0 blue:0 alpha:0];
  GMSStrokeStyle *grad1 = [GMSStrokeStyle gradientFromColor:green toColor:greenTransp];
  GMSStrokeStyle *grad2 = [GMSStrokeStyle gradientFromColor:redTransp toColor:red];
  _styles = @[
    grad1,
    grad2,
    [GMSStrokeStyle solidColor:[UIColor colorWithWhite:0 alpha:0]],
  ];
  _step = 50000;
  [self initLines];
  [self tick];
}

@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 中,按下“编译”按钮,使用当前方案构建应用。构建会产生错误,提示您在 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 文件,然后将您的 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 访问您的位置信息,请选择允许