#import "AnnotationViewController.h"
#import <MapKit/MapKit.h>
#import "CustomAnnotation.h"
@interface AnnotationViewController () <MKMapViewDelegate>
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
- (IBAction)addAnnotation:(UIButton *)sender;
@end
@implementation AnnotationViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 跟踪用户位置
self.mapView.userTrackingMode = MKUserTrackingModeFollow;
// 2. 设置地图类型
self.mapView.mapType = MKMapTypeStandard;
// 3. 设置代理
self.mapView.delegate = self;
#pragma mark----添加手势, 给 mapView 添加一个轻拍手势
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapMapView:)];
[self.mapView addGestureRecognizer:tapGR];
}
// 监听 mapView 的轻拍事件
- (void)tapMapView:(UIGestureRecognizer *)tap
{
// 1. 获取用户点击在 mapView 上的位置: x, y
CGPoint point = [tap locationInView:self.mapView];
// 2. 将数学坐标系中的点转换成经纬度坐标
CLLocationCoordinate2D coordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
// 3. 创建大头针模型对象
CustomAnnotation *customAnno = [[CustomAnnotation alloc]init];
#pragma mark---- 必须要实现的属性
// 必须要设置的属性
customAnno.coordinate = coordinate;
customAnno.title = @"hahahahahah";
customAnno.imageName = @"2";
// 4. 将大头针添加到 mapView 上
[self.mapView addAnnotation:customAnno];
}
#pragma mark----实现 MKMapViewDelegate 代理方法
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
}
// 如果想自定义大头针, 需要实现协议中的一个方法
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
// 如果不是自定义的大头针, 则返回
if (![annotation isKindOfClass:[CustomAnnotation class]]) {
return nil;
}
// 先到重用集合中去取 大头针视图对象 (MKAnnotationView)
static NSString *identifier = @"custon";
MKAnnotationView *annotationViewCell = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationViewCell == nil) {
annotationViewCell = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:identifier];
// 显示子标题 title 和 subtitle
annotationViewCell.canShowCallout = YES;
// 设置大头针上显示的描述区域的偏移量
annotationViewCell.calloutOffset = CGPointMake(0, -10); // - 向上, + 向下
// 设置大头针上面显示的描述区域 左右两边的辅助空间
annotationViewCell.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
annotationViewCell.leftCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
}
// 将传过来的 annotation 给 annotationView赋值(传递模型对象)
annotationViewCell.annotation = annotation;
// 设置图片
CustomAnnotation *customAnno = (CustomAnnotation *)annotation;
annotationViewCell.image = [UIImage imageNamed:customAnno.imageName];
return annotationViewCell;
}