MapKit 是 iOS 內建的地圖框架,可以顯示標準地圖、衛星地圖與混合地圖,也能搭配 CoreLocation 顯示使用者位置,並透過 CLGeocoder 做地址反向解析。
#import <MapKit/MapKit.h>
MKMapView *mapView =
[[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
mapView.delegate = self;
mapView.showsUserLocation = YES;
mapView.mapType = MKMapTypeStandard;
CLLocationCoordinate2D coordinate = {33.00, 112.52};
MKCoordinateSpan span = {5, 5};
MKCoordinateRegion region = {coordinate, span};
[mapView setRegion:region];
[self.view addSubview:mapView];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
取得座標後,可以使用 CLGeocoder 把經緯度轉為地址資訊。
self.geocoder = [[CLGeocoder alloc] init];
[self.geocoder reverseGeocodeLocation:newLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *place in placemarks) {
NSLog(@"name: %@", place.name);
NSLog(@"country: %@", place.country);
NSLog(@"locality: %@", place.locality);
}
}];
執行時若看到 CGBitmapContextCreate: unsupported parameter combination 或 vImage decode failed 的訊息,通常與地圖渲染或圖片資源的位圖設定有關。若地圖仍能顯示,可先確認是否來自特定模擬器、圖片資產或第三方圖層。
MapKit 的基本流程是:建立地圖視圖、設定代理、啟動定位、接收位置更新,最後依需求顯示標註或進行地址解析。