現代 App 經常需要定位與地圖功能,例如尋找附近店家、外送追蹤、導航與位置標記。在 iOS 中,主要會使用 CoreLocation 進行定位,使用 MapKit 進行地圖顯示與互動。
CoreLocation 提供位置追蹤與地理編碼功能。最常使用的類別是 CLLocationManager。使用前通常要先檢查定位服務是否開啟,並請求授權。
_locationManager = [[CLLocationManager alloc] init];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服務尚未開啟");
return;
}
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
[_locationManager requestWhenInUseAuthorization];
}
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10.0;
[_locationManager startUpdatingLocation];
定位成功後,會透過代理方法回傳位置。若只需要一次定位,取得結果後可停止更新,以節省電力。
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations firstObject];
NSLog(@"經度:%f, 緯度:%f", location.coordinate.longitude, location.coordinate.latitude);
[manager stopUpdatingLocation];
}
CLGeocoder 可用來做地理編碼與反地理編碼。地理編碼是將地址轉成座標,反地理編碼則是將座標轉成地址資訊。
_geocoder = [[CLGeocoder alloc] init];
[_geocoder geocodeAddressString:@"北京市" completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks firstObject];
NSLog(@"位置:%@", placemark.location);
}];
MapKit 提供 MKMapView,可顯示標準地圖、衛星地圖與混合地圖。常見設定包含地圖類型、使用者追蹤模式與代理。
_mapView = [[MKMapView alloc] initWithFrame:rect];
_mapView.delegate = self;
_mapView.userTrackingMode = MKUserTrackingModeFollow;
_mapView.mapType = MKMapTypeStandard;
[self.view addSubview:_mapView];
開啟使用者位置追蹤後,地圖會顯示目前位置。iOS 8 之後,通常會自動將目前位置設為中心點。

若要在地圖上標記地點,可建立實作 MKAnnotation 協議的物件,再透過 addAnnotation 加入地圖。
@interface KCAnnotation : NSObject
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end
KCAnnotation *annotation = [[KCAnnotation alloc] init];
annotation.title = @"CMJ Studio";
annotation.subtitle = @"Kenshin Cui's Studios";
annotation.coordinate = CLLocationCoordinate2DMake(39.95, 116.35);
[_mapView addAnnotation:annotation];
若需要自訂大頭針樣式,可實作 mapView:viewForAnnotation:,並回傳 MKAnnotationView。

系統預設的大頭針提示框可能無法滿足需求。常見做法是點擊一般大頭針後,再動態加入另一個作為提示框的大頭針,並回傳自訂 MKAnnotationView。

這種方式可以自訂圖示、文字、星等與背景樣式,適合需要展示店家資訊、評價或摘要的情境。

若不需要高度自訂,也可以直接開啟 Apple 自帶地圖。MKMapItem 提供 openInMapsWithLaunchOptions 與 openMapsWithItems:launchOptions:,可用來標記單一位置、標記多個位置或進行路線規劃。
MKPlacemark *mkPlacemark = [[MKPlacemark alloc] initWithPlacemark:clPlacemark];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:mkPlacemark];
[mapItem openInMapsWithLaunchOptions:options];

若要同時標記多個地點,可建立多個 MKMapItem,再使用靜態方法一次開啟。
[MKMapItem openMapsWithItems:@[mapItem1, mapItem2] launchOptions:options];

若需要導航,可在 options 中加入路線模式,例如駕車或步行。系統會依設定規劃路線。
NSDictionary *options = @{
MKLaunchOptionsMapTypeKey: @(MKMapTypeStandard),
MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving
};
[MKMapItem openMapsWithItems:@[mapItem1, mapItem2] launchOptions:options];
