Bật nút Vị trí của tôi

Hình ảnh nút Bật Vị trí của tôi.

Nút Vị trí của tôi hiển thị ở góc dưới cùng bên phải của chế độ xem bản đồ. Khi người dùng nhấn vào nút này, bản đồ sẽ xoay đến vị trí hiện tại của người dùng.

Bắt đầu

Trước khi có thể thử mã mẫu, bạn phải định cấu hình môi trường phát triển. Để biết thêm thông tin, hãy xem Mẫu mã SDK Bản đồ dành cho iOS.

Xem mã

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       

Chạy ứng dụng mẫu đầy đủ trên máy

Ứng dụng mẫu SDK Bản đồ dành cho iOS có sẵn dưới dạng tài nguyên lưu trữ để tải xuống trên GitHub. Hãy làm theo các bước sau để cài đặt và dùng thử ứng dụng mẫu Maps SDK cho iOS.

  1. Chạy git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git để nhân bản kho lưu trữ mẫu vào một thư mục cục bộ.
  2. Mở cửa sổ dòng lệnh, chuyển đến thư mục mà bạn đã nhân bản các tệp mẫu và đi sâu vào thư mục 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. Trong Xcode, hãy nhấn vào nút biên dịch để tạo ứng dụng bằng giao thức hiện tại. Bản dựng sẽ tạo ra lỗi, nhắc bạn nhập khoá API trong tệp SDKConstants.swift cho Swift hoặc tệp SDKDemoAPIKey.h cho Objective-C.
  4. Lấy khoá API từ dự án của bạn bằng cách bật SDK Bản đồ dành cho iOS.
  5. Chỉnh sửa tệp SDKConstants.swift cho Swift hoặc tệp SDKDemoAPIKey.h cho Objective-C và dán khoá API vào định nghĩa của hằng số apiKey hoặc kAPIKey. Ví dụ:

    Swift

    static let apiKey = "YOUR_API_KEY"

    Objective-C

    static NSString *const kAPIKey = @"YOUR_API_KEY";
  6. Trong tệp SDKConstants.swift (Swift) hoặc tệp SDKDemoAPIKey.h (Objective-C), hãy xoá dòng sau vì dòng này dùng để đăng ký vấn đề do người dùng xác định:

    Swift

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

    Objective-C

    #error Register for API Key and insert here.
  7. Tạo bản dựng và chạy dự án. Cửa sổ trình mô phỏng iOS sẽ xuất hiện, hiển thị danh sách Bản minh hoạ SDK Bản đồ.
  8. Chọn một trong các tuỳ chọn hiển thị để thử nghiệm một tính năng của SDK Bản đồ dành cho iOS.
  9. Nếu bạn được nhắc cho phép GoogleMapsDemos truy cập vào vị trí của bạn, hãy chọn Cho phép.