iOS 地图的奇技淫巧

MapKit

2016-07-18  本文已影响1641人  英雄出少年

MapKit框架的基本使用

用于地图展示,例如大头针,路线、覆盖层展示等(着重界面展示)
导入主头文件 #import <MapKit/MapKit.h>
MapKit有一个比较重要的UI控件:MKMapView,专门用于地图显示


![MKMapTypeSatelliteFlyover.png](https://img.haomeiwen.com/i1116822/46296b71a1c4867f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) MKMapTypeSatellite.png MKMapTypeHybridFlyover.png MKMapTypeHybrid.png


@interface ViewController ()
@property (weak, nonatomic) IBOutlet MKMapView *mapView;


/** 位置管理者 */
@property (nonatomic, strong) CLLocationManager *locationM;


@end

@implementation ViewController


#pragma mark -懒加载
-(CLLocationManager *)locationM
{
    if (!_locationM) {
        _locationM = [[CLLocationManager alloc] init];
        
        
        // 版本适配
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [_locationM requestAlwaysAuthorization];
        }

    }
    return _locationM;
}



- (void)viewDidLoad {
    [super viewDidLoad];
 
//    MKMapTypeStandard = 0, // 标准地图
//    MKMapTypeSatellite, // 卫星云图
//    MKMapTypeHybrid, // 混合(在卫星云图上加了标准地图的覆盖层)
//    MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D立体
//    MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D混合
    // 设置地图显示样式(必须注意,设置时 注意对应的版本)
    self.mapView.mapType = MKMapTypeStandard;
    
    // 设置地图的控制项
    // 是否可以滚动
//    self.mapView.scrollEnabled = NO;
    // 缩放
//    self.mapView.zoomEnabled = NO;
    // 旋转
//    self.mapView.rotateEnabled = NO;
    
    // 设置地图的显示项(注意::版本适配)
    // 显示建筑物
    self.mapView.showsBuildings = YES;
    // 指南针
    self.mapView.showsCompass = YES;
    // 兴趣点
    self.mapView.showsPointsOfInterest = YES;
    // 比例尺
    self.mapView.showsScale = YES;
    // 交通
    self.mapView.showsTraffic = YES;
    
    
    // 显示用户位置
    [self locationM];
    // 显示用户位置, 但是地图并不会自动放大到合适比例
//   self.mapView.showsUserLocation = YES;
    
    /**
     *  MKUserTrackingModeNone = 0, 不追踪
     MKUserTrackingModeFollow,  追踪
     MKUserTrackingModeFollowWithHeading, 带方向的追踪
     */
    // 不但显示用户位置, 而且还会自动放大地图到合适的比例(也要进行定位授权)
    // 不灵光
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
}


@end

MapKit框架的中级使用--区域显示


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

@interface ViewController ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;


/** 位置管理者 */
@property (nonatomic, strong) CLLocationManager *locationM;


@end

@implementation ViewController


#pragma mark -懒加载
-(CLLocationManager *)locationM
{
    if (!_locationM) {
        _locationM = [[CLLocationManager alloc] init];
        
        
        // 版本适配
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [_locationM requestAlwaysAuthorization];
        }

    }
    return _locationM;
}



