Включить и отключить жесты карты, Включить и отключить жесты карты, Включить и отключить жесты карты, Включить и отключить жесты карты

Карта реагирует на жесты масштабирования только тогда, когда переключатель включен.

Начать

Прежде чем вы сможете опробовать пример кода, вам необходимо настроить среду разработки. Дополнительную информацию см . в примерах кода Maps SDK для iOS .

Посмотреть код

Быстрый

import GoogleMaps
import UIKit

class GestureControlViewController: UIViewController {
  private let holderHeight: CGFloat = 60
  private let zoomLabelInset: CGFloat = 16

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

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(mapView)

    let holder = UIView(frame: .zero)
    holder.backgroundColor = UIColor(white: 1, alpha: 0.8)
    view.addSubview(holder)

    let zoomLabel = UILabel(frame: .zero)
    zoomLabel.text = "Zoom gestures"
    zoomLabel.font = .boldSystemFont(ofSize: 18)
    holder.addSubview(zoomLabel)

    // Control zooming.
    holder.addSubview(zoomSwitch)
    zoomSwitch.addTarget(self, action: #selector(toggleZoom), for: .valueChanged)
    zoomSwitch.isOn = true

    [mapView, holder, zoomLabel, zoomSwitch].forEach({
      $0.translatesAutoresizingMaskIntoConstraints = false
    })
    NSLayoutConstraint.activate([
      mapView.leftAnchor.constraint(equalTo: view.leftAnchor),
      mapView.rightAnchor.constraint(equalTo: view.rightAnchor),
      mapView.topAnchor.constraint(equalTo: view.topAnchor),
      mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
      holder.heightAnchor.constraint(equalToConstant: holderHeight),
      holder.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      holder.widthAnchor.constraint(equalTo: view.widthAnchor),
      zoomLabel.leftAnchor.constraint(equalTo: holder.leftAnchor, constant: zoomLabelInset),
      zoomLabel.centerYAnchor.constraint(equalTo: holder.centerYAnchor),
      zoomSwitch.rightAnchor.constraint(equalTo: holder.rightAnchor, constant: -zoomLabelInset),
      zoomSwitch.centerYAnchor.constraint(
        equalTo: holder.centerYAnchor),
    ])
    NSLayoutConstraint.activate([
      holder.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
    ])
  }

  @objc func toggleZoom() {
    mapView.settings.zoomGestures = zoomSwitch.isOn
  }

}
      

Цель-C

#import "GoogleMapsDemos/Samples/GestureControlViewController.h"

#import <GoogleMaps/GoogleMaps.h>

@implementation GestureControlViewController {
  GMSMapView *_mapView;
  UISwitch *_zoomSwitch;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-25.5605
                                                          longitude:133.605097
                                                               zoom:3];

  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  _mapView.accessibilityIdentifier = @"gestureControlDemoMapView";

  self.view = [[UIView alloc] initWithFrame:CGRectZero];
  [self.view addSubview:_mapView];

  UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 59)];
  holder.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
  holder.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8f];
  [self.view addSubview:holder];

  // Zoom label.
  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, 200, 29)];
  label.text = @"Zooming?";
  label.font = [UIFont boldSystemFontOfSize:18.0f];
  label.textAlignment = NSTextAlignmentLeft;
  label.backgroundColor = [UIColor clearColor];
  label.layer.shadowColor = [[UIColor whiteColor] CGColor];
  label.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
  label.layer.shadowOpacity = 1.0f;
  label.layer.shadowRadius = 0.0f;
  [holder addSubview:label];

  // Control zooming.
  _zoomSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(-90, 16, 0, 0)];
  _zoomSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
  [_zoomSwitch addTarget:self
                  action:@selector(didChangeZoomSwitch)
        forControlEvents:UIControlEventValueChanged];
  _zoomSwitch.on = YES;
  [holder addSubview:_zoomSwitch];
}

- (void)didChangeZoomSwitch {
  _mapView.settings.zoomGestures = _zoomSwitch.isOn;
}

@end
      

Запустите полный пример приложения локально

