ios-MKMapView上添加大头针

在MKMapView上添加大头针有如下几个步骤

首先我们都知道我们在MapView中获取我们的位置的时候,那个蓝色圆点其实就是一个大头针,有一个对应的大头针模型MKUserLocation

同理我们如果要创建自定义的大头针,也应该有一个模型类,所以这个时候我们需要自己去创建一个大头针模型类

在这个模型类当中,我们需要去让它遵守<MKAnnotation>这个协议,然后在这个协议当中的具体内容如下所示,也就是说我们必须要有的属性就是CLLocationCoordinate2D coordinate,其他是可选。

@protocol MKAnnotation <NSObject>

// Center latitude and longitude of the annotation view.
// The implementation of this property must be KVO compliant.
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

@optional

// Title and subtitle for use by selection UI.
@property (nonatomic, readonly, copy, nullable) NSString *title;
@property (nonatomic, readonly, copy, nullable) NSString *subtitle;

// Called as a result of dragging an annotation view.
- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate NS_AVAILABLE(10_9, 4_0);

@end

下面是自定义的模型类,我们可以把属性直接从上面拷贝下来,然后删除个readonly就可以了。

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface Annotation : NSObject<MKAnnotation>
//包含经纬度的结构体
@property (nonatomic) CLLocationCoordinate2D coordinate;
//标题
@property (nonatomic, copy, nullable) NSString *title;
//子标题
@property (nonatomic, copy, nullable) NSString *subtitle;

@end
有了这个模型类我们就可以去添加大头针了,我们可以考虑根据用户手指所点击的位置,然后去设置大头针,我们可以这么做

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    
    //获取触摸对象
    UITouch * touch = [touches anyObject];
    
    //获取手指所点击的那个点
    CGPoint point = [touch locationInView:self.mapView];
    
    //self.mapView想要转换,将来自mapView中的点转换成经纬度的点
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:point  toCoordinateFromView:self.mapView];
    //创建大头针模型,需要我们自定义大头针的模型类
    Annotation * annotation = [Annotation new];
    
    //设置经纬度
    annotation.coordinate = coordinate;
    //设置标题
    annotation.title = @"爱你";
    annotation.subtitle = @"哈哈";
    
    //添加大头针模型
    [self.mapView addAnnotation:annotation];
}
效果如下所示


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值