美文网首页iOS开发
iOS 自定义大头针

iOS 自定义大头针

作者: CMD独白 | 来源:发表于2016-10-28 11:07 被阅读580次

先了解一下大头针视图:

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}];
 
    }];    
}

相关文章

  • 大头针Annotation

    自定义大头针 使用大头针 点击添加大头针 自定义大头针颜色和动画 系统大头针的处理 自定义大头针图片 修改大头针模...

  • iOS 地图开发(MapKit)(二)

    相关类的介绍:MKAnnotation(大头针协议)大头针数据类(自定义的大头针需要遵守大头针协议)MKPoint...

  • iOS 系统自带API地图开发相关(二)

    地图-自定义大头针 关于大头针视图分两类: MKPinAnnotationView : apple自带的大头针,可...

  • 自定义大头针

    自定义大头针其实没什么东西,讲讲简单的自定义大头针吧! 1.需要定义大头针模型(里面至少有三个属性)#import...

  • 高德地图---iOS笔记摘录

    概念 使用 地图显示 交互 显示 计算 其他 1.1 大头针 自定义大头针: MAPointAnnotation ...

  • 百度地图自定义气泡

    iOS-百度地图自定义气泡IOS百度地图自定义大头针和气泡 重点是定义了一个全局变量来取气泡的数据模型:stati...

  • 百度地图大头针点击之后不调用mapView: viewForAn

    1.如何你自定义的大头针,看看大头针的UIImageView的userInteractionEnabled属性有没...

  • 地图高级 - 自定义大头针

    地图高级 - 自定义大头针 1. 理论支撑 2. 模拟实现系统大头针 实现当添加大头针数据模型时,地图回调的代理方...

  • iOS 自定义大头针

    一、自定义大头针 需求 需求:鼠标拖拽是在地图的哪个位置, 就在对应的位置加一个大头针,并反地理编码大头针所在城市...

  • 高德地图calloutView点击无响应,解决办法

    因为自定义的气泡是添加到大头针上的,而大头针的size只有下面很小一部分,所以calloutView是在大头针的外...

网友评论

    本文标题:iOS 自定义大头针

    本文链接:https://www.haomeiwen.com/subject/rfzsuttx.html