Пример приложения Maps SDK для iOS доступен в виде архива для загрузки на GitHub . Выполните следующие действия, чтобы установить и опробовать пример приложения Maps SDK для iOS.

  1. Запустите git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git , чтобы клонировать репозиторий образцов в локальный каталог.
  2. Откройте окно терминала, перейдите в каталог, в который вы клонировали файлы примеров, и перейдите к каталогу GoogleMaps:

    Быстрый

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

    Цель-C

    cd maps-sdk-for-ios-samples-main/GoogleMaps
    pod install
    open GoogleMapsDemos.xcworkspace
  3. В Xcode нажмите кнопку компиляции, чтобы создать приложение с текущей схемой. При сборке возникает ошибка, предлагающая ввести ключ API в файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C.
  4. Если у вас еще нет ключа API, следуйте инструкциям , чтобы настроить проект в Google Cloud Console и получить ключ API. При настройке ключа в Cloud Console вы можете ограничить ключ идентификатором пакета примера приложения, чтобы гарантировать, что только ваше приложение может использовать ключ. Идентификатор пакета по умолчанию для примера приложения SDK — com.example.GoogleMapsDemos .
  5. Отредактируйте файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C и вставьте свой ключ API в определение константы apiKey или kAPIKey . Например:

    Быстрый

    static let apiKey = "YOUR_API_KEY"

    Цель-C

    static NSString *const kAPIKey = @"YOUR_API_KEY";
  6. В файле SDKConstants.swift (Swift) или файле SDKDemoAPIKey.h (Objective-C) удалите следующую строку, поскольку она используется для регистрации определяемой пользователем проблемы:

    Быстрый

    #error (Register for API Key and insert here. Then delete this line.)

    Цель-C

    #error Register for API Key and insert here.
  7. Создайте и запустите проект. Появится окно симулятора iOS со списком демонстрационных версий Maps SDK .
  8. Выберите один из отображаемых вариантов, чтобы поэкспериментировать с функцией Maps SDK для iOS.
  9. Если будет предложено разрешить GoogleMapsDemos доступ к вашему местоположению, выберите «Разрешить» .
,
Карта реагирует на жесты масштабирования только тогда, когда переключатель включен.

Начать

Прежде чем вы сможете опробовать пример кода, вам необходимо настроить среду разработки. Дополнительную информацию см . в примерах кода Maps SDK для iOS .

Посмотреть код

Быстрый

import GoogleMaps
import UIKit

class GestureControlViewController: UIViewController {
  private let holderHeight: CGFloat = 60
  private let zoomLabelInset: CGFloat = 16

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

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(mapView)

    let holder = UIView(frame: .zero)
    holder.backgroundColor = UIColor(white: 1, alpha: 0.8)
    view.addSubview(holder)

    let zoomLabel = UILabel(frame: .zero)
    zoomLabel.text = "Zoom gestures"
    zoomLabel.font = .boldSystemFont(ofSize: 18)
    holder.addSubview(zoomLabel)

    // Control zooming.
    holder.addSubview(zoomSwitch)
    zoomSwitch.addTarget(self, action: #selector(toggleZoom), for: .valueChanged)
    zoomSwitch.isOn = true

    [mapView, holder, zoomLabel, zoomSwitch].forEach({
      $0.translatesAutoresizingMaskIntoConstraints = false
    })
    NSLayoutConstraint.activate([
      mapView.leftAnchor.constraint(equalTo: view.leftAnchor),
      mapView.rightAnchor.constraint(equalTo: view.rightAnchor),
      mapView.topAnchor.constraint(equalTo: view.topAnchor),
      mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
      holder.heightAnchor.constraint(equalToConstant: holderHeight),
      holder.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      holder.widthAnchor.constraint(equalTo: view.widthAnchor),
      zoomLabel.leftAnchor.constraint(equalTo: holder.leftAnchor, constant: zoomLabelInset),
      zoomLabel.centerYAnchor.constraint(equalTo: holder.centerYAnchor),
      zoomSwitch.rightAnchor.constraint(equalTo: holder.rightAnchor, constant: -zoomLabelInset),
      zoomSwitch.centerYAnchor.constraint(
        equalTo: holder.centerYAnchor),
    ])
    NSLayoutConstraint.activate([
      holder.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
    ])
  }

