地图标注
所谓的地图标注就是我们俗称的大头针:
钉在某个具体位置,用来标识这个位置上有特定的事物(比如地图某位置上标注有家餐馆)
大头针的基本操作
添加单个大头针
- (void)addAnnotation:(id <MKAnnotation>)annotation;
添加多个大头针
- (void)addAnnotations:(NSArray *)annotations;
移除一个大头针
- (void)removeAnnotation:(id <MKAnnotation>)annotation;
移除多个大头针
- (void)removeAnnotations:(NSArray *)annotations;
(id <MKAnnotation>)annotation
参数是什么东西?
大头针模型对象:用来封装大头针的数据,比如大头针的位置、标题、子标题等数据
大头针模型
新建一个大头针模型类
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface YXYMKAnnotation : NSObject<MKAnnotation>// 遵守协议,自定义大头针数据模型
/** 坐标位置 */
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
/** 标题 */
@property (nonatomic, copy) NSString *title;
/** 子标题 */
@property (nonatomic, copy) NSString *subtitle;
/** 图标字符串 */
@property (nonatomic, copy) NSString *icon;
@end
自定义大头针
如何自定义大头针:
1.设置MKMapView的代理
2.实现下面的代理方法,返回大头针控件
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;
3.根据传进来的(id )annotation参数创建并返回对应的大头针控件
代理方法的使用注意!
如果返回nil,显示出来的大头针就采取系统的默认样式
标识用户位置的蓝色发光圆点,它也是一个大头针,当显示这个大头针时,也会调用代理方法
因此,需要在代理方法中分清楚(id )annotation参数代表自定义的大头针还是蓝色发光圆点
#pragma mark - MKMapViewDelegate 封装过的代码
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
// 判断如果是定位用户的大头针,用系统自己的大头针样式,而不是用自定义的,防止崩溃
// 返回nil就会按照系统的默认方法创建
if (![annotation isKindOfClass:[YXYMKAnnotation class]]){
return nil;
}
// 调用自定义大头针的方法 -- 获得大头针控件
YXYAnnotationView *annotationView = [YXYAnnotationView annotationViewWithMapView:mapView];
// 传数据(annotationView.annotation是 MKAnnotationView本身具备的属性)
annotationView.annotation = annota