- (void)viewDidLoad {
    [super viewDidLoad];
 
//    MKMapTypeStandard = 0, // 标准地图
//    MKMapTypeSatellite, // 卫星云图
//    MKMapTypeHybrid, // 混合(在卫星云图上加了标准地图的覆盖层)
//    MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D立体
//    MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D混合
    // 设置地图显示样式(必须注意,设置时 注意对应的版本)
    self.mapView.mapType = MKMapTypeStandard;
    
 
    // 设置地图的控制项
    // 是否可以滚动
//    self.mapView.scrollEnabled = NO;
    // 缩放
//    self.mapView.zoomEnabled = NO;
    // 旋转
//    self.mapView.rotateEnabled = NO;
    
    
    // 设置地图的显示项(注意::版本适配)
    // 显示建筑物
    self.mapView.showsBuildings = YES;
    // 指南针
    self.mapView.showsCompass = YES;
    // 兴趣点
    self.mapView.showsPointsOfInterest = YES;
    // 比例尺
    self.mapView.showsScale = YES;
    // 交通
    self.mapView.showsTraffic = YES;
    
    // 显示用户位置
    [self locationM];
    // 显示用户位置, 但是地图并不会自动放大到合适比例
   self.mapView.showsUserLocation = YES;
    
    /**
     *  MKUserTrackingModeNone = 0, 不追踪
     MKUserTrackingModeFollow,  追踪
     MKUserTrackingModeFollowWithHeading, 带方向的追踪
     */
    // 不但显示用户位置, 而且还会自动放大地图到合适的比例(也要进行定位授权)
    // 不灵光
//    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}




#pragma mark -MKMapViewDelegate 
/**
 *  当地图获取到用户位置时调用
 *
 *  @param mapView      地图
 *  @param userLocation 大头针数据模型
 */
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    /**
     *  MKUserLocation : 专业术语: 大头针模型 其实喊什么都行, 只不过这个类遵循了大头针数据模型必须遵循的一个协议 MKAnnotation 
     // title : 标注的标题
     // subtitle : 标注的子标题
     */
    userLocation.title = @"小码哥";
    userLocation.subtitle = @"大神三期";
    
    // 移动地图的中心,显示用户的当前位置
//    [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
    
    // 显示地图的显示区域
    
    // 控制区域中心
    CLLocationCoordinate2D center = userLocation.location.coordinate;
    // 设置区域跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(0.077919, 0.044529);

    // 创建一个区域
    MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
    // 设置地图显示区域
    [mapView setRegion:region animated:YES];
    
}

/**
 *  地图区域已经改变时调用 --- 先缩放 获取经纬度跨度,根据经纬度跨度显示区域
 *
 *  @param mapView  地图
 *  @param animated 动画
 */
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    NSLog(@"%f---%f", mapView.region.span.latitudeDelta, mapView.region.span.longitudeDelta);
}

/**
 *  地图区域将要改变时带哦用
 *
 *  @param mapView  地图
 *  @param animated 动画
 */
-(void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    
}
@end

MapKit框架的高级使用--大头针

自定义大头针( TGAnnotation)

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface TGAnnotation : NSObject<MKAnnotation>
// 控制大头针扎在地图上哪个位置
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

// 控制大头针弹框显示的标题
@property (nonatomic, copy, nullable) NSString *title;
// 控制大头针弹框显示的子标题
@property (nonatomic, copy, nullable) NSString *subtitle;
@end



#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "TGAnnotation.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<MKMapViewDelegate>

@property (weak, nonatomic) IBOutlet MKMapView *mapView;

/** 地理编码 */
@property (nonatomic, strong) CLGeocoder *geoC;

@end

@implementation ViewController

#pragma mark -懒加载
-(CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}


/**
 *  在地图上操作大头针, 就等于操作大头针数据模型
 *  添加大头针: 添加大头针数据模型
 *  删除大头针: 删除大头针数据模型
 */

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 要求, 鼠标点击地图的哪个位置, 就在对应的位置加一个大头针
    
    // 1. 获取当前用户在屏幕上点击的点坐标
    UITouch *touch = [touches anyObject];
    CGPoint center = [touch locationInView:self.mapView];
    
    // 2. 把点坐标 转换成 在地图对应的地理坐标
    CLLocationCoordinate2D centerCoordinate = [self.mapView convertPoint:center toCoordinateFromView:self.mapView];
    
    // 3. 设置弹框标题和子标题
    NSString *title = @"连线";
    NSString *subTitle = @"iOS技术部";
    
    // 4. 调用自定义方法, 添加大头针数据模型
    TGAnnotation *annotation = [self addAnnotationWithCoordinate:centerCoordinate title:title andSubtitle:subTitle];

    // 反地理编码
    CLLocation *location = [[CLLocation alloc] initWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];
    [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        // 地标对象
        CLPlacemark *pl = [placemarks firstObject];
        
        // 取详细地址
        NSString *name = pl.name;
        
        // 获取城市
        NSString *city = pl.locality;
        
        annotation.title = city;
        annotation.subtitle = name;
  
    }];
    

}


-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    // 获取地图上所有的大头针数据模型
    NSArray *annotations = self.mapView.annotations;
    
    // 移除大头针
    [self.mapView removeAnnotations:annotations];
}

/**
 *  自定义方法,添加大头针
 *
 *  @param center   大头针扎在哪
 *  @param title    弹框标题
 *  @param subTitle 弹框子标题
 */
