
Ví dụ này cho thấy nút Vị trí của tôi trên chế độ xem bản đồ. Khi bạn nhấn vào nút này, bản đồ sẽ di chuyển đến vị trí hiện tại của thiết bị.
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ã mẫu của 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 hoàn chỉnh trên máy cục bộ
Ứng dụng mẫu SDK bản đồ dành cho iOS được cung cấp dưới dạng bản lưu trữ có thể tải xuống từ GitHub. Hãy làm theo các bước sau để cài đặt và dùng thử ứng dụng mẫu SDK bản đồ dành cho iOS.
- Chạy
git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.gitđể sao chép kho lưu trữ mẫu vào thư mục cục bộ. Mở cửa sổ dòng lệnh, chuyển đến thư mục mà bạn đã sao chép các tệp mẫu và xem chi tiết thư mục GoogleMaps:
Swift
cd maps-sdk-for-ios-samples/GoogleMaps-Swift
open GoogleMapsSwiftXCFrameworkDemos.xcodeprojObjective-C
cd maps-sdk-for-ios-samples-main/GoogleMaps
open GoogleMapsDemos.xcodeproj- Trong dự án Xcode, hãy chuyển đến File (Tệp) > Add Package Dependencies (Thêm phần phụ thuộc của gói).
Nhập
https://github.com/googlemaps/ios-maps-sdklàm URL, nhấn phím Enter để lấy gói rồi nhấp vào Add Package (Thêm gói). - Trong Xcode, hãy nhấn vào nút biên dịch để tạo ứng dụng bằng lược đồ hiện tại. Bản dựng sẽ tạo ra lỗi, nhắc bạn nhập khoá API
vào tệp
SDKConstants.swiftcho Swift hoặc tệpSDKDemoAPIKey.hcho Objective-C. - Lấy khoá API từ dự án của bạn khi đã bật SDK bản đồ dành cho iOS.
- Chỉnh sửa tệp
SDKConstants.swiftcho Swift hoặc tệpSDKDemoAPIKey.hcho Objective-C rồi dán khoá API vào định nghĩa của hằng sốapiKeyhoặckAPIKey. Ví dụ:Swift
static let apiKey = "YOUR_API_KEY"
Objective-C
static NSString *const kAPIKey = @"YOUR_API_KEY";
- Trong tệp
SDKConstants.swift(Swift) hoặc tệpSDKDemoAPIKey.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. - 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, cho thấy danh sách Bản minh hoạ SDK Maps.
- Chọn một trong các lựa chọn hiển thị để thử nghiệm một tính năng của SDK bản đồ dành cho iOS.
- Nếu được nhắc cho phép GoogleMapsDemos truy cập vào thông tin vị trí của bạn, hãy chọn Cho phép.