Chọn địa điểm hiện tại và hiển thị chi tiết trên bản đồ
Hướng dẫn này minh hoạ cách tạo một ứng dụng iOS truy xuất vị trí hiện tại của thiết bị, xác định các vị trí có thể có, nhắc người dùng chọn vị trí phù hợp nhất và hiển thị điểm đánh dấu bản đồ cho vị trí đã chọn.
Chương trình này phù hợp với những người có kiến thức mới bắt đầu hoặc trung cấp về Swift hoặc Target-C và có kiến thức chung về Xcode. Để có hướng dẫn nâng cao về cách tạo bản đồ, hãy đọc hướng dẫn dành cho nhà phát triển.
Bạn sẽ tạo bản đồ sau đây bằng hướng dẫn này. Điểm đánh dấu bản đồ được đặt ở San Francisco, California, nhưng sẽ di chuyển đến bất cứ nơi nào đặt thiết bị hoặc trình mô phỏng.
Hướng dẫn này sử dụng SDK Địa điểm cho iOS, SDK Maps dành cho iOS và khung Vị trí lõi của Apple.
Lấy mã
Sao chép hoặc tải kho lưu trữ mẫu Google Maps dành cho iOS xuống từ GitHub.Hoặc, nhấp vào nút sau để tải xuống mã nguồn:
MapViewController trong Swift
/* * Copyright 2016 Google Inc. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import GoogleMaps import GooglePlaces class MapViewController: UIViewController { var locationManager: CLLocationManager! var currentLocation: CLLocation? var mapView: GMSMapView! var placesClient: GMSPlacesClient! var preciseLocationZoomLevel: Float = 15.0 var approximateLocationZoomLevel: Float = 10.0 // An array to hold the list of likely places. var likelyPlaces: [GMSPlace] = [] // The currently selected place. var selectedPlace: GMSPlace? // Update the map once the user has made their selection. @IBAction func unwindToMain(segue: UIStoryboardSegue) { // Clear the map. mapView.clear() // Add a marker to the map. if let place = selectedPlace { let marker = GMSMarker(position: place.coordinate) marker.title = selectedPlace?.name marker.snippet = selectedPlace?.formattedAddress marker.map = mapView } listLikelyPlaces() } override func viewDidLoad() { super.viewDidLoad() // Initialize the location manager. locationManager = CLLocationManager() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.distanceFilter = 50 locationManager.startUpdatingLocation() locationManager.delegate = self placesClient = GMSPlacesClient.shared() // A default location to use when location permission is not granted. let defaultLocation = CLLocation(latitude: -33.869405, longitude: 151.199) // Create a map. let zoomLevel = locationManager.accuracyAuthorization == .fullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel let camera = GMSCameraPosition.camera(withLatitude: defaultLocation.coordinate.latitude, longitude: defaultLocation.coordinate.longitude, zoom: zoomLevel) mapView = GMSMapView.map(withFrame: view.bounds, camera: camera) mapView.settings.myLocationButton = true mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.isMyLocationEnabled = true // Add the map to the view, hide it until we've got a location update. view.addSubview(mapView) mapView.isHidden = true listLikelyPlaces() } // Populate the array with the list of likely places. func listLikelyPlaces() { // Clean up from previous sessions. likelyPlaces.removeAll() let placeFields: GMSPlaceField = [.name, .coordinate] placesClient.findPlaceLikelihoodsFromCurrentLocation(withPlaceFields: placeFields) { (placeLikelihoods, error) in guard error == nil else { // TODO: Handle the error. print("Current Place error: \(error!.localizedDescription)") return } guard let placeLikelihoods = placeLikelihoods else { print("No places found.") return } // Get likely places and add to the list. for likelihood in placeLikelihoods { let place = likelihood.place self.likelyPlaces.append(place) } } } // Prepare the segue. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueToSelect" { if let nextViewController = segue.destination as? PlacesViewController { nextViewController.likelyPlaces = likelyPlaces } } } } // Delegates to handle events for the location manager. extension MapViewController: CLLocationManagerDelegate { // Handle incoming location events. func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location: CLLocation = locations.last! print("Location: \(location)") let zoomLevel = locationManager.accuracyAuthorization == .fullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: zoomLevel) if mapView.isHidden { mapView.isHidden = false mapView.camera = camera } else { mapView.animate(to: camera) } listLikelyPlaces() } // Handle authorization for the location manager. func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { // Check accuracy authorization let accuracy = manager.accuracyAuthorization switch accuracy { case .fullAccuracy: print("Location accuracy is precise.") case .reducedAccuracy: print("Location accuracy is not precise.") @unknown default: fatalError() } // Handle authorization status switch status { case .restricted: print("Location access was restricted.") case .denied: print("User denied access to location.") // Display the map using the default location. mapView.isHidden = false case .notDetermined: print("Location status not determined.") case .authorizedAlways: fallthrough case .authorizedWhenInUse: print("Location status is OK.") @unknown default: fatalError() } } // Handle location manager errors. func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationManager.stopUpdatingLocation() print("Error: \(error)") } }
Swift PlacesViewController
/* * Copyright 2017 Google Inc. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import GooglePlaces class PlacesViewController: UIViewController { @IBOutlet weak var tableView: UITableView! // An array to hold the list of possible locations. var likelyPlaces: [GMSPlace] = [] var selectedPlace: GMSPlace? // Cell reuse id (cells that scroll out of view can be reused). let cellReuseIdentifier = "cell" override func viewDidLoad() { super.viewDidLoad() // Register the table view cell class and its reuse id. tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) // This view controller provides delegate methods and row data for the table view. tableView.delegate = self tableView.dataSource = self tableView.reloadData() } // Pass the selected place to the new view controller. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "unwindToMain" { if let nextViewController = segue.destination as? MapViewController { nextViewController.selectedPlace = selectedPlace } } } } // Respond when a user selects a place. extension PlacesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedPlace = likelyPlaces[indexPath.row] performSegue(withIdentifier: "unwindToMain", sender: self) } // Adjust cell height to only show the first five items in the table // (scrolling is disabled in IB). func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.tableView.frame.size.height/5 } // Make table rows display at proper height if there are less than 5 items. func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if (section == tableView.numberOfSections - 1) { return 1 } return 0 } } // Populate the table with the list of most likely places. extension PlacesViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return likelyPlaces.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) let collectionItem = likelyPlaces[indexPath.row] cell.textLabel?.text = collectionItem.name return cell } }
MapViewController trong Obj-C
// // MapsViewController.m // current-place-on-map // // Created by Chris Arriola on 9/18/20. // Copyright © 2020 William French. All rights reserved. // #import "MapViewController.h" #import "PlacesViewController.h" @import CoreLocation; @import GooglePlaces; @import GoogleMaps; @interface MapViewController () <CLLocationManagerDelegate> @end @implementation MapViewController { CLLocationManager *locationManager; CLLocation * _Nullable currentLocation; GMSMapView *mapView; GMSPlacesClient *placesClient; float preciseLocationZoomLevel; float approximateLocationZoomLevel; // An array to hold the list of likely places. NSMutableArray<GMSPlace *> *likelyPlaces; // The currently selected place. GMSPlace * _Nullable selectedPlace; } - (void)viewDidLoad { [super viewDidLoad]; preciseLocationZoomLevel = 15.0; approximateLocationZoomLevel = 15.0; // Initialize the location manager. locationManager = [[CLLocationManager alloc] init]; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager requestWhenInUseAuthorization]; locationManager.distanceFilter = 50; [locationManager startUpdatingLocation]; locationManager.delegate = self; placesClient = [GMSPlacesClient sharedClient]; // A default location to use when location permission is not granted. CLLocationCoordinate2D defaultLocation = CLLocationCoordinate2DMake(-33.869405, 151.199); // Create a map. float zoomLevel = locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:defaultLocation.latitude longitude:defaultLocation.longitude zoom:zoomLevel]; mapView = [GMSMapView mapWithFrame:self.view.bounds camera:camera]; mapView.settings.myLocationButton = YES; mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; mapView.myLocationEnabled = YES; // Add the map to the view, hide it until we've got a location update. [self.view addSubview:mapView]; mapView.hidden = YES; [self listLikelyPlaces]; } // Populate the array with the list of likely places. - (void) listLikelyPlaces { // Clean up from previous sessions. likelyPlaces = [NSMutableArray array]; GMSPlaceField placeFields = GMSPlaceFieldName | GMSPlaceFieldCoordinate; [placesClient findPlaceLikelihoodsFromCurrentLocationWithPlaceFields:placeFields callback:^(NSArray<GMSPlaceLikelihood *> * _Nullable likelihoods, NSError * _Nullable error) { if (error != nil) { // TODO: Handle the error. NSLog(@"Current Place error: %@", error.localizedDescription); return; } if (likelihoods == nil) { NSLog(@"No places found."); return; } for (GMSPlaceLikelihood *likelihood in likelihoods) { GMSPlace *place = likelihood.place; [likelyPlaces addObject:place]; } }]; } // Update the map once the user has made their selection. - (void) unwindToMain:(UIStoryboardSegue *)segue { // Clear the map. [mapView clear]; // Add a marker to the map. if (selectedPlace != nil) { GMSMarker *marker = [GMSMarker markerWithPosition:selectedPlace.coordinate]; marker.title = selectedPlace.name; marker.snippet = selectedPlace.formattedAddress; marker.map = mapView; } [self listLikelyPlaces]; } // Prepare the segue. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"segueToSelect"]) { if ([segue.destinationViewController isKindOfClass:[PlacesViewController class]]) { PlacesViewController *placesViewController = (PlacesViewController *)segue.destinationViewController; placesViewController.likelyPlaces = likelyPlaces; } } } // Delegates to handle events for the location manager. #pragma mark - CLLocationManagerDelegate // Handle incoming location events. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { CLLocation *location = locations.lastObject; NSLog(@"Location: %@", location); float zoomLevel = locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel; GMSCameraPosition * camera = [GMSCameraPosition cameraWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude zoom:zoomLevel]; if (mapView.isHidden) { mapView.hidden = NO; mapView.camera = camera; } else { [mapView animateToCameraPosition:camera]; } [self listLikelyPlaces]; } // Handle authorization for the location manager. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { // Check accuracy authorization CLAccuracyAuthorization accuracy = manager.accuracyAuthorization; switch (accuracy) { case CLAccuracyAuthorizationFullAccuracy: NSLog(@"Location accuracy is precise."); break; case CLAccuracyAuthorizationReducedAccuracy: NSLog(@"Location accuracy is not precise."); break; } // Handle authorization status switch (status) { case kCLAuthorizationStatusRestricted: NSLog(@"Location access was restricted."); break; case kCLAuthorizationStatusDenied: NSLog(@"User denied access to location."); // Display the map using the default location. mapView.hidden = NO; case kCLAuthorizationStatusNotDetermined: NSLog(@"Location status not determined."); case kCLAuthorizationStatusAuthorizedAlways: case kCLAuthorizationStatusAuthorizedWhenInUse: NSLog(@"Location status is OK."); } } // Handle location manager errors. - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { [manager stopUpdatingLocation]; NSLog(@"Error: %@", error.localizedDescription); } @end
Obj-C PlacesViewController
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import "PlacesViewController.h" @interface PlacesViewController () <UITableViewDataSource, UITableViewDelegate> @property (nonatomic, weak) UITableView *tableView; @end @implementation PlacesViewController { // Cell reuse id (cells that scroll out of view can be reused). NSString *cellReuseIdentifier; } - (void)viewDidLoad { [super viewDidLoad]; cellReuseIdentifier = @"cell"; } -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { } #pragma mark - UITableViewDelegate // Respond when a user selects a place. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.selectedPlace = [self.likelyPlaces objectAtIndex:indexPath.row]; [self performSegueWithIdentifier:@"unwindToMain" sender:self]; } // Adjust cell height to only show the first five items in the table // (scrolling is disabled in IB). -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return self.tableView.frame.size.height/5; } // Make table rows display at proper height if there are less than 5 items. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { if (section == tableView.numberOfSections - 1) { return 1; } return 0; } #pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.likelyPlaces.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { return [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier forIndexPath:indexPath]; } @end
Bắt đầu
Trình quản lý gói Swift
Bạn có thể cài đặt SDK bản đồ dành cho iOS bằng cách sử dụng Trình quản lý gói Swift.
- Đảm bảo bạn đã xoá mọi SDK Maps hiện có cho các phần phụ thuộc iOS.
- Mở một cửa sổ dòng lệnh rồi chuyển đến thư mục
tutorials/current-place-on-map
. -
Hãy đảm bảo rằng không gian làm việc Xcode của bạn đã đóng và chạy các lệnh sau:
sudo gem install cocoapods-deintegrate cocoapods-clean pod deintegrate pod cache clean --all rm Podfile rm current-place-on-map.xcworkspace
- Mở dự án Xcode của bạn rồi xoá tệp podfile đó.
- Thêm SDK Địa điểm và Bản đồ:
- Chuyển đến File > Add Package Dependencies (Tệp > Thêm phần phụ thuộc gói).
- Nhập https://github.com/googlemaps/ios-places-sdk làm URL, nhấn Enter để kéo gói vào và nhấp vào Add Package (Thêm gói).
- Nhập https://github.com/googlemaps/ios-maps-sdk làm URL, nhấn Enter để kéo trong gói và nhấp vào Add Package (Thêm gói).
- Bạn có thể cần đặt lại bộ nhớ đệm của gói bằng cách sử dụng File > Packages > Reset Package Cache (Tệp > Gói > Đặt lại bộ nhớ đệm của gói).
Sử dụng CocoaPods
- Tải xuống và cài đặt Xcode phiên bản 15.0 trở lên.
- Nếu bạn chưa có CocoaPods, hãy cài đặt ứng dụng này trên macOS bằng cách chạy lệnh sau trên cửa sổ dòng lệnh:
sudo gem install cocoapods
- Chuyển đến thư mục
tutorials/current-place-on-map
. - Chạy lệnh
pod install
. Thao tác này sẽ cài đặt SDK Bản đồ và Địa điểm được chỉ định trongPodfile
, cùng với mọi phần phụ thuộc. - Chạy
pod outdated
để so sánh phiên bản nhóm đã cài đặt với mọi bản cập nhật mới. Nếu phát hiện thấy một phiên bản mới, hãy chạypod update
để cập nhậtPodfile
rồi cài đặt SDK mới nhất. Để biết thêm thông tin, hãy xem Hướng dẫn về CocoaPods. - Mở (nhấp đúp) tệp current-place-on-map.xcworkspace
của dự án để mở tệp đó trong Xcode. Bạn phải sử dụng tệp
.xcworkspace
để mở dự án.
Nhận khoá API và bật các API cần thiết
Để hoàn tất hướng dẫn này, bạn cần có khoá API của Google được phép sử dụng SDK Maps dành cho iOS và API Địa điểm.
- Hãy làm theo hướng dẫn trong bài viết Bắt đầu sử dụng Nền tảng Google Maps để thiết lập một tài khoản thanh toán và một dự án được kích hoạt thông qua cả hai sản phẩm này.
- Làm theo hướng dẫn trong phần Tải khoá API để tạo khoá API cho dự án phát triển mà bạn đã thiết lập trước đó.
Thêm khoá API vào ứng dụng của bạn
Thêm khoá API vào AppDelegate.swift
của bạn như sau:
- Lưu ý rằng câu lệnh nhập sau đã được thêm vào tệp:
import GooglePlaces import GoogleMaps
- Chỉnh sửa dòng sau trong phương thức
application(_:didFinishLaunchingWithOptions:)
, thay thế YOUR_API_KEY bằng khoá API:GMSPlacesClient.provideAPIKey("YOUR_API_KEY") GMSServices.provideAPIKey("YOUR_API_KEY")
Tạo và chạy ứng dụng
- Kết nối thiết bị iOS với máy tính của bạn hoặc chọn một trình mô phỏng từ trình đơn bật lên lược đồ Xcode.
- Nếu bạn đang sử dụng một thiết bị, hãy đảm bảo rằng dịch vụ vị trí đã được bật. Nếu bạn đang sử dụng trình mô phỏng, hãy chọn một vị trí trong trình đơn Tính năng.
- Trong Xcode, hãy nhấp vào tuỳ chọn trình đơn Product/Run (Sản phẩm/Chạy) (hoặc biểu tượng nút phát).
- Xcode sẽ tạo ứng dụng rồi chạy ứng dụng trên thiết bị hoặc trên trình mô phỏng.
- Bạn sẽ thấy một bản đồ có một số điểm đánh dấu được căn giữa xung quanh vị trí hiện tại của bạn.
Gỡ rối:
- Nếu không thấy bản đồ, hãy kiểm tra để đảm bảo bạn đã lấy được một khoá API và thêm khoá đó vào ứng dụng như mô tả ở trên. Kiểm tra bảng điều khiển gỡ lỗi của Xcode để xem thông báo lỗi về khoá API.
- Nếu bạn đã hạn chế khoá API bằng giá trị nhận dạng gói iOS, hãy chỉnh sửa khoá này để thêm giá trị nhận dạng gói cho ứng dụng:
com.google.examples.current-place-on-map
. - Bản đồ sẽ không hiển thị chính xác nếu yêu cầu cấp quyền cho
dịch vụ vị trí bị từ chối.
- Nếu bạn đang sử dụng một thiết bị, hãy chuyển đến phần Cài đặt/Chung/Quyền riêng tư/Dịch vụ vị trí rồi bật lại dịch vụ vị trí.
- Nếu bạn đang sử dụng trình mô phỏng, hãy chuyển đến phần Trình mô phỏng/Đặt lại nội dung và cài đặt...
- Đảm bảo rằng bạn có kết nối Wi-Fi hoặc GPS tốt.
- Nếu ứng dụng khởi chạy nhưng không hiển thị bản đồ, hãy đảm bảo rằng bạn đã cập nhật tệp Info.plist cho dự án của mình bằng các quyền truy cập thông tin vị trí thích hợp. Để biết thêm thông tin về cách xử lý quyền, hãy xem hướng dẫn yêu cầu quyền truy cập thông tin vị trí trong ứng dụng ở bên dưới.
- Sử dụng công cụ gỡ lỗi Xcode để xem nhật ký và gỡ lỗi ứng dụng.
Tìm hiểu mã nguồn
Phần này của hướng dẫn giải thích các phần quan trọng nhất của ứng dụng current-place-on-map, để giúp bạn hiểu cách tạo một ứng dụng tương tự.
Ứng dụng current-place-on-map có hai bộ điều khiển chế độ xem: Một bộ điều khiển để hiển thị bản đồ cho thấy địa điểm hiện tại của người dùng và một bộ điều khiển để hiển thị cho người dùng danh sách các địa điểm có thể để chọn. Xin lưu ý rằng mỗi trình điều khiển khung hiển thị đều có cùng các biến để theo dõi danh sách các địa điểm có thể (likelyPlaces
) và để cho biết lựa chọn của người dùng (selectedPlace
). Việc di chuyển giữa các khung hiển thị được thực hiện bằng cách sử dụng các phiên bản.
Yêu cầu quyền truy cập thông tin vị trí
Ứng dụng của bạn phải nhắc người dùng đồng ý sử dụng dịch vụ vị trí. Để thực hiện việc này, hãy đưa khoá NSLocationAlwaysUsageDescription
vào tệp Info.plist
cho ứng dụng và đặt giá trị của mỗi khoá thành một chuỗi mô tả cách ứng dụng định sử dụng dữ liệu vị trí.
Thiết lập trình quản lý vị trí
Sử dụng CLLocationManager để tìm vị trí hiện tại của thiết bị và yêu cầu cập nhật thường xuyên khi thiết bị di chuyển đến vị trí mới. Hướng dẫn này cung cấp mã bạn cần để nhận thông tin vị trí của thiết bị. Để biết thêm thông tin, hãy xem hướng dẫn Lấy thông tin vị trí của người dùng trong Tài liệu dành cho nhà phát triển của Apple.
- Khai báo trình quản lý vị trí, vị trí hiện tại, chế độ xem bản đồ, ứng dụng đặt vị trí và mức thu phóng mặc định ở cấp lớp.
- Khởi chạy trình quản lý vị trí và
GMSPlacesClient
trongviewDidLoad()
. - Khai báo các biến để lưu giữ danh sách các địa điểm có thể xuất hiện và địa điểm mà người dùng chọn.
- Thêm uỷ quyền để xử lý các sự kiện cho trình quản lý vị trí bằng cách sử dụng mệnh đề tiện ích.
Swift
var locationManager: CLLocationManager! var currentLocation: CLLocation? var mapView: GMSMapView! var placesClient: GMSPlacesClient! var preciseLocationZoomLevel: Float = 15.0 var approximateLocationZoomLevel: Float = 10.0
Objective-C
CLLocationManager *locationManager; CLLocation * _Nullable currentLocation; GMSMapView *mapView; GMSPlacesClient *placesClient; float preciseLocationZoomLevel; float approximateLocationZoomLevel;
Swift
// Initialize the location manager. locationManager = CLLocationManager() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.distanceFilter = 50 locationManager.startUpdatingLocation() locationManager.delegate = self placesClient = GMSPlacesClient.shared()
Objective-C
// Initialize the location manager. locationManager = [[CLLocationManager alloc] init]; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager requestWhenInUseAuthorization]; locationManager.distanceFilter = 50; [locationManager startUpdatingLocation]; locationManager.delegate = self; placesClient = [GMSPlacesClient sharedClient];
Swift
// An array to hold the list of likely places. var likelyPlaces: [GMSPlace] = [] // The currently selected place. var selectedPlace: GMSPlace?
Objective-C
// An array to hold the list of likely places. NSMutableArray<GMSPlace *> *likelyPlaces; // The currently selected place. GMSPlace * _Nullable selectedPlace;
Swift
// Delegates to handle events for the location manager. extension MapViewController: CLLocationManagerDelegate { // Handle incoming location events. func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location: CLLocation = locations.last! print("Location: \(location)") let zoomLevel = locationManager.accuracyAuthorization == .fullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: zoomLevel) if mapView.isHidden { mapView.isHidden = false mapView.camera = camera } else { mapView.animate(to: camera) } listLikelyPlaces() } // Handle authorization for the location manager. func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { // Check accuracy authorization let accuracy = manager.accuracyAuthorization switch accuracy { case .fullAccuracy: print("Location accuracy is precise.") case .reducedAccuracy: print("Location accuracy is not precise.") @unknown default: fatalError() } // Handle authorization status switch status { case .restricted: print("Location access was restricted.") case .denied: print("User denied access to location.") // Display the map using the default location. mapView.isHidden = false case .notDetermined: print("Location status not determined.") case .authorizedAlways: fallthrough case .authorizedWhenInUse: print("Location status is OK.") @unknown default: fatalError() } } // Handle location manager errors. func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationManager.stopUpdatingLocation() print("Error: \(error)") } }
Objective-C
// Delegates to handle events for the location manager. #pragma mark - CLLocationManagerDelegate // Handle incoming location events. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { CLLocation *location = locations.lastObject; NSLog(@"Location: %@", location); float zoomLevel = locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel; GMSCameraPosition * camera = [GMSCameraPosition cameraWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude zoom:zoomLevel]; if (mapView.isHidden) { mapView.hidden = NO; mapView.camera = camera; } else { [mapView animateToCameraPosition:camera]; } [self listLikelyPlaces]; } // Handle authorization for the location manager. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { // Check accuracy authorization CLAccuracyAuthorization accuracy = manager.accuracyAuthorization; switch (accuracy) { case CLAccuracyAuthorizationFullAccuracy: NSLog(@"Location accuracy is precise."); break; case CLAccuracyAuthorizationReducedAccuracy: NSLog(@"Location accuracy is not precise."); break; } // Handle authorization status switch (status) { case kCLAuthorizationStatusRestricted: NSLog(@"Location access was restricted."); break; case kCLAuthorizationStatusDenied: NSLog(@"User denied access to location."); // Display the map using the default location. mapView.hidden = NO; case kCLAuthorizationStatusNotDetermined: NSLog(@"Location status not determined."); case kCLAuthorizationStatusAuthorizedAlways: case kCLAuthorizationStatusAuthorizedWhenInUse: NSLog(@"Location status is OK."); } } // Handle location manager errors. - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { [manager stopUpdatingLocation]; NSLog(@"Error: %@", error.localizedDescription); }
Thêm bản đồ
Tạo bản đồ và thêm bản đồ đó vào chế độ xem trong viewDidLoad()
trong bộ điều khiển chế độ xem chính. Bản đồ luôn bị ẩn cho đến khi nhận được thông tin cập nhật vị trí (thông tin cập nhật vị trí được xử lý trong tiện ích CLLocationManagerDelegate
).
Swift
// A default location to use when location permission is not granted. let defaultLocation = CLLocation(latitude: -33.869405, longitude: 151.199) // Create a map. let zoomLevel = locationManager.accuracyAuthorization == .fullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel let camera = GMSCameraPosition.camera(withLatitude: defaultLocation.coordinate.latitude, longitude: defaultLocation.coordinate.longitude, zoom: zoomLevel) mapView = GMSMapView.map(withFrame: view.bounds, camera: camera) mapView.settings.myLocationButton = true mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.isMyLocationEnabled = true // Add the map to the view, hide it until we've got a location update. view.addSubview(mapView) mapView.isHidden = true
Objective-C
// A default location to use when location permission is not granted. CLLocationCoordinate2D defaultLocation = CLLocationCoordinate2DMake(-33.869405, 151.199); // Create a map. float zoomLevel = locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:defaultLocation.latitude longitude:defaultLocation.longitude zoom:zoomLevel]; mapView = [GMSMapView mapWithFrame:self.view.bounds camera:camera]; mapView.settings.myLocationButton = YES; mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; mapView.myLocationEnabled = YES; // Add the map to the view, hide it until we've got a location update. [self.view addSubview:mapView]; mapView.hidden = YES;
Nhắc người dùng chọn địa điểm hiện tại
Sử dụng SDK địa điểm dành cho iOS để xem khả năng xuất hiện của 5 địa điểm hàng đầu dựa trên vị trí hiện tại của người dùng và trình bày danh sách trong UITableView
. Khi người dùng chọn một địa điểm, hãy thêm điểm đánh dấu vào bản đồ.
- Lấy danh sách các địa điểm có thể để điền dữ liệu vào
UITableView
, từ đó người dùng có thể chọn vị trí hiện tại của họ. - Mở chế độ xem mới để hiển thị các địa điểm có thể cho người dùng. Khi người dùng nhấn vào "Nhận địa điểm", chúng ta sẽ chuyển sang một khung hiển thị mới và cho người dùng thấy danh sách các địa điểm có thể để chọn. Hàm
prepare
cập nhậtPlacesViewController
bằng danh sách các địa điểm có thể hiện có và tự động được gọi khi thực hiện một segue. - Trong
PlacesViewController
, hãy điền vào bảng bằng cách sử dụng danh sách các địa điểm có nhiều khả năng nhất bằng cách sử dụng tiện ích uỷ quyềnUITableViewDataSource
. - Xử lý lựa chọn của người dùng bằng cách sử dụng tiện ích uỷ quyền
UITableViewDelegate
.
Swift
// Populate the array with the list of likely places. func listLikelyPlaces() { // Clean up from previous sessions. likelyPlaces.removeAll() let placeFields: GMSPlaceField = [.name, .coordinate] placesClient.findPlaceLikelihoodsFromCurrentLocation(withPlaceFields: placeFields) { (placeLikelihoods, error) in guard error == nil else { // TODO: Handle the error. print("Current Place error: \(error!.localizedDescription)") return } guard let placeLikelihoods = placeLikelihoods else { print("No places found.") return } // Get likely places and add to the list. for likelihood in placeLikelihoods { let place = likelihood.place self.likelyPlaces.append(place) } } }
Objective-C
// Populate the array with the list of likely places. - (void) listLikelyPlaces { // Clean up from previous sessions. likelyPlaces = [NSMutableArray array]; GMSPlaceField placeFields = GMSPlaceFieldName | GMSPlaceFieldCoordinate; [placesClient findPlaceLikelihoodsFromCurrentLocationWithPlaceFields:placeFields callback:^(NSArray<GMSPlaceLikelihood *> * _Nullable likelihoods, NSError * _Nullable error) { if (error != nil) { // TODO: Handle the error. NSLog(@"Current Place error: %@", error.localizedDescription); return; } if (likelihoods == nil) { NSLog(@"No places found."); return; } for (GMSPlaceLikelihood *likelihood in likelihoods) { GMSPlace *place = likelihood.place; [likelyPlaces addObject:place]; } }]; }
Swift
// Prepare the segue. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueToSelect" { if let nextViewController = segue.destination as? PlacesViewController { nextViewController.likelyPlaces = likelyPlaces } } }
Objective-C
// Prepare the segue. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"segueToSelect"]) { if ([segue.destinationViewController isKindOfClass:[PlacesViewController class]]) { PlacesViewController *placesViewController = (PlacesViewController *)segue.destinationViewController; placesViewController.likelyPlaces = likelyPlaces; } } }
Swift
// Populate the table with the list of most likely places. extension PlacesViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return likelyPlaces.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) let collectionItem = likelyPlaces[indexPath.row] cell.textLabel?.text = collectionItem.name return cell } }
Objective-C
#pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.likelyPlaces.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { return [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier forIndexPath:indexPath]; } @end
Swift
class PlacesViewController: UIViewController { // ... // Pass the selected place to the new view controller. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "unwindToMain" { if let nextViewController = segue.destination as? MapViewController { nextViewController.selectedPlace = selectedPlace } } } } // Respond when a user selects a place. extension PlacesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedPlace = likelyPlaces[indexPath.row] performSegue(withIdentifier: "unwindToMain", sender: self) } // Adjust cell height to only show the first five items in the table // (scrolling is disabled in IB). func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.tableView.frame.size.height/5 } // Make table rows display at proper height if there are less than 5 items. func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if (section == tableView.numberOfSections - 1) { return 1 } return 0 } }
Objective-C
@interface PlacesViewController () <UITableViewDataSource, UITableViewDelegate> // ... -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { } #pragma mark - UITableViewDelegate // Respond when a user selects a place. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.selectedPlace = [self.likelyPlaces objectAtIndex:indexPath.row]; [self performSegueWithIdentifier:@"unwindToMain" sender:self]; } // Adjust cell height to only show the first five items in the table // (scrolling is disabled in IB). -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return self.tableView.frame.size.height/5; } // Make table rows display at proper height if there are less than 5 items. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { if (section == tableView.numberOfSections - 1) { return 1; } return 0; }
Thêm điểm đánh dấu vào bản đồ
Khi người dùng lựa chọn, hãy sử dụng tuỳ chọn thư giãn để quay lại khung hiển thị trước và thêm điểm đánh dấu vào bản đồ. IBAction unwindToMain
sẽ được tự động gọi khi quay lại bộ điều khiển khung hiển thị chính.
Swift
// Update the map once the user has made their selection. @IBAction func unwindToMain(segue: UIStoryboardSegue) { // Clear the map. mapView.clear() // Add a marker to the map. if let place = selectedPlace { let marker = GMSMarker(position: place.coordinate) marker.title = selectedPlace?.name marker.snippet = selectedPlace?.formattedAddress marker.map = mapView } listLikelyPlaces() }
Objective-C
// Update the map once the user has made their selection. - (void) unwindToMain:(UIStoryboardSegue *)segue { // Clear the map. [mapView clear]; // Add a marker to the map. if (selectedPlace != nil) { GMSMarker *marker = [GMSMarker markerWithPosition:selectedPlace.coordinate]; marker.title = selectedPlace.name; marker.snippet = selectedPlace.formattedAddress; marker.map = mapView; } [self listLikelyPlaces]; }
Xin chúc mừng! Bạn đã xây dựng một ứng dụng iOS cho phép người dùng chọn địa điểm hiện tại của họ và hiển thị kết quả trên bản đồ Google. Trong quá trình thực hiện việc này, bạn đã tìm hiểu cách sử dụng SDK Địa điểm dành cho iOS, SDK Bản đồ dành cho iOS và khung Vị trí cốt lõi của Apple.