- 实现之后的效果图
- 什么是大头针
-
现实生活中的大头针(下图)
- 地图上的大头针(下图)
- 钉在某个具体位置,用来标识这个位置上有特定的事物(比如这个位置上有加餐馆)
基本使用
- 先创建好地图视图
- 在故事板中将一个MapView加到viewController中
- 导入框架
- 自己自定义一个大头针模型
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface LCAnno : NSObject<MKAnnotation>
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy, nullable) NSString *title;
@property (nonatomic, copy, nullable) NSString *subtitle;
@end
- 定义一个添加大头针的方法
- (void)addAnnoWithPT:(CLLocationCoordinate2D)pt{
__block LCAnno *anno = [[LCAnno alloc]init];
anno.coordinate = pt;
anno.title = @"大神";
anno.subtitle = @"在这里";
[self.mapView addAnnotation:anno];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:anno.coordinate.latitude longitude:anno.coordinate.longitude];
[self.geoC reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *pl = [placemarks firstObject];
anno.title = pl.locality;
anno.subtitle = pl.thoroughfare;
}];
}
- 屏幕的触摸事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//1.获取当前触摸点
CGPoint point = [[touches anyObject] locationInView:self.mapView];
//2.转换成经纬度
CLLocationCoordinate2D pt = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
//3.添加大头针
[self addAnnoWithPT:pt];
}
- 移动屏幕时,移除大头针视图
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//移除大头针(模型)
NSArray *annos = self.mapView.annotations;
[self.mapView removeAnnotations:annos];
}
- 代码链接
- 点击下载代码