  @objc func toggleZoom() {
    mapView.settings.zoomGestures = zoomSwitch.isOn
  }

}
      

Цель-C

#import "GoogleMapsDemos/Samples/GestureControlViewController.h"

#import <GoogleMaps/GoogleMaps.h>

@implementation GestureControlViewController {
  GMSMapView *_mapView;
  UISwitch *_zoomSwitch;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-25.5605
                                                          longitude:133.605097
                                                               zoom:3];

  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  _mapView.accessibilityIdentifier = @"gestureControlDemoMapView";

  self.view = [[UIView alloc] initWithFrame:CGRectZero];
  [self.view addSubview:_mapView];

  UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 59)];
  holder.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
  holder.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8f];
  [self.view addSubview:holder];

  // Zoom label.
  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, 200, 29)];
  label.text = @"Zooming?";
  label.font = [UIFont boldSystemFontOfSize:18.0f];
  label.textAlignment = NSTextAlignmentLeft;
  label.backgroundColor = [UIColor clearColor];
  label.layer.shadowColor = [[UIColor whiteColor] CGColor];
  label.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
  label.layer.shadowOpacity = 1.0f;
  label.layer.shadowRadius = 0.0f;
  [holder addSubview:label];

  // Control zooming.
  _zoomSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(-90, 16, 0, 0)];
  _zoomSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
  [_zoomSwitch addTarget:self
                  action:@selector(didChangeZoomSwitch)
        forControlEvents:UIControlEventValueChanged];
  _zoomSwitch.on = YES;
  [holder addSubview:_zoomSwitch];
}

- (void)didChangeZoomSwitch {
  _mapView.settings.zoomGestures = _zoomSwitch.isOn;
}

@end
      

Запустите полный пример приложения локально

Пример приложения Maps SDK для iOS доступен в виде архива для загрузки на GitHub . Выполните следующие действия, чтобы установить и опробовать пример приложения Maps SDK для iOS.

  1. Запустите git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git , чтобы клонировать репозиторий образцов в локальный каталог.
  2. Откройте окно терминала, перейдите в каталог, в который вы клонировали файлы примеров, и перейдите к каталогу GoogleMaps:

    Быстрый

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

    Цель-C

    cd maps-sdk-for-ios-samples-main/GoogleMaps
    pod install
    open GoogleMapsDemos.xcworkspace
  3. В Xcode нажмите кнопку компиляции, чтобы создать приложение с текущей схемой. При сборке возникает ошибка, предлагающая ввести ключ API в файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C.
  4. Если у вас еще нет ключа API, следуйте инструкциям , чтобы настроить проект в Google Cloud Console и получить ключ API. При настройке ключа в Cloud Console вы можете ограничить ключ идентификатором пакета примера приложения, чтобы гарантировать, что только ваше приложение может использовать ключ. Идентификатор пакета по умолчанию для примера приложения SDK — com.example.GoogleMapsDemos .
  5. Отредактируйте файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C и вставьте свой ключ API в определение константы apiKey или kAPIKey . Например:

    Быстрый

    static let apiKey = "YOUR_API_KEY"

    Цель-C

    static NSString *const kAPIKey = @"YOUR_API_KEY";
  6. В файле SDKConstants.swift (Swift) или файле SDKDemoAPIKey.h (Objective-C) удалите следующую строку, поскольку она используется для регистрации определяемой пользователем проблемы:

    Быстрый

    #error (Register for API Key and insert here. Then delete this line.)

    Цель-C

    #error Register for API Key and insert here.
  7. Создайте и запустите проект. Появится окно симулятора iOS со списком демонстрационных версий Maps SDK .
  8. Выберите один из отображаемых вариантов, чтобы поэкспериментировать с функцией Maps SDK для iOS.
  9. Если будет предложено разрешить GoogleMapsDemos доступ к вашему местоположению, выберите «Разрешить» .
