类方法 | 说明 |
+ (BOOL)locationServicesEnabled; | 是否启用定位服务,通常如果用户没有启用定位服务可以提示用户打开定位服务 |
+ (CLAuthorizationStatus)authorizationStatus; | 定位服务授权状态,返回枚举类型: kCLAuthorizationStatusNotDetermined: 用户尚未做出决定是否启用定位服务 kCLAuthorizationStatusRestricted: 没有获得用户授权使用定位服务,可能用户没有自己禁止访问授权 kCLAuthorizationStatusDenied :用户已经明确禁止应用使用定位服务或者当前系统定位服务处于关闭状态 kCLAuthorizationStatusAuthorizedAlways: 应用获得授权可以一直使用定位服务,即使应用不在使用状态 kCLAuthorizationStatusAuthorizedWhenInUse: 使用此应用过程中允许访问定位服务 |
属性 | 说明 |
desiredAccuracy | 定位精度,枚举类型: kCLLocationAccuracyBest:最精确定位 CLLocationAccuracy kCLLocationAccuracyNearestTenMeters:十米误差范围 kCLLocationAccuracyHundredMeters:百米误差范围 kCLLocationAccuracyKilometer:千米误差范围 kCLLocationAccuracyThreeKilometers:三千米误差范围 |
distanceFilter | 位置信息更新最小距离,只有移动大于这个距离才更新位置信息,默认为kCLDistanceFilterNone:不进行距离限制 |
对象方法 | 说明 |
startUpdatingLocation | 开始定位追踪,开始定位后将按照用户设置的更新频率执行-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;方法反馈定位信息 |
stopUpdatingLocation | 停止定位追踪 |
startUpdatingHeading | 开始导航方向追踪 |
stopUpdatingHeading | 停止导航方向追踪 |
startMonitoringForRegion: | 开始对某个区域进行定位追踪,开始对某个区域进行定位后。如果用户进入或者走出某个区域会调用- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region和- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region代理方法反馈相关信息 |
stopMonitoringForRegion: | 停止对某个区域进行定位追踪 |
requestWhenInUseAuthorization | 请求获得应用使用时的定位服务授权,注意使用此方法前在要在info.plist中配置NSLocationWhenInUseUsageDescription |
requestAlwaysAuthorization | 请求获得应用一直使用定位服务授权,注意使用此方法前要在info.plist中配置NSLocationAlwaysUsageDescription |
代理方法 | 说明 |
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations; | 位置发生改变后执行(第一次定位到某个位置之后也会执行) |
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading; | 导航方向发生变化后执行 |
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region | 进入某个区域之后执行 |
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region | 走出某个区域之后执行 |
//// KCMainViewController.m// CoreLocation//// Created by Kenshin Cui on 14-03-27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>@interface KCMainViewController ()<CLLocationManagerDelegate>{CLLocationManager *_locationManager;}@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];//定位管理器_locationManager=[[CLLocationManager alloc]init];if (![CLLocationManager locationServicesEnabled]) {NSLog(@"定位服务当前可能尚未打开,请设置打开!");return;}//如果没有授权则请求用户授权if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){[_locationManager requestWhenInUseAuthorization];}else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){//设置代理_locationManager.delegate=self;//设置定位精度_locationManager.desiredAccuracy=kCLLocationAccuracyBest;//定位频率,每隔多少米定位一次CLLocationDistance distance=10.0;//十米定位一次_locationManager.distanceFilter=distance;//启动跟踪定位[_locationManager startUpdatingLocation];}}#pragma mark - CoreLocation 代理#pragma mark 跟踪定位代理方法,每次位置发生变化即会执行(只要定位到相应位置)//可以通过模拟器设置一个虚拟位置,否则在模拟器中无法调用此方法-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{CLLocation *location=[locations firstObject];//取出第一个位置CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);//如果不需要实时定位,使用完即使关闭定位服务[_locationManager stopUpdatingLocation];}@end注意:
//// KCMainViewController.m// CoreLocation//// Created by Kenshin Cui on 14-03-27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>@interface KCMainViewController ()<CLLocationManagerDelegate>{CLGeocoder *_geocoder;}@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];_geocoder=[[CLGeocoder alloc]init];[self getCoordinateByAddress:@"北京"];[self getAddressByLatitude:39.54 longitude:116.28];}#pragma mark 根据地名确定地理坐标-(void)getCoordinateByAddress:(NSString *)address{//地理编码[_geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {//取得第一个地标,地标中存储了详细的地址信息,注意:一个地名可能搜索出多个地址CLPlacemark *placemark=[placemarks firstObject];CLLocation *location=placemark.location;//位置CLRegion *region=placemark.region;//区域NSDictionary *addressDic= placemark.addressDictionary;//详细地址信息字典,包含以下部分信息//NSString *name=placemark.name;//地名//NSString *thoroughfare=placemark.thoroughfare;//街道//NSString *subThoroughfare=placemark.subThoroughfare; //街道相关信息,例如门牌等//NSString *locality=placemark.locality; // 城市//NSString *subLocality=placemark.subLocality; // 城市相关信息,例如标志性建筑//NSString *administrativeArea=placemark.administrativeArea; // 州//NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息//NSString *postalCode=placemark.postalCode; //邮编//NSString *ISOcountryCode=placemark.ISOcountryCode; //国家编码//NSString *country=placemark.country; //国家//NSString *inlandWater=placemark.inlandWater; //水源、湖泊//NSString *ocean=placemark.ocean; // 海洋//NSArray *areasOfInterest=placemark.areasOfInterest; //关联的或利益相关的地标NSLog(@"位置:%@,区域:%@,详细信息:%@",location,region,addressDic);}];}#pragma mark 根据坐标取得地名-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{//反地理编码CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];[_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {CLPlacemark *placemark=[placemarks firstObject];NSLog(@"详细信息:%@",placemark.addressDictionary);}];}@end地图
属性 | 说明 |
userTrackingMode | 跟踪类型,是一个枚举: MKUserTrackingModeNone :不进行用户位置跟踪; MKUserTrackingModeFollow :跟踪用户位置; MKUserTrackingModeFollowWithHeading :跟踪用户位置并且跟踪用户前进方向; |
mapType | 地图类型,是一个枚举: MKMapTypeStandard :标准地图,一般情况下使用此地图即可满足; MKMapTypeSatellite :卫星地图; MKMapTypeHybrid :混合地图,加载最慢比较消耗资源; |
userLocation | 用户位置,只读属性 |
annotations | 当前地图中的所有大头针,只读属性 |
对象方法 | 说明 |
- (void)addAnnotation:(id <MKAnnotation>)annotation; | 添加大头针,对应的有添加大头针数组 |
- (void)removeAnnotation:(id <MKAnnotation>)annotation; | 删除大头针,对应的有删除大头针数组 |
- (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated; | 设置地图显示区域,用于控制当前屏幕显示地图范围 |
- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated; | 设置地图中心点位置 |
- (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view; | 将地理坐标(经纬度)转化为数学坐标(UIKit坐标) |
- (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view; | 将数学坐标转换为地理坐标 |
- (MKAnnotationView *)dequeueReusableAnnotationViewWithIdentifier:(NSString *)identifier; | 从缓存池中取出大头针,类似于UITableView中取出UITableViewCell,为了进行性能优化而设计 |
- (void)selectAnnotation:(id <MKAnnotation>)annotation animated:(BOOL)animated; | 选中指定的大头针 |
- (void)deselectAnnotation:(id <MKAnnotation>)annotation animated:(BOOL)animated; | 取消选中指定的大头针 |
代理方法 | 说明 |
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation ; | 用户位置发生改变时触发(第一次定位到用户位置也会触发该方法) |
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation ; | 显示区域发生改变后触发 |
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView; | 地图加载完成后触发 |
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation; | 显示大头针时触发,返回大头针视图,通常自定义大头针可以通过此方法进行 |
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view | 点击选中某个大头针时触发 |
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view | 取消选中大头针时触发 |
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay | 渲染地图覆盖物时触发 |
//// KCAnnotation.h// MapKit//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>#import <MapKit/MapKit.h>@interface KCAnnotation : NSObject<MKAnnotation>@property (nonatomic) CLLocationCoordinate2D coordinate;@property (nonatomic, copy) NSString *title;@property (nonatomic, copy) NSString *subtitle;@endKCMainViewController.m
//// KCMainViewController.m// MapKit Annotation//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.// 37.785834-122.406417// 39.92 116.39#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>#import "KCAnnotation.h"@interface KCMainViewController ()<MKMapViewDelegate>{CLLocationManager *_locationManager;MKMapView *_mapView;}@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];[self initGUI];}#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(39.95, 116.35);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];}#pragma mark - 地图控件代理方法#pragma mark 更新用户位置,只要用户改变则调用此方法(包括第一次定位到用户位置)-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{NSLog(@"%@",userLocation);//设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)//MKCoordinateSpan span=MKCoordinateSpanMake(0.01, 0.01);//MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);//[_mapView setRegion:region animated:true];}@end运行效果:
属性 | 说明 |
annotation | 大头针模型信息,包括标题、子标题、地理位置。 |
image | 大头针图片 |
canShowCallout | 点击大头针是否显示标题、子标题内容等,注意如果在- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;方法中重新定义大头针默认情况是无法交互的需要设置为true。 |
calloutOffset | 点击大头针时弹出详情信息视图的偏移量 |
selected | 是否被选中状态 |
leftCalloutAccessoryView | 弹出详情左侧视图 |
rightCalloutAccessoryView | 弹出详情右侧视图 |
//// KCAnnotation.h// MapKit//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>#import <MapKit/MapKit.h>@interface KCAnnotation : NSObject<MKAnnotation>@property (nonatomic) CLLocationCoordinate2D coordinate;@property (nonatomic, copy) NSString *title;@property (nonatomic, copy) NSString *subtitle;#pragma mark 自定义一个图片属性在创建大头针视图时使用@property (nonatomic,strong) UIImage *image;@endKCMainViewController.m
//// KCMainViewController.m// MapKit Annotation//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.// 37.785834-122.406417// 39.92 116.39#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>#import "KCAnnotation.h"@interface KCMainViewController ()<MKMapViewDelegate>{CLLocationManager *_locationManager;MKMapView *_mapView;}@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];[self initGUI];}#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(39.95, 116.35);KCAnnotation *annotation1=[[KCAnnotation alloc]init];annotation1.title=@"CMJ Studio";annotation1.subtitle=@"Kenshin Cui"s Studios";annotation1.coordinate=location1;annotation1.image=[UIImage imageNamed:@"icon_pin_floating.png"];[_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;annotation2.image=[UIImage imageNamed:@"icon_paopao_waterdrop_streetscape.png"];[_mapView addAnnotation:annotation2];}#pragma mark - 地图控件代理方法#pragma mark 显示大头针时调用,注意方法中的annotation参数是即将显示的大头针对象-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{//由于当前位置的标注也是一个大头针,所以此时需要判断,此代理方法返回nil使用默认大头针视图if ([annotation isKindOfClass:[KCAnnotation class]]) {static NSString *key1=@"AnnotationKey1";MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];//如果缓存池中不存在则新建if (!annotationView) {annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];annotationView.canShowCallout=true;//允许交互点击annotationView.calloutOffset=CGPointMake(0, 1);//定义详情视图偏移量annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定义详情左侧视图}//修改大头针视图//重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的,位置是放到缓存池时的位置)annotationView.annotation=annotation;annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片return annotationView;}else {return nil;}}@end运行效果:
//// KCAnnotation.h// MapKit//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>#import <MapKit/MapKit.h>@interface KCAnnotation : NSObject<MKAnnotation>@property (nonatomic) CLLocationCoordinate2D coordinate;@property (nonatomic, copy) NSString *title;@property (nonatomic, copy) NSString *subtitle;#pragma mark 自定义一个图片属性在创建大头针视图时使用@property (nonatomic,strong) UIImage *image;#pragma mark 大头针详情左侧图标@property (nonatomic,strong) UIImage *icon;#pragma mark 大头针详情描述 @property (nonatomic,copy) NSString *detail;#pragma mark 大头针右下方星级评价@property (nonatomic,strong) UIImage *rate;@end弹出详情大头针模型:KCCalloutAnnotation.h
//// KCCalloutAnnotation.h// MapKit//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <UIKit/UIKit.h>#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>@interface KCCalloutAnnotation : NSObject<MKAnnotation>@property (nonatomic) CLLocationCoordinate2D coordinate;@property (nonatomic, copy,readonly) NSString *title;@property (nonatomic, copy,readonly) NSString *subtitle;#pragma mark 左侧图标@property (nonatomic,strong) UIImage *icon;#pragma mark 详情描述@property (nonatomic,copy) NSString *detail;#pragma mark 星级评价@property (nonatomic,strong) UIImage *rate;@end弹出详情大头针视图:KCCalloutAnnotatonView.h//// KCCalloutView.h// MapKit//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.// 自定义弹出标注视图#import <UIKit/UIKit.h>#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>#import "KCCalloutAnnotation.h"@interface KCCalloutAnnotationView : MKAnnotationView@property (nonatomic ,strong) KCCalloutAnnotation *annotation;#pragma mark 从缓存取出标注视图+(instancetype)calloutViewWithMapView:(MKMapView *)mapView;@endKCCalloutAnnotationView.m//// KCCalloutView.m// MapKit//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "KCCalloutAnnotationView.h"#define kSpacing 5#define kDetailFontSize 12#define kViewOffset 80@interface KCCalloutAnnotationView(){UIView *_backgroundView;UIImageView *_iconView;UILabel *_detailLabel;UIImageView *_rateView;}@end@implementation KCCalloutAnnotationView-(instancetype)init{if(self=[super init]){[self layoutUI];}return self;}-(instancetype)initWithFrame:(CGRect)frame{if (self=[super initWithFrame:frame]) {[self layoutUI];}return self;}-(void)layoutUI{//背景_backgroundView=[[UIView alloc]init];_backgroundView.backgroundColor=[UIColor whiteColor];//左侧添加图标_iconView=[[UIImageView alloc]init];//上方详情_detailLabel=[[UILabel alloc]init];_detailLabel.lineBreakMode=NSLineBreakByWordWrapping;//[_text sizeToFit];_detailLabel.font=[UIFont systemFontOfSize:kDetailFontSize];//下方星级_rateView=[[UIImageView alloc]init];[self addSubview:_backgroundView];[self addSubview:_iconView];[self addSubview:_detailLabel];[self addSubview:_rateView];}+(instancetype)calloutViewWithMapView:(MKMapView *)mapView{static NSString *calloutKey=@"calloutKey1";KCCalloutAnnotationView *calloutView=(KCCalloutAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:calloutKey];if (!calloutView) {calloutView=[[KCCalloutAnnotationView alloc]init];}return calloutView;}#pragma mark 当给大头针视图设置大头针模型时可以在此处根据模型设置视图内容-(void)setAnnotation:(KCCalloutAnnotation *)annotation{[super setAnnotation:annotation];//根据模型调整布局_iconView.image=annotation.icon;_iconView.frame=CGRectMake(kSpacing, kSpacing, annotation.icon.size.width, annotation.icon.size.height);_detailLabel.text=annotation.detail;float detailWidth=150.0;CGSize detailSize= [annotation.detail boundingRectWithSize:CGSizeMake(detailWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kDetailFontSize]} context:nil].size;float detailX=CGRectGetMaxX(_iconView.frame)+kSpacing;_detailLabel.frame=CGRectMake(detailX, kSpacing, detailSize.width, detailSize.height);_rateView.image=annotation.rate;_rateView.frame=CGRectMake(detailX, CGRectGetMaxY(_detailLabel.frame)+kSpacing, annotation.rate.size.width, annotation.rate.size.height);float backgroundWidth=CGRectGetMaxX(_detailLabel.frame)+kSpacing;float backgroundHeight=_iconView.frame.size.height+2*kSpacing;_backgroundView.frame=CGRectMake(0, 0, backgroundWidth, backgroundHeight);self.bounds=CGRectMake(0, 0, backgroundWidth, backgroundHeight+kViewOffset);}@end主视图控制器:KCMainViewController.m
//// KCMainViewController.m// MapKit Annotation//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.// 37.785834-122.406417// 39.92 116.39#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>#import "KCAnnotation.h"#import "KCCalloutAnnotationView.h"#import "KCCalloutAnnotationView.h"@interface KCMainViewController ()<MKMapViewDelegate>{CLLocationManager *_locationManager;MKMapView *_mapView;}@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];[self initGUI];}#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(39.95, 116.35);KCAnnotation *annotation1=[[KCAnnotation alloc]init];annotation1.title=@"CMJ Studio";annotation1.subtitle=@"Kenshin Cui"s Studios";annotation1.coordinate=location1;annotation1.image=[UIImage imageNamed:@"icon_pin_floating.png"];annotation1.icon=[UIImage imageNamed:@"icon_mark1.png"];annotation1.detail=@"CMJ Studio...";annotation1.rate=[UIImage imageNamed:@"icon_Movie_Star_rating.png"];[_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;annotation2.image=[UIImage imageNamed:@"icon_paopao_waterdrop_streetscape.png"];annotation2.icon=[UIImage imageNamed:@"icon_mark2.png"];annotation2.detail=@"Kenshin Cui...";annotation2.rate=[UIImage imageNamed:@"icon_Movie_Star_rating.png"];[_mapView addAnnotation:annotation2];}#pragma mark - 地图控件代理方法#pragma mark 显示大头针时调用,注意方法中的annotation参数是即将显示的大头针对象-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{//由于当前位置的标注也是一个大头针,所以此时需要判断,此代理方法返回nil使用默认大头针视图if ([annotation isKindOfClass:[KCAnnotation class]]) {static NSString *key1=@"AnnotationKey1";MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];//如果缓存池中不存在则新建if (!annotationView) {annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];//annotationView.canShowCallout=true;//允许交互点击annotationView.calloutOffset=CGPointMake(0, 1);//定义详情视图偏移量annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定义详情左侧视图}//修改大头针视图//重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的,位置是放到缓存池时的位置)annotationView.annotation=annotation;annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片return annotationView;}else if([annotation isKindOfClass:[KCCalloutAnnotation class]]){//对于作为弹出详情视图的自定义大头针视图无弹出交互功能(canShowCallout=false,这是默认值),在其中可以自由添加其他视图(因为它本身继承于UIView)KCCalloutAnnotationView *calloutView=[KCCalloutAnnotationView calloutViewWithMapView:mapView];calloutView.annotation=annotation;return calloutView;} else {return nil;}}#pragma mark 选中大头针时触发//点击一般的大头针KCAnnotation时添加一个大头针作为所点大头针的弹出详情视图-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{KCAnnotation *annotation=view.annotation;if ([view.annotation isKindOfClass:[KCAnnotation class]]) {//点击一个大头针时移除其他弹出详情视图//[self removeCustomAnnotation];//添加详情大头针,渲染此大头针视图时将此模型对象赋值给自定义大头针视图完成自动布局KCCalloutAnnotation *annotation1=[[KCCalloutAnnotation alloc]init];annotation1.icon=annotation.icon;annotation1.detail=annotation.detail;annotation1.rate=annotation.rate;annotation1.coordinate=view.annotation.coordinate;[mapView addAnnotation:annotation1];}}#pragma mark 取消选中时触发-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view{[self removeCustomAnnotation];}#pragma mark 移除所用自定义大头针-(void)removeCustomAnnotation{[_mapView.annotations enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {if ([obj isKindOfClass:[KCCalloutAnnotation class]]) {[_mapView removeAnnotation:obj];}}];}@end在这个过程中需要注意几点:
键(常量) | 说明 | 值 |
MKLaunchOptionsDirectionsModeKey | 路线模式,常量 | MKLaunchOptionsDirectionsModeDriving 驾车模式 MKLaunchOptionsDirectionsModeWalking 步行模式 |
MKLaunchOptionsMapTypeKey | 地图类型,枚举 | MKMapTypeStandard :标准模式 MKMapTypeSatellite :卫星模式 MKMapTypeHybrid :混合模式 |
MKLaunchOptionsMapCenterKey | 中心点坐标,CLLocationCoordinate2D类型 | |
MKLaunchOptionsMapSpanKey | 地图显示跨度,MKCoordinateSpan 类型 | |
MKLaunchOptionsShowsTrafficKey | 是否 显示交通状况,布尔型 | |
MKLaunchOptionsCameraKey | 3D地图效果,MKMapCamera类型 注意:此属性从iOS7及以后可用,前面的属性从iOS6开始可用 |
//// KCMainViewController.m// AppleMap//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>@interface KCMainViewController ()@property (nonatomic,strong) CLGeocoder *geocoder;@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];_geocoder=[[CLGeocoder alloc]init];[self location];}#pragma mark 在地图上定位-(void)location{//根据“北京市”进行地理编码[_geocoder geocodeAddressString:@"北京市" completionHandler:^(NSArray *placemarks, NSError *error) {CLPlacemark *clPlacemark=[placemarks firstObject];//获取第一个地标MKPlacemark *mkplacemark=[[MKPlacemark alloc]initWithPlacemark:clPlacemark];//定位地标转化为地图的地标NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard)};MKMapItem *mapItem=[[MKMapItem alloc]initWithPlacemark:mkplacemark];[mapItem openInMapsWithLaunchOptions:options];}];}@end运行效果:
//// KCMainViewController.m// AppleMap//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>@interface KCMainViewController ()@property (nonatomic,strong) CLGeocoder *geocoder;@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];_geocoder=[[CLGeocoder alloc]init];[self listPlacemark];}-(void)listPlacemark{//根据“北京市”进行地理编码[_geocoder geocodeAddressString:@"北京市" completionHandler:^(NSArray *placemarks, NSError *error) {CLPlacemark *clPlacemark1=[placemarks firstObject];//获取第一个地标MKPlacemark *mkPlacemark1=[[MKPlacemark alloc]initWithPlacemark:clPlacemark1];//注意地理编码一次只能定位到一个位置,不能同时定位,所在放到第一个位置定位完成回调函数中再次定位[_geocoder geocodeAddressString:@"郑州市" completionHandler:^(NSArray *placemarks, NSError *error) {CLPlacemark *clPlacemark2=[placemarks firstObject];//获取第一个地标MKPlacemark *mkPlacemark2=[[MKPlacemark alloc]initWithPlacemark:clPlacemark2];NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard)};//MKMapItem *mapItem1=[MKMapItem mapItemForCurrentLocation];//当前位置MKMapItem *mapItem1=[[MKMapItem alloc]initWithPlacemark:mkPlacemark1];MKMapItem *mapItem2=[[MKMapItem alloc]initWithPlacemark:mkPlacemark2];[MKMapItem openMapsWithItems:@[mapItem1,mapItem2] launchOptions:options];}];}];}@end运行效果:
//// KCMainViewController.m// AppleMap//// Created by Kenshin Cui on 14/3/27.// Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "KCMainViewController.h"#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>@interface KCMainViewController ()@property (nonatomic,strong) CLGeocoder *geocoder;@end@implementation KCMainViewController- (void)viewDidLoad {[super viewDidLoad];_geocoder=[[CLGeocoder alloc]init];[self turnByTurn];}-(void)turnByTurn{//根据“北京市”地理编码[_geocoder geocodeAddressString:@"北京市" completionHandler:^(NSArray *placemarks, NSError *error) {CLPlacemark *clPlacemark1=[placemarks firstObject];//获取第一个地标MKPlacemark *mkPlacemark1=[[MKPlacemark alloc]initWithPlacemark:clPlacemark1];//注意地理编码一次只能定位到一个位置,不能同时定位,所在放到第一个位置定位完成回调函数中再次定位[_geocoder geocodeAddressString:@"郑州市" completionHandler:^(NSArray *placemarks, NSError *error) {CLPlacemark *clPlacemark2=[placemarks firstObject];//获取第一个地标MKPlacemark *mkPlacemark2=[[MKPlacemark alloc]initWithPlacemark:clPlacemark2];NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard),MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving};//MKMapItem *mapItem1=[MKMapItem mapItemForCurrentLocation];//当前位置MKMapItem *mapItem1=[[MKMapItem alloc]initWithPlacemark:mkPlacemark1];MKMapItem *mapItem2=[[MKMapItem alloc]initWithPlacemark:mkPlacemark2];[MKMapItem openMapsWithItems:@[mapItem1,mapItem2] launchOptions:options];}];}];}@end运行效果: