MapView添加自定义大头针(Obj-C)

1.创建大头针模型类,遵循<MKMapViewDelegate>协议

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface JSAnnotation : NSObject  <MKAnnotation>
//经纬度
@property (nonatomic) CLLocationCoordinate2D coordinate;
//标题
@property (nonatomic, copy, nullable) NSString *title;
//子标题
@property (nonatomic, copy, nullable) NSString *subtitle;
@end

2.获取屏幕坐标
3.创建自定义大头针模型对象
4.设置大头针模型信息
5.将自定义大头针添加到MapView中

示例代码:

// 添加大头针到点击的位置
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    // 获取touch
    UITouch *touch = touches.anyObject;
    
    // 获取点击屏幕坐标
    CGPoint point = [touch locationInView:touch.view];
    
    // 地图添加大头针模型类,生成模型对象  所有遵守MKAnnotation协议的对象都可以作为大头针的模型
    //创建自定义大头针模型对象
    JSAnnotation *annotation = [[JSAnnotation alloc]init];
    
    
    // 设置数据 (mapView可以对iOS坐标和经纬度进行转化)
    annotation.coordinate = [self.mapView convertPoint:point toCoordinateFromView:touch.view];
    annotation.title = @"自定义大头针";
    annotation.subtitle = @"系统样式";
    
    // mapView中添加大头针
    [self.mapView addAnnotation:annotation];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容