,
Карта реагирует на жесты масштабирования только тогда, когда переключатель включен.

Начать

Прежде чем вы сможете опробовать пример кода, вам необходимо настроить среду разработки. Дополнительную информацию см. в разделе «Примеры кода Maps SDK для iOS» .

Посмотреть код

Быстрый

import GoogleMaps
import UIKit

class GestureControlViewController: UIViewController {
  private let holderHeight: CGFloat = 60
  private let zoomLabelInset: CGFloat = 16

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

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(mapView)

    let holder = UIView(frame: .zero)
    holder.backgroundColor = UIColor(white: 1, alpha: 0.8)
    view.addSubview(holder)

    let zoomLabel = UILabel(frame: .zero)
    zoomLabel.text = "Zoom gestures"
    zoomLabel.font = .boldSystemFont(ofSize: 18)
    holder.addSubview(zoomLabel)

    // Control zooming.
    holder.addSubview(zoomSwitch)
    zoomSwitch.addTarget(self, action: #selector(toggleZoom), for: .valueChanged)
    zoomSwitch.isOn = true

    [mapView, holder, zoomLabel, zoomSwitch].forEach({
      $0.translatesAutoresizingMaskIntoConstraints = false
    })
    NSLayoutConstraint.activate([
      mapView.leftAnchor.constraint(equalTo: view.leftAnchor),
      mapView.rightAnchor.constraint(equalTo: view.rightAnchor),
      mapView.topAnchor.constraint(equalTo: view.topAnchor),
      mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
      holder.heightAnchor.constraint(equalToConstant: holderHeight),
      holder.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      holder.widthAnchor.constraint(equalTo: view.widthAnchor),
      zoomLabel.leftAnchor.constraint(equalTo: holder.leftAnchor, constant: zoomLabelInset),
      zoomLabel.centerYAnchor.constraint(equalTo: holder.centerYAnchor),
      zoomSwitch.rightAnchor.constraint(equalTo: holder.rightAnchor, constant: -zoomLabelInset),
      zoomSwitch.centerYAnchor.constraint(
        equalTo: holder.centerYAnchor),
    ])
    NSLayoutConstraint.activate([
      holder.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
    ])
  }

  @objc func toggleZoom() {
    mapView.settings.zoomGestures = zoomSwitch.isOn
  }

}
      

Цель-C

#import "GoogleMapsDemos/Samples/GestureControlViewController.h"

#import <GoogleMaps/GoogleMaps.h>

@implementation GestureControlViewController {
  GMSMapView *_mapView;
  UISwitch *_zoomSwitch;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-25.5605
                                                          longitude:133.605097
                                                               zoom:3];

  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  _mapView.accessibilityIdentifier = @"gestureControlDemoMapView";

  self.view = [[UIView alloc] initWithFrame:CGRectZero];
  [self.view addSubview:_mapView];

  UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 59)];
  holder.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
  holder.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8f];
  [self.view addSubview:holder];

  // Zoom label.
  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, 200, 29)];
  label.text = @"Zooming?";
  label.font = [UIFont boldSystemFontOfSize:18.0f];
  label.textAlignment = NSTextAlignmentLeft;
  label.backgroundColor = [UIColor clearColor];
  label.layer.shadowColor = [[UIColor whiteColor] CGColor];
  label.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
  label.layer.shadowOpacity = 1.0f;
  label.layer.shadowRadius = 0.0f;
  [holder addSubview:label];

  // Control zooming.
  _zoomSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(-90, 16, 0, 0)];
  _zoomSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
  [_zoomSwitch addTarget:self
                  action:@selector(didChangeZoomSwitch)
        forControlEvents:UIControlEventValueChanged];
  _zoomSwitch.on = YES;
  [holder addSubview:_zoomSwitch];
}

- (void)didChangeZoomSwitch {
  _mapView.settings.zoomGestures = _zoomSwitch.isOn;
}

@end
      

Запустите полный пример приложения локально

