在 iOS 中實作地圖與定位,通常會使用 CoreLocation 與 MapKit 兩個框架。前者負責取得裝置位置,後者負責顯示地圖與管理註解。
開始之前,需要在專案中引入 CoreLocation.framework 與 MapKit.framework,並在需要定位時請求使用者授權。
常見的屬性可以這樣規劃:
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, copy) NSString *currentLatitude;
@property (nonatomic, copy) NSString *currentLongitude;
CLLocationManager 是取得位置的核心。設定精度、距離篩選與授權狀態,是常見初始化步驟。
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager startUpdatingLocation];
}
MKMapView 負責顯示地圖內容。若希望地圖跟隨使用者位置,可以設定 userTrackingMode。
self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
self.mapView.delegate = self;
self.mapView.mapType = MKMapTypeStandard;
self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
[self.view addSubview:self.mapView];
取得經緯度後,可以建立自訂的 MKAnnotation 物件,再透過 showAnnotations 加入地圖。
BasicMapAnnotation *annotation = [[BasicMapAnnotation alloc] initWithLatitude:latitude andLongitude:longitude];
annotation.title = @"目前位置";
[self.mapView showAnnotations:@[annotation] animated:YES];
當定位資料更新時,可以在 MKMapViewDelegate 的 didUpdateUserLocation 中取得最新座標,並更新畫面或重新整理註解。
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
self.currentLatitude = [NSString stringWithFormat:@"%.4f", userLocation.location.coordinate.latitude];
self.currentLongitude = [NSString stringWithFormat:@"%.4f", userLocation.location.coordinate.longitude];
}
若要讓註解顯示自訂圖示,可實作 viewForAnnotation,並使用 dequeueReusableAnnotationViewWithIdentifier 提升復用效率。
整體來說,iOS 地圖與定位的基本流程就是:請求授權、啟動定位、建立地圖、更新座標、顯示註解。掌握這幾個步驟後,再根據需求加入自訂樣式與互動即可。