啟用「我的位置資訊」按鈕

地圖角落顯示「我的位置」按鈕。

這個範例會在地圖檢視畫面上顯示「我的位置」按鈕。輕觸該按鈕後,地圖會平移至裝置的目前位置。

開始使用

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

查看程式碼

Swift

import GoogleMaps
import UIKit

class MyLocationViewController: UIViewController {

  private let cameraLatitude: CLLocationDegrees = -33.868

  private let cameraLongitude: CLLocationDegrees = 151.2086

  private let cameraZoom: Float = 12

  lazy var mapView: GMSMapView = {
    let camera = GMSCameraPosition(
      latitude: cameraLatitude, longitude: cameraLongitude, zoom: cameraZoom)
    return GMSMapView(frame: .zero, camera: camera)
  }()

  var observation: NSKeyValueObservation?
  var location: CLLocation? {
    didSet {
      guard oldValue == nil, let firstLocation = location else { return }
      mapView.camera = GMSCameraPosition(target: firstLocation.coordinate, zoom: 14)
    }
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self
    mapView.settings.compassButton = true
    mapView.settings.myLocationButton = true
    mapView.isMyLocationEnabled = true
    view = mapView

    // Listen to the myLocation property of GMSMapView.
    observation = mapView.observe(\.myLocation, options: [.new]) {
      [weak self] mapView, _ in
      self?.location = mapView.myLocation
    }
  }

  deinit {
    observation?.invalidate()
  }
}

extension MyLocationViewController: GMSMapViewDelegate {
  func mapView(_ mapView: GMSMapView, didTapMyLocation location: CLLocationCoordinate2D) {
    let alert = UIAlertController(
      title: "Location Tapped",
      message: "Current location: <\(location.latitude), \(location.longitude)>",
      preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    present(alert, animated: true)
  }
}
      

Objective-C

#import "GoogleMapsDemos/Samples/MyLocationViewController.h"

#import <GoogleMaps/GoogleMaps.h>

@implementation MyLocationViewController {
  GMSMapView *_mapView;
  BOOL _firstLocationUpdate;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
                                                          longitude:151.2086
                                                               zoom:12];

  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  _mapView.delegate = self;
  _mapView.settings.compassButton = YES;
  _mapView.settings.myLocationButton = YES;

  // Listen to the myLocation property of GMSMapView.
  [_mapView addObserver:self
             forKeyPath:@"myLocation"
                options:NSKeyValueObservingOptionNew
                context:NULL];

  self.view = _mapView;

  // Ask for My Location data after the map has already been added to the UI.
  GMSMapView *mapView = _mapView;
  dispatch_async(dispatch_get_main_queue(), ^{
    mapView.myLocationEnabled = YES;
  });
}

- (void)mapView:(GMSMapView *)mapView didTapMyLocation:(CLLocationCoordinate2D)location {
  NSString *message = [NSString stringWithFormat:@"My Location Dot Tapped at: [lat: %f, lng: %f]",
                                                 location.latitude, location.longitude];
  UIAlertController *alertController =
      [UIAlertController alertControllerWithTitle:@"Location Tapped"
                                          message:message
                                   preferredStyle:UIAlertControllerStyleAlert];
  UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action){
                                                   }];
  [alertController addAction:okAction];
  [self presentViewController:alertController animated:YES completion:nil];
}

- (void)dealloc {
  [_mapView removeObserver:self forKeyPath:@"myLocation" context:NULL];
}

#pragma mark - KVO updates

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
  if (!_firstLocationUpdate) {
    // If the first location update has not yet been received, then jump to that location.
    _firstLocationUpdate = YES;
    CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
    _mapView.camera = [GMSCameraPosition cameraWithTarget:location.coordinate zoom:14];
  }
}

@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/GoogleMaps-Swift
    open GoogleMapsSwiftXCFrameworkDemos.xcodeproj

    Objective-C

    cd maps-sdk-for-ios-samples-main/GoogleMaps
    open GoogleMapsDemos.xcodeproj
  3. 在 Xcode 專案中,依序前往「File」>「Add Package Dependencies」。 輸入 https://github.com/googlemaps/ios-maps-sdk 做為網址,按下 Enter 鍵提取套件,然後按一下「Add Package」。
  4. 在 Xcode 中,按下編譯按鈕,使用目前的配置建構應用程式。建構作業會產生錯誤,提示您在 Swift 的 SDKConstants.swift 檔案或 Objective-C 的 SDKDemoAPIKey.h 檔案中輸入 API 金鑰。
  5. 從已啟用 Maps SDK for iOS 的專案取得 API 金鑰。
  6. 編輯 Swift 的 SDKConstants.swift 檔案或 Objective-C 的 SDKDemoAPIKey.h 檔案,然後將 API 金鑰貼到 apiKey 或 kAPIKey 常數的定義中。例如:

    Swift

    static let apiKey = "YOUR_API_KEY"

    Objective-C

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