MapKit 能做的事比很多人想象的多:標注、繪製線條多邊形圓圈、熱點搜索、正向地理編碼、自定義大頭針視圖,全都在系統框架之內。本文用一個完整示例把它們串起來。
1. 在 Info.plist 中加入定位用途說明:
<!-- 使用期間允許定位 --> NSLocationWhenInUseUsageDescription → "需要定位嗎?" <!-- 始終允許定位(含後台),與上一項二選一 --> NSLocationAlwaysUsageDescription → "確定定位嗎?" // 對應代碼 [_locationManager requestWhenInUseAuthorization]; [_locationManager requestAlwaysAuthorization];
2. 引入兩個系統庫:MapKit.framework 與 CoreLocation.framework。
3. 示例同時演示系統自帶的 MKPointAnnotation / MKPinAnnotationView,以及自定義版本。
- (void)createMapView {
_mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
// 地圖模式:Standard 標準、Satellite 衛星、Hybrid 混合
_mapView.mapType = MKMapTypeStandard;
// 初始中心點
CLLocationCoordinate2D location = CLLocationCoordinate2DMake(36.083743, 120.366486);
_mapView.region = MKCoordinateRegionMakeWithDistance(location, 1000, 1000);
_mapView.zoomEnabled = YES;
_mapView.scrollEnabled = YES;
// 定位服務已開啟時才顯示藍點
if ([CLLocationManager locationServicesEnabled] == YES) {
_mapView.showsUserLocation = YES;
// None 不跟隨;Follow 保持正北;FollowWithHeading 地圖隨設備方向旋轉
[_mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:YES];
}
_mapView.delegate = self;
[self.view addSubview:_mapView];
}
這個代理方法有一個容易忽略的細節:刷新時用戶的藍點也會被傳進來,所以必須先判斷類型,否則藍點會被替換成自定義大頭針。
- (MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKPointAnnotation class]] == NO) {
return nil; // 交給系統處理藍點
}
return [self customMethodWithMapView:mapView andAnnotation:annotation];
}
// 系統樣式
- (MKPinAnnotationView *)systemMethodWithMapView:(MKMapView *)mapView
andAnnotation:(MKPointAnnotation *)annotation {
MKPinAnnotationView *annotationView =
(MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"AnnotationView"];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:@"AnnotationView"];
annotationView.pinColor = MKPinAnnotationColorPurple; // 紅、綠、紫
annotationView.canShowCallout = YES; // 允許彈出氣泡
annotationView.animatesDrop = YES; // 落下動畫
annotationView.draggable = YES; // 可拖拽
} else {
annotationView.annotation = annotation;
}
return annotationView;
}
// 自定義樣式
- (MKPinAnnotationView *)customMethodWithMapView:(MKMapView *)mapView
andAnnotation:(MKPointAnnotation *)annotation {
MyAnnotationView *annotationView =
(MyAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomAnnotationView"];
if (annotationView == nil) {
annotationView = [[MyAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:@"CustomAnnotationView"];
} else {
annotationView.annotation = annotation;
}
return annotationView;
}
這裡的復用機制與 UITableView 完全一致:先從隊列取,取不到才新建。
- (void)createAnnotations {
MKPointAnnotation *annotation1 = [[MKPointAnnotation alloc] init];
annotation1.title = @"不知道是哪";
annotation1.subtitle = @"真不知道是哪兒";
annotation1.coordinate = CLLocationCoordinate2DMake(-39.89, -79.88);
[_mapView addAnnotation:annotation1];
MKPointAnnotation *annotation2 = [[MKPointAnnotation alloc] init];
annotation2.title = @"南半球";
annotation2.subtitle = @"真是南半球";
annotation2.coordinate = CLLocationCoordinate2DMake(-80.89, 156.456);
[_mapView addAnnotation:annotation2];
// 自定義標注模型,多帶一個 information 字段
MyPointAnnotation *annotation3 = [[MyPointAnnotation alloc]
initWithCoorDinate:CLLocationCoordinate2DMake(40.5, -88.7)
title:@"第一個位置"
subTitle:@"這裡風景優美"
information:@"這裡是國家級旅游景點"];
MyPointAnnotation *annotation4 = [[MyPointAnnotation alloc]
initWithCoorDinate:CLLocationCoordinate2DMake(37.68, -96.54)
title:@"第二個位置"
subTitle:@"這裡有點冷"
information:@"世界冰展所在地"];
[_mapView addAnnotations:@[annotation3, annotation4]];
_mapView.centerCoordinate = annotation1.coordinate;
}
- (void)overLay {
[self pathOverLay];
[self polyOverlay];
[self circleOverlay];
}
// 折線
- (void)pathOverLay {
CLLocationCoordinate2D coords[6] = {
CLLocationCoordinate2DMake(33.123, -77.456),
CLLocationCoordinate2DMake(34.123, -78.456),
CLLocationCoordinate2DMake(32.123, -79.456),
CLLocationCoordinate2DMake(36.123, -71.456),
CLLocationCoordinate2DMake(35.123, -70.456),
CLLocationCoordinate2DMake(36.123, 73.456)
};
[_mapView addOverlay:[MKPolyline polylineWithCoordinates:coords count:6]];
}
// 多邊形:首尾坐標必須重合,否則無法閉合
- (void)polyOverlay {
CLLocationCoordinate2D coords[5] = {
CLLocationCoordinate2DMake(35.443, -77.876),
CLLocationCoordinate2DMake(36.553, -77.976),
CLLocationCoordinate2DMake(35.553, -79.567),
CLLocationCoordinate2DMake(34.443, -79.567),
CLLocationCoordinate2DMake(35.443, -77.876)
};
[_mapView addOverlay:[MKPolygon polygonWithCoordinates:coords count:5]];
}
// 圓
- (void)circleOverlay {
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(37.68, -96.54);
[_mapView addOverlay:[MKCircle circleWithCenterCoordinate:center radius:100000]];
}
// 統一管理覆蓋層渲染
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView
rendererForOverlay:(id<MKOverlay>)overlay {
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolylineRenderer *line = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
line.lineWidth = 2;
line.strokeColor = [UIColor blueColor];
return line;
} else if ([overlay isKindOfClass:[MKPolygon class]]) {
MKPolygonRenderer *poly = [[MKPolygonRenderer alloc] initWithOverlay:overlay];
poly.lineWidth = 1;
poly.strokeColor = [UIColor greenColor];
poly.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
return poly;
} else if ([overlay isKindOfClass:[MKCircle class]]) {
MKCircleRenderer *circle = [[MKCircleRenderer alloc] initWithOverlay:overlay];
circle.lineWidth = 1;
circle.strokeColor = [UIColor redColor];
circle.fillColor = [[UIColor greenColor] colorWithAlphaComponent:0.4];
return circle;
}
return nil;
}
- (void)createUI {
_userLocationLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, 320, 80)];
[self.view addSubview:_userLocationLable];
// 一鍵回到用戶位置
MKUserTrackingBarButtonItem *item =
[[MKUserTrackingBarButtonItem alloc] initWithMapView:_mapView];
self.navigationItem.leftBarButtonItem = item;
UIButton *hotSearchButton = [UIButton buttonWithType:UIButtonTypeCustom];
hotSearchButton.frame = CGRectMake(0, 64, 100, 40);
[hotSearchButton setTitle:@"熱點搜索" forState:UIControlStateNormal];
[hotSearchButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[hotSearchButton addTarget:self action:@selector(hotSeatch)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:hotSearchButton];
UIButton *keywordSearchButton = [UIButton buttonWithType:UIButtonTypeCustom];
keywordSearchButton.frame = CGRectMake(100, 64, 100, 40);
[keywordSearchButton setTitle:@"關鍵字搜索" forState:UIControlStateNormal];
[keywordSearchButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[keywordSearchButton addTarget:self action:@selector(keywordSearch)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:keywordSearchButton];
// 長按添加大頭針
UILongPressGestureRecognizer *longPress =
[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
longPress.minimumPressDuration = 1;
[_mapView addGestureRecognizer:longPress];
}
- (void)longPress:(UILongPressGestureRecognizer *)longPress {
if (longPress.state != UIGestureRecognizerStateBegan) return;
CGPoint point = [longPress locationInView:_mapView];
CLLocationCoordinate2D coordinate = [_mapView convertPoint:point
toCoordinateFromView:_mapView];
MyPointAnnotation *annotation = [[MyPointAnnotation alloc]
initWithCoorDinate:coordinate
title:@"手勢加入"
subTitle:@"長按手勢"
information:@"長按手勢信息"];
[_mapView addAnnotation:annotation];
}
// 定位更新
- (void)mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation {
_userLocationLable.text = [NSString stringWithFormat:@"用戶位置: %.5f, %.5f",
userLocation.coordinate.latitude,
userLocation.coordinate.longitude];
}
MKLocalSearchRequest 的 naturalLanguageQuery 接受自然語言,這是它最強的地方。
- (void)hotSeatch {
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = @"學校";
CLLocationCoordinate2D origin = CLLocationCoordinate2DMake(36.08397, 120.37126);
MKCoordinateSpan span = MKCoordinateSpanMake(0.3, 0.3);
MKCoordinateRegion region = MKCoordinateRegionMake(origin, span);
request.region = region;
[_mapView setRegion:region];
MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response,
NSError * _Nullable error) {
if (error) {
NSLog(@"搜索失敗");
return;
}
for (MKMapItem *item in response.mapItems) {
MKPlacemark *placeMark = item.placemark;
MyPointAnnotation *annotation = [[MyPointAnnotation alloc]
initWithCoorDinate:placeMark.location.coordinate
title:placeMark.name
subTitle:placeMark.locality
information:placeMark.locality];
[_mapView addAnnotation:annotation];
}
}];
}
- (void)keywordSearch {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:@"青島科技大學" completionHandler:^(NSArray<CLPlacemark> * _Nullable placemarks,
NSError * _Nullable error) {
if (error) {
NSLog(@"正向地理編碼解析失敗");
return;
}
for (CLPlacemark *place in placemarks) {
MyPointAnnotation *annotation = [[MyPointAnnotation alloc]
initWithCoorDinate:place.location.coordinate
title:place.name
subTitle:place.locality
information:place.locality];
[_mapView addAnnotation:annotation];
}
}];
}
// MyPointAnnotation.h
#import <MapKit/MapKit.h>
@interface MyPointAnnotation : MKPointAnnotation
@property (nonatomic, copy) NSString *information;
- (id)initWithCoorDinate:(CLLocationCoordinate2D)coordinate
title:(NSString *)title
subTitle:(NSString *)subTitle
information:(NSString *)information;
@end
// MyPointAnnotation.m
@implementation MyPointAnnotation
- (id)initWithCoorDinate:(CLLocationCoordinate2D)coordinate
title:(NSString *)title
subTitle:(NSString *)subTitle
information:(NSString *)information {
if (self = [super init]) {
self.title = title;
self.subtitle = subTitle;
self.coordinate = coordinate;
self.information = information;
}
return self;
}
@end
// MyAnnotationView.m
@implementation MyAnnotationView
- (instancetype)initWithAnnotation:(id<MKAnnotation>)annotation
reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]) {
myPointAnnotation = annotation;
UIImage *image = [UIImage imageNamed:@"pink"];
// 直接設 self.image 只適合靜態圖片,與拖拽、動畫會衝突。
// 那種做法需要改繼承 MKAnnotationView。這裡用子視圖更靈活。
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(-15, -5, 45, 45)];
imageView.image = image;
[self addSubview:imageView];
self.canShowCallout = YES;
self.draggable = YES;
self.animatesDrop = YES;
UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[leftButton addTarget:self action:@selector(leftButton)
forControlEvents:UIControlEventTouchUpInside];
self.leftCalloutAccessoryView = leftButton;
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
[rightButton addTarget:self action:@selector(rightButton)
forControlEvents:UIControlEventTouchUpInside];
self.rightCalloutAccessoryView = rightButton;
}
return self;
}
- (void)leftButton { NSLog(@"leftButton:%@", myPointAnnotation.title); }
- (void)rightButton { NSLog(@"rightButton:%@", myPointAnnotation.information); }
@end
最後提醒兩點: MKUserTrackingBarButtonItem 需要把 ViewController 包進 UINavigationController 才能顯示; MKLocalSearch 的 completionHandler 在子線程回調,更新 UI 前記得切回主線程。