Chọn địa điểm hiện tại và hiển thị thông tin 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 có thể truy xuất vị trí hiện tại của thiết bị, xác định các vị trí có khả năng, 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.
Hướng dẫn này phù hợp với những người có kiến thức cơ bản hoặc trung cấp về Swift hoặc Objective-C và a kiến thức chung về Xcode. Để xem 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 có thiết bị hoặc trình mô phỏng.
Hướng dẫn này sử dụng SDK Địa điểm dành cho iOS, SDK Bản đồ dành cho iOS, và khung Apple Core Location.
Lấy mã
Sao chép hoặc tải kho lưu trữ mẫu Google Maps iOS xuống từ GitHub.Ngoài ra, hãy nhấp vào nút sau để tải mã nguồn xuống:
MapViewController
Swift
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)") } }
Objective-C
#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
PlacesViewController
Swift
import UIKit import GooglePlaces 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 } } // 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
#import "PlacesViewController.h" @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; } #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 Trình quản lý gói Swift.
- Xoá mọi phần phụ thuộc hiện có của SDK Bản đồ dành cho iOS.
- Mở cửa sổ dòng lệnh và chuyển đến thư mục
tutorials/current-place-on-map. -
Đóng không gian làm việc Xcode rồi 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 rồi xoá tệp podfile.
- Thêm SDK Địa điểm và SDK Bản đồ:
- Chuyển đến File > Add Package Dependencies (Tệp > Thêm phần phụ thuộc của gói).
- Nhập https://github.com/googlemaps/ios-places-sdk làm URL, nhấn Enter để kéo gói vào rồi nhấp vào Add Package.
- Nhập https://github.com/googlemaps/ios-maps-sdk làm URL, nhấn Enter để kéo gói vào rồi nhấp vào Add Package.
- 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 26.0 trở lên.
- Nếu bạn chưa có CocoaPods,
hãy cài đặt CocoaPods trên macOS bằng cách chạy lệnh sau từ 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. Lệnh này sẽ cài đặt SDK Bản đồ và SDK Đị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 pod đã cài đặt với mọi bản cập nhật mới. Nếu phát hiện thấy phiên bản mới, hãy chạypod updateđể cập nhậtPodfilevà cài đặt SDK mới nhất. Để biết thêm thông tin chi tiết, 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.
Lấy 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 uỷ quyền sử dụng SDK Bản đồ dành cho iOS và Places API.
- Làm theo hướng dẫn trong phần Bắt đầu sử dụng Google Maps Platform để thiết lập tài khoản thanh toán và một dự án được bật cả hai sản phẩm này.
- Làm theo hướng dẫn trong phần Lấy 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
Thêm khoá API vào AppDelegate.swift như sau:
- Lưu ý rằng câu lệnh nhập sau đây đã đượ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 của bạn: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 hoặc chọn một trình mô phỏng trong trình đơn lược đồ Xcode.
- Nếu bạn đang sử dụng 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 Features (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 tạo ứng dụng, sau đó 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 tập trung xung quanh vị trí hiện tại của bạn.
Gỡ rối:
- Nếu bạn không thấy bản đồ, hãy kiểm tra để đảm bảo bạn đã lấy 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 theo mã nhận dạng gói iOS, hãy chỉnh sửa khoá để thêm mã 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ị đúng cách 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 thiết bị, hãy chuyển đến Settings/General/Privacy/Location Services (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 Simulator/Reset Content and Settings...
- Đảm bảo 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 bạn đã cập nhật Info.plist cho dự án bằng các quyền truy cập 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ác công cụ gỡ lỗi Xcode để xem nhật ký và gỡ lỗi ứng dụng.
Tìm hiểu mã
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 khung hiển thị: Một bộ để hiển thị bản đồ cho thấy địa điểm mà người dùng đã chọn và một bộ để hiển thị cho người dùng danh sách các địa điểm có khả năng để chọn. Lưu ý rằng
mỗi bộ điều khiển khung hiển thị có cùng các biến để theo dõi danh sách các
địa điểm có khả năng (likelyPlaces) và để cho biết lựa chọn của người dùng (selectedPlace). Việc điều hướng giữa các khung hiển thị được
thực hiện bằng cách sử dụng các đoạn chuyển cảnh.
Yêu cầu cấp 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 thêm 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 dự đị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 một vị trí mới. Hướng dẫn này cung cấp mã bạn cần để lấy vị trí của thiết bị. Để biết thêm thông tin chi tiết, hãy xem hướng dẫn Lấy 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, khung hiển thị bản đồ, ứng dụng địa điểm 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à
GMSPlacesClienttrongviewDidLoad(). - Khai báo các biến để giữ danh sách các địa điểm có khả năng và địa điểm mà người dùng đã chọn.
- Thêm đại biểu để xử lý các sự kiện cho trình quản lý vị trí bằng cách sử dụng mệnh đề mở rộng.
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 khung hiển thị trong viewDidLoad() trong bộ điều khiển khung hiển thị chính. Bản đồ vẫn ẩn cho đến khi nhận được thông báo cập nhật vị trí (thông báo cập nhật vị trí được xử lý trong phần mở rộng 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 để lấy 5 địa điểm có khả năng cao nhất 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ó khả năng để điền vào
UITableView, từ đó người dùng có thể chọn địa điểm mà họ đang ở. - Mở chế độ xem mới để trình bày các địa điểm có khả năng cho người dùng. Khi người dùng nhấn vào "Get Place" (Lấy địa điểm), chúng ta sẽ chuyển sang chế độ xem mới và cho người dùng xem danh sách các địa điểm có thể chọn. Hàm
preparecập nhậtPlacesViewControllerbằng danh sách các địa điểm có khả năng hiện tại và được gọi tự động khi thực hiện một đoạn chuyển cảnh. - Trong
PlacesViewController, hãy điền vào bảng bằng danh sách các địa điểm có khả năng cao nhất, sử dụng phần mở rộng đại biểuUITableViewDataSource. - Xử lý lựa chọn của người dùng bằng cách sử dụng phần mở rộng đại biểu
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 chọn, hãy sử dụng đoạn chuyển cảnh huỷ để quay lại khung hiển thị trước đó và thêm điểm đánh dấu vào bản đồ. IBAction unwindToMain được gọi tự động 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 đã tạo một ứng dụng iOS cho phép người dùng chọn địa điểm hiện tại 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 đã học được cách sử dụng SDK Địa điểm dành cho iOS, SDK Bản đồ dành cho iOS và khung Apple Core Location.