Пример приложения Maps SDK для iOS доступен в виде архива для загрузки на GitHub . Выполните следующие действия, чтобы установить и опробовать пример приложения Maps SDK для iOS.

  1. Запустите git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git , чтобы клонировать репозиторий образцов в локальный каталог.
  2. Откройте окно терминала, перейдите в каталог, в который вы клонировали файлы примеров, и перейдите к каталогу GoogleMaps:

    Быстрый

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

    Цель-C

    cd maps-sdk-for-ios-samples-main/GoogleMaps
    pod install
    open GoogleMapsDemos.xcworkspace
  3. В Xcode нажмите кнопку компиляции, чтобы создать приложение с текущей схемой. При сборке возникает ошибка, предлагающая ввести ключ API в файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C.
  4. Если у вас еще нет ключа API, следуйте инструкциям , чтобы настроить проект в Google Cloud Console и получить ключ API. При настройке ключа в Cloud Console вы можете ограничить ключ идентификатором пакета примера приложения, чтобы гарантировать, что только ваше приложение может использовать ключ. Идентификатор пакета по умолчанию для примера приложения SDK — com.example.GoogleMapsDemos .
  5. Отредактируйте файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C и вставьте свой ключ API в определение константы apiKey или kAPIKey . Например:

    Быстрый

    static let apiKey = "YOUR_API_KEY"

    Цель-C

    static NSString *const kAPIKey = @"YOUR_API_KEY";
  6. В файле SDKConstants.swift (Swift) или файле SDKDemoAPIKey.h (Objective-C) удалите следующую строку, поскольку она используется для регистрации определяемой пользователем проблемы:

    Быстрый

    #error (Register for API Key and insert here. Then delete this line.)

    Цель-C

    #error Register for API Key and insert here.
  7. Создайте и запустите проект. Появится окно симулятора iOS со списком демонстрационных версий Maps SDK .
  8. Выберите один из отображаемых вариантов, чтобы поэкспериментировать с функцией Maps SDK для iOS.
  9. Если будет предложено разрешить GoogleMapsDemos доступ к вашему местоположению, выберите «Разрешить» .
,
Карта реагирует на жесты масштабирования только тогда, когда переключатель включен.

Начать

Прежде чем вы сможете опробовать пример кода, вам необходимо настроить среду разработки. Дополнительную информацию см . в примерах кода Maps SDK для iOS .

Посмотреть код

Быстрый

import GoogleMaps
import UIKit

class GestureControlViewController: UIViewController {
  private let holderHeight: CGFloat = 60
  private let zoomLabelInset: CGFloat = 16

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

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(mapView)

    let holder = UIView(frame: .zero)
    holder.backgroundColor = UIColor(white: 1, alpha: 0.8)
    view.addSubview(holder)

    let zoomLabel = UILabel(frame: .zero)
    zoomLabel.text = "Zoom gestures"
    zoomLabel.font = .boldSystemFont(ofSize: 18)
    holder.addSubview(zoomLabel)

    // Control zooming.
    holder.addSubview(zoomSwitch)
    zoomSwitch.addTarget(self, action: #selector(toggleZoom), for: .valueChanged)
    zoomSwitch.isOn = true

    [mapView, holder, zoomLabel, zoomSwitch].forEach({
      $0.translatesAutoresizingMaskIntoConstraints = false
    })
    NSLayoutConstraint.activate([
      mapView.leftAnchor.constraint(equalTo: view.leftAnchor),
      mapView.rightAnchor.constraint(equalTo: view.rightAnchor),
      mapView.topAnchor.constraint(equalTo: view.topAnchor),
      mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
      holder.heightAnchor.constraint(equalToConstant: holderHeight),
      holder.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      holder.widthAnchor.constraint(equalTo: view.widthAnchor),
      zoomLabel.leftAnchor.constraint(equalTo: holder.leftAnchor, constant: zoomLabelInset),
      zoomLabel.centerYAnchor.constraint(equalTo: holder.centerYAnchor),
      zoomSwitch.rightAnchor.constraint(equalTo: holder.rightAnchor, constant: -zoomLabelInset),
      zoomSwitch.centerYAnchor.constraint(
        equalTo: holder.centerYAnchor),
    ])
    NSLayoutConstraint.activate([
      holder.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
    ])
  }

