- 创建自定义标注类:
- 自定义标注类需继承自
MKPointAnnotation
,这样可以在地图上表示一个点标注。
- 示例代码:
#import <MapKit/MapKit.h>
@interface CustomAnnotation : MKPointAnnotation
// 可以在这里添加自定义属性,比如图片、详细描述等
@property (nonatomic, strong) NSString *customTitle;
@property (nonatomic, strong) NSString *customSubtitle;
@end
@implementation CustomAnnotation
@end
- 添加标注到地图:
- 获取地图视图
MKMapView
的实例。
- 创建自定义标注的实例,并设置其坐标、标题等属性。
- 将标注添加到地图视图。
- 示例代码:
#import "ViewController.h"
#import "CustomAnnotation.h"
@interface ViewController () <MKMapViewDelegate>
@property (nonatomic, strong) MKMapView *mapView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化地图视图
self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.mapView];
self.mapView.delegate = self;
// 创建自定义标注
CustomAnnotation *annotation = [[CustomAnnotation alloc] init];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(37.7749, -122.4194); // 示例坐标
annotation.coordinate = coordinate;
annotation.customTitle = @"自定义标题";
annotation.customSubtitle = @"自定义副标题";
// 添加标注到地图
[self.mapView addAnnotation:annotation];
}
@end
- 自定义标注视图(可选,若需要自定义外观):
- 实现
MKMapViewDelegate
的mapView:viewForAnnotation:
方法。
- 在该方法中,为自定义标注创建自定义的
MKAnnotationView
。
- 示例代码:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:[CustomAnnotation class]]) {
static NSString *identifier = @"CustomAnnotationView";
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (!annotationView) {
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
}
annotationView.image = [UIImage imageNamed:@"customAnnotationImage.png"]; // 自定义图片
annotationView.canShowCallout = YES;
return annotationView;
}
return nil;
}