- (TGAnnotation *)addAnnotationWithCoordinate:(CLLocationCoordinate2D)center title:(NSString *)title andSubtitle:(NSString *)subTitle
{
 
    TGAnnotation *annotation = [[TGAnnotation alloc] init];
    annotation.coordinate = center;
    
    annotation.title = title;
    annotation.subtitle = subTitle;
    
    [self.mapView addAnnotation:annotation];
    return annotation;
    
}


- (void)addAnnotation
{
    // 添加大头针 == 添加大头针数据模型
    
    // 1. 创建大头针数据模型
    TGAnnotation *annotation = [[TGAnnotation alloc] init];
    // 1.1 设置经纬度
    annotation.coordinate = self.mapView.centerCoordinate;
    // 1.2 弹框标题
    annotation.title = @"连线";
    // 1.3 弹框子标题
    annotation.subtitle = @"iOS研发部";
    
    // 添加大头针数据模型
    [self.mapView addAnnotation:annotation];
    
}



#pragma mark -'MKMapViewDelegate

/**
 *  地图定位到之后调用
 *
 *  @param mapView      地图
 *  @param userLocation 大头针数据模型
 */
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    
}



@end



#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "XMGAnnotation.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<MKMapViewDelegate>

@property (weak, nonatomic) IBOutlet MKMapView *mapView;

/** 位置管理者 */
@property (nonatomic, strong) CLLocationManager *locationM;



/** 地理编码 */
@property (nonatomic, strong) CLGeocoder *geoC;


@end

@implementation ViewController


-(CLLocationManager *)locationM
{
    if (!_locationM) {
        _locationM = [[CLLocationManager alloc] init];
        
        [_locationM requestAlwaysAuthorization];
    }
    return _locationM;
}

#pragma mark -懒加载
-(CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}


/**
 *  在地图上操作大头针, 就等于操作大头针数据模型
 *  添加大头针: 添加大头针数据模型
 *  删除大头针: 删除大头针数据模型
 */




-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 要求, 鼠标点击地图的哪个位置, 就在对应的位置加一个大头针
    
    // 1. 获取当前用户在屏幕上点击的点坐标
//    UITouch *touch = [touches anyObject];
//    CGPoint center = [touch locationInView:self.mapView];
//    
//    // 2. 把点坐标 转换成 在地图对应的地理坐标
//    CLLocationCoordinate2D centerCoordinate = [self.mapView convertPoint:center toCoordinateFromView:self.mapView];
//    
//    // 3. 设置弹框标题和子标题
//    NSString *title = @"小码哥";
//    NSString *subTitle = @"大神三期";
//    
//    // 4. 调用自定义方法, 添加大头针数据模型
//    XMGAnnotation *annotation = [self addAnnotationWithCoordinate:centerCoordinate title:title andSubtitle:subTitle];
//
//    // 反地理编码
//    CLLocation *location = [[CLLocation alloc] initWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];
//    [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        // 地标对象
//        CLPlacemark *pl = [placemarks firstObject];
//        
//        // 取详细地址
//        NSString *name = pl.name;
//        
//        // 获取城市
//        NSString *city = pl.locality;
//        
//        annotation.title = city;
//        annotation.subtitle = name;
//  
//    }];
    [self locationM];
    
    // 在地图上根据当前用户位置, 添加了一个大头针视图
    self.mapView.showsUserLocation = YES;

}


-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    // 获取地图上所有的大头针数据模型
//    NSArray *annotations = self.mapView.annotations;
    
    // 移除大头针
//    [self.mapView removeAnnotations:annotations];
    
       [self addAnnotation];
}

/**
 *  自定义方法,添加大头针
 *
 *  @param center   大头针扎在哪
 *  @param title    弹框标题
 *  @param subTitle 弹框子标题
 */
- (XMGAnnotation *)addAnnotationWithCoordinate:(CLLocationCoordinate2D)center title:(NSString *)title andSubtitle:(NSString *)subTitle
{
 
    XMGAnnotation *annotation = [[XMGAnnotation alloc] init];
    annotation.coordinate = center;
    
    annotation.title = title;
    annotation.subtitle = subTitle;
    
    [self.mapView addAnnotation:annotation];
    return annotation;
    
}


- (void)addAnnotation
{
    // 添加大头针 == 添加大头针数据模型
    
    // 1. 创建大头针数据模型
    XMGAnnotation *annotation = [[XMGAnnotation alloc] init];
    // 1.1 设置经纬度
    annotation.coordinate = self.mapView.centerCoordinate;
    // 1.2 弹框标题
    annotation.title = @"小码哥";
    // 1.3 弹框子标题
    annotation.subtitle = @"大神三期";
    
    // 添加大头针数据模型
    [self.mapView addAnnotation:annotation];
    
}


