iOS 自定义大头针

先了解一下大头针视图:

MKPinAnnotationView :不能改变大头针的图片 可以改变颜色
MKAnnotationView:自己随意定义大头针的样式

大头针使用的一些属性:

《1》初始化initWithAnnotation:reuseIdentifier:
《2》image 设置大头针图片
《3》centerOffset 中心点的偏移量 x正右 y正下
《4》calloutOffset 插图的偏移量
《5》enabled 是否激活 默认YES
《6》highlighted 是否高亮 默认NO
《9》selected 是否选中
《10》canShowCallout 设置是否可以显示 插入视图
《11》leftCalloutAccessoryView 左侧插入视图的附加视图
《12》rightCalloutAccessoryView:右侧插入视图的附加视图
《13》detailCalloutAccessoryView iOS9之后出现 插入视图的详细视图
《14》draggable 是否可以拖拽
《15》dragState 拖拽的状态

代码主要实现了:

  • 地图添加 大头针 并且保存到本地
    1.判断有没有可以读取的大头针模型数据
    2.如果有 读取添加到地图上
    3.添加大头针的时候 同时把大头针数据 存到数组中
    4.退出页面的时候 对数组 数据持久化
  • 长按地图上的某个点 添加一个大头针,大头针显示地理位置的真实信息
    1.添加长按手势
    2.添加一个大头针数据模型 到地图上
    《1》视图上的point 需要转换成经纬度
    《2》把数据模型添加到地图上
    addAnnotation:添加一个大头针数据模型
    addAnnotations:添加一组大头针数据模型
  • 移除大头针
    removeAnnotation :移除一个
    removeAnnotations :移除多个

代码如下:

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<MKMapViewDelegate>
{
    CLLocationManager *locationManger;
    MKMapView *myMapView;
    NSMutableArray *allAnnotationsArray;
    
}

@property (nonatomic,strong) CLGeocoder *geoCoder;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    if (![CLLocationManager locationServicesEnabled]) {
      UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请在设置中打开定位功能" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:action];
        
        [self presentViewController:alertController animated:YES completion:nil];

    }
    locationManger = [[CLLocationManager alloc]init];
    [locationManger requestWhenInUseAuthorization];
    myMapView = [[MKMapView alloc]initWithFrame:self.view.frame];
    myMapView.mapType = MKMapTypeStandard;
    myMapView.showsUserLocation = YES;
    myMapView.delegate = self;
    [self.view addSubview:myMapView];
    
    UILongPressGestureRecognizer *addPin = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(addPin:)];
    [myMapView addGestureRecognizer:addPin];    
}

地图代理方法:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
    MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
    MKCoordinateRegion regin = MKCoordinateRegionMake(userLocation.location.coordinate, span);
    [mapView setRegion:regin animated:YES];
    
//    userLocation -> MKUserLocation ->大头针数据模型(用户)->遵守
//    MKAnnotation协议 ->经纬度  标题  副标题
//    MKUserLocation 经纬度  标题  副标题 航向 location
    userLocation.title = @"深圳市龙岗区"; 
}

在这里可以设置大头针的图片、位置等:

- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    
    //    判断是不是用户的大头针数据模型
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        
        MKAnnotationView *userView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"user"];
        
        //        image 设置大头针视图的图片
        userView.image = [UIImage imageNamed:@"7"];
        
        //  是否允许显示插入视图
        userView.canShowCallout = YES;
        
        //设置大头针视图中心点偏移
        //x 正 -> 向右
        //Y 正 -> 向下
        userView.centerOffset = CGPointMake(100, -100);
        
        //设置大头针插入视图的 偏移量
        userView.calloutOffset = CGPointMake(-50, 0);
        
        //设置大头针视图  是否可以拖动
        userView.draggable = YES;
        
        //设置配件视图
        
        UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        leftView.image = [UIImage imageNamed:@"7"];
        userView.leftCalloutAccessoryView = leftView;
        
        UIImageView *rightView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        rightView.image = [UIImage imageNamed:@"7"];
        userView.rightCalloutAccessoryView = rightView;
        
 UIImageView *detailView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        detailView.image = [UIImage imageNamed:@"7"];
        userView.detailCalloutAccessoryView = detailView;
        return userView;
    }
    
    return nil;
}
//定位成功的代理方法
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations{
    NSLog(@"定位成功");
    //此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    
    CLLocation *currentLocation = [locations lastObject];
    
    NSLog(@"locations===%@",[locations lastObject]);
//    [self ungeocoder:currentLocation];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     
     {
         if (array.count > 0)
             
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
            NSLog(@"%@",placemark.name);

             //获取城市
             
             NSString *city = placemark.locality;
             
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                 city = placemark.administrativeArea;
                 
             }
             NSLog(@"%@",city);

         }
         
         else if (error == nil && [array count] == 0)
             
         {
             NSLog(@"No results were returned.");
         }
         
         else if (error != nil)
             
         {
          NSLog(@"An error occurred = %@", error);
             
         }
         
     }];
    
    //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
    
    [manager stopUpdatingLocation];
}

//定位失败的代理方法
- (void)locationManager:(CLLocationManager *)manager

       didFailWithError:(NSError *)error {
    
    NSLog(@"定位失败");
    
    if (error.code == kCLErrorDenied) {
        
        // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在
        
    }
}

把大头针保存到本地,代码如下:

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    作.判断有没有可以读取的大头针数据模型
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isSave"]) {
        
        allAnnotationsArray = [[[NSUserDefaults standardUserDefaults]arrayForKey:@"allAnnotationsArray"] mutableCopy];
        
        NSMutableArray *dataList = [NSMutableArray array];
        for (NSDictionary *info in allAnnotationsArray) {
            MKPointAnnotation *an = [[MKPointAnnotation alloc]init];
            an.coordinate = CLLocationCoordinate2DMake([info[@"coordinate"][@"latitude"] doubleValue], [info[@"coordinate"][@"longitude"] doubleValue]);
            an.title = info[@"title"];
            [dataList addObject:an];
        }
        
        // 作第二步
        [myMapView addAnnotations:dataList];
        
    }else{
        allAnnotationsArray = [NSMutableArray array];
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    if (allAnnotationsArray.count != 0) {
        [defaults setObject:allAnnotationsArray forKey:@"allAnnotationsArray"];
        [defaults setBool:YES forKey:@"isSave"];
    }
    //    多线程同步  方式保存
    [defaults synchronize];    
}

长按屏幕,添加大头针,代码如下:

- (void)addPin:(UILongPressGestureRecognizer *)sender{
    
    if (sender.state != UIGestureRecognizerStateBegan) {
    return;
    }
    
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
    
    
//    通过手势  得到手指 触摸的点 -> point
    CGPoint point = [sender locationInView:self.view];
    
//    通过地图类的对象  把点转换成经纬度
    CLLocationCoordinate2D coordinate = [myMapView convertPoint:point toCoordinateFromView:sender.view];
    
  [self.geoCoder reverseGeocodeLocation:[[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude] completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        annotation.coordinate = coordinate;
        annotation.title = placemarks.firstObject.name;
       [myMapView addAnnotation:annotation];
        
//        作第三步  添加大头针地图的时候  同时添加到数组
        [allAnnotationsArray addObject:@{@"coordinate":@{@"latitude":@(coordinate.latitude),@"longitude":@(coordinate.longitude)},@"title":placemarks.firstObject.name}];
 
    }];    
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,511评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,495评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,595评论 0 225
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,558评论 0 190
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,715评论 3 270
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,672评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,112评论 2 291
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,837评论 0 181
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,417评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,928评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,316评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,773评论 2 234
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,253评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,827评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,440评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,523评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,583评论 2 249

推荐阅读更多精彩内容