  @objc func toggleZoom() {
    mapView.settings.zoomGestures = zoomSwitch.isOn
  }

}
      

Цель-C

#import "GoogleMapsDemos/Samples/GestureControlViewController.h"

#import <GoogleMaps/GoogleMaps.h>

@implementation GestureControlViewController {
  GMSMapView *_mapView;
  UISwitch *_zoomSwitch;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-25.5605
                                                          longitude:133.605097
                                                               zoom:3];

  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  _mapView.accessibilityIdentifier = @"gestureControlDemoMapView";

  self.view = [[UIView alloc] initWithFrame:CGRectZero];
  [self.view addSubview:_mapView];

  UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 59)];
  holder.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
  holder.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8f];
  [self.view addSubview:holder];

  // Zoom label.
  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, 200, 29)];
  label.text = @"Zooming?";
  label.font = [UIFont boldSystemFontOfSize:18.0f];
  label.textAlignment = NSTextAlignmentLeft;
  label.backgroundColor = [UIColor clearColor];
  label.layer.shadowColor = [[UIColor whiteColor] CGColor];
  label.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
  label.layer.shadowOpacity = 1.0f;
  label.layer.shadowRadius = 0.0f;
  [holder addSubview:label];

  // Control zooming.
  _zoomSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(-90, 16, 0, 0)];
  _zoomSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
  [_zoomSwitch addTarget:self
                  action:@selector(didChangeZoomSwitch)
        forControlEvents:UIControlEventValueChanged];
  _zoomSwitch.on = YES;
  [holder addSubview:_zoomSwitch];
}

- (void)didChangeZoomSwitch {
  _mapView.settings.zoomGestures = _zoomSwitch.isOn;
}

@end
      

Запустите полный пример приложения локально

Пример приложения Maps SDK для iOS доступен в виде архива для загрузки на GitHub . Выполните следующие действия, чтобы установить и опробовать пример приложения Maps SDK для iOS.

  1. Запустите git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git , чтобы клонировать репозиторий образцов в локальный каталог.
  2. Откройте окно терминала, перейдите в каталог, в который вы клонировали файлы примеров, и перейдите к каталогу GoogleMaps:

    Быстрый

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

    Цель-C

    cd maps-sdk-for-ios-samples-main/GoogleMaps
    pod install
    open GoogleMapsDemos.xcworkspace
  3. В Xcode нажмите кнопку компиляции, чтобы создать приложение с текущей схемой. При сборке возникает ошибка, предлагающая ввести ключ API в файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C.
  4. Если у вас еще нет ключа API, следуйте инструкциям , чтобы настроить проект в Google Cloud Console и получить ключ API. При настройке ключа в Cloud Console вы можете ограничить ключ идентификатором пакета примера приложения, чтобы гарантировать, что только ваше приложение может использовать ключ. Идентификатор пакета по умолчанию для примера приложения SDK — com.example.GoogleMapsDemos .
  5. Отредактируйте файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C и вставьте свой ключ API в определение константы apiKey или kAPIKey . Например:

    Быстрый

    static let apiKey = "YOUR_API_KEY"

    Цель-C

    static NSString *const kAPIKey = @"YOUR_API_KEY";
  6. В файле SDKConstants.swift (Swift) или файле SDKDemoAPIKey.h (Objective-C) удалите следующую строку, поскольку она используется для регистрации определяемой пользователем проблемы:

    Быстрый

    #error (Register for API Key and insert here. Then delete this line.)

    Цель-C

    #error Register for API Key and insert here.
  7. Создайте и запустите проект. Появится окно симулятора iOS со списком демонстрационных версий Maps SDK .
  8. Выберите один из отображаемых вариантов, чтобы поэкспериментировать с функцией Maps SDK для iOS.
  9. Если будет предложено разрешить GoogleMapsDemos доступ к вашему местоположению, выберите «Разрешить» .