MKMapView与大头针
相关的注意点在前面两篇博客中已经强调,这里就不做过多的陈述了
如果在地图大头针的时候 没有定位到当前的位置,很有可能是没有在plist 文件里面去设置
NSLocationAlwaysUsageDescription 、NSLocationWhenInUseUsageDescription 属性
导入头文件
#import <MapKit/MapKit.h> //地图
#import "KCAnnotation.h"
设置协议
MKMapViewDelegate
设置属性
CLLocationManager *_locationManager;//定位管理器
MKMapView *_mapView;//地图
#pragma mark 添加地图控件
-(void)initGUI{
CGRect rect=[UIScreen mainScreen].bounds;
_mapView=[[MKMapView alloc]initWithFrame:rect];
[self.view addSubview:_mapView];
//设置代理
_mapView.delegate=self;
//请求定位服务
_locationManager=[[CLLocationManager alloc]init];
if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
[_locationManager requestWhenInUseAuthorization];
}
//用户位置追踪(用户位置追踪用于标记用户当前位置,此时会调用定位服务)
_mapView.userTrackingMode=MKUserTrackingModeFollow;
//设置地图类型
_mapView.mapType=MKMapTypeStandard;
//添加大头针
[self addAnnotation];
}
#pragma mark 添加大头针
-(void)addAnnotation{
CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(23.13, 113.27);
KCAnnotation *annotation1=[[KCAnnotation alloc]init];
annotation1.title=@"CMJ Studio";
annotation1.subtitle=@"Kenshin Cui's Studios";
annotation1.coordinate=location1;
[_mapView addAnnotation:annotation1];
CLLocationCoordinate2D location2=CLLocationCoordinate2DMake(39.87, 116.35);
KCAnnotation *annotation2=[[KCAnnotation alloc]init];
annotation2.title=@"Kenshin&Kaoru";
annotation2.subtitle=@"Kenshin Cui's Home";
annotation2.coordinate=location2;
[_mapView addAnnotation:annotation2];
/*
*注意: 如果在plist 文件里面 没有设置requestAlwaysAuthorization或locationServicesEnabled 那么就不会显示当前的位置
*/
}
#pragma mark - 地图控件代理方法
#pragma mark 更新用户位置,只要用户改变则调用此方法(包括第一次定位到用户位置)
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
NSLog(@"%@",userLocation.title);
//设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)
// MKCoordinateSpan span=MKCoordinateSpanMake(0.01, 0.01);
// MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
// [_mapView setRegion:region animated:true];
}
/*
新建一个类:KCAnnotation,只需要在.h 做如下操作即可
大头针模型:KCAnnotation.h
*/
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h> //地图
/**
*大头针
在iOS开发中经常会标记某个位置,需要使用地图标注,也就是大家俗称的“大头针”。只要一个NSObject类实现
MKAnnotation协议就可以作为一个大头针,通常会重写协议中coordinate(标记位置)、title(标题)、subtitle(子标题)三个属性,然后在程序中创建大头针对象并调用addAnnotation:方法添加大头针即可(之所以iOS没有定义一个基类实现这个协议供开发者使用,多数原因应该是MKAnnotation是一个模型对象,对于多数应用模型会稍有不同,例如后面的内容中会给大头针模型对象添加其他属性)
*/
@interface KCAnnotation : NSObject<MKAnnotation>
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end