/**
 *  系统的大头针视图返回如果为nil , 实现方案
 *
 *  @param mapView    地图
 *  @param annotation 大头针数据模型
 *
 *  @return 大头针视图
 */
-(MKAnnotationView *)xitongmapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    
    // -------模拟当次方返回nil , 系统的实现方案
    
    // 系统默认的大头这视图 对应的类 MKPinAnnotationView
    // 大头针标识
    static NSString *pinID = @"pinID";
    MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
    // 如果从缓存池取出的大头针视图为空, 就创建
    if (pinView == nil) {
        pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
    }
    
    // 重新设置数据模型 (一定要记得!!!), 为了防止循环利用时, 数据混乱
    pinView.annotation = annotation;
    
    // 控制大头针是否弹框
    pinView.canShowCallout = YES;
    
    // 设置大头针颜色
    //    pinView.pinColor = MKPinAnnotationColorGreen;
    pinView.pinTintColor = [UIColor blackColor]; // iOS9.0
    
    // 设置大头针下落动画
    pinView.animatesDrop = YES;
    
    
    // 设置大头针显示图片(如果是系统的大头针视图, 那么就无法进行自定义)
    //    pinView.image = [UIImage imageNamed:@"category_1.png"];
    
    return pinView;
}




#pragma mark -MKMapViewDelegate

/**
 *  地图定位到之后调用
 *
 *  @param mapView      地图
 *  @param userLocation 大头针数据模型
 */
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    
}


/**
 *  当我们添加大头针数据模型时, 就会调用这个方法, 查找对应的大头针视图
 *
 *  @param mapView    地图
 *  @param annotation 大头针数据模型
 *
 *  @return 大头针视图
 *  注意: 如果这个方法, 没有实现, 或者, 这个方法返回nil, 那么系统就会调用系统默认的大头针视图
 */
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    
    // 如果是系统的大头针数据模型, 那么使用系统默认的大头针视图,
    if([annotation isKindOfClass:[MKUserLocation class]])
    {
        return nil;
    }
    
    // 如果想要自定义大头针视图, 必须使用MKAnnotationView 或者 继承 MKAnnotationView 的子类
    
    // 设置循环利用标识
    static NSString *pinID = @"pinID";
    
    // 从缓存池取出大头针数据视图
    MKAnnotationView *customView = [mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
    
    // 如果取出的为nil , 那么就手动创建大头针视图
    if (customView == nil) {
        customView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
    }
    
    // 1. 设置大头针图片
    customView.image = [UIImage imageNamed:@"category_5.png"];

    // 2. 设置弹框
    customView.canShowCallout = YES;
    
    // 2.1 设置大头针偏移量
//    customView.centerOffset = CGPointMake(100, -100);
    // 2.2 设置弹框的偏移量
//    customView.calloutOffset = CGPointMake(100, 100);
    
    
    // 3. 自定义弹框
    // 3.1 设置弹框左侧的视图
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    imageView.image = [UIImage imageNamed:@"htl.jpeg"];
    customView.leftCalloutAccessoryView = imageView;
    
    
    // 3.2 设置弹框右侧视图
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    imageView2.image = [UIImage imageNamed:@"eason.jpg"];
    customView.rightCalloutAccessoryView = imageView2;
    
    // 3.3 设置弹框的详情视图(一定要注意,对应的版本)
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        customView.detailCalloutAccessoryView = [UISwitch new];
    }
    
    // 设置大头针视图可以被拖拽
    customView.draggable = YES;

    
    
    return customView;
    return nil;
}

/**
 *  选中大头针视图时调用这个方法
 *
 *  @param mapView 地图
 *  @param view    大头针视图
 */
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    NSLog(@"选中---%@", view.annotation.title);
}

/**
 *  取消选中某个大头针视图
 *
 *  @param mapView 地图
 *  @param view    大头针视图
 */
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
     NSLog(@"取消选中--%@", view.annotation.title);
}


/**
 *  改变大头针视图拖拽状态时调用
 *
 *  @param mapView  地图
 *  @param view     大头针视图
 *  @param newState 新状态
 *  @param oldState 老状态
 */
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState
{
    NSLog(@"%zd---%zd", oldState, newState);
}

@end


上一篇下一篇

猜你喜欢

热点阅读