当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS开发系列--地图与定位源代码详解

iOS开发系列--地图与定位源代码详解

2019年07月24日  | 移动技术网IT编程  | 我要评论

官晶华照片,pk51私服发布网,十二生肖mp4下载

概览

现在很多社交、电商、团购应用都引入了地图和定位功能,似乎地图功能不再是地图应用和导航应用所特有的。的确,有了地图和定位功能确实让我们的生活更加丰富多彩,极大的改变了我们的生活方式。例如你到了一个陌生的地方想要查找附近的酒店、超市等就可以打开软件搜索周边;类似的,还有很多团购软件可以根据你所在的位置自动为你推荐某些商品。总之,目前地图和定位功能已经大量引入到应用开发中。今天就和大家一起看一下ios如何进行地图和定位开发。

  • 定位
  • 地图

定位

要实现地图、导航功能,往往需要先熟悉定位功能,在ios中通过core location框架进行定位操作。core location自身可以单独使用,和地图开发框架mapkit完全是独立的,但是往往地图开发要配合定位框架使用。在core location中主要包含了定位、地理编码(包括反编码)功能。

定位功能

定位是一个很常用的功能,如一些地图软件打开之后如果用户允许软件定位的话,那么打开软件后就会自动锁定到当前位置,如果用户手机移动那么当前位置也会跟随着变化。要实现这个功能需要使用core loaction中cllocationmanager类,首先看一下这个类的一些主要方法和属性:

类方法 说明
+ (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
走出某个区域之后执行

ios 8 还提供了更加人性化的定位服务选项。app 的定位服务不再仅仅是关闭或打开,现在,定位服务的启用提供了三个选项,「永不」「使用应用程序期间」和「始终」。同时,考虑到能耗问题,如果一款 app 要求始终能在后台开启定位服务,ios 8 不仅会在首次打开 app 时主动向你询问,还会在日常使用中弹窗提醒你该 app 一直在后台使用定位服务,并询问你是否继续允许。在ios7及以前的版本,如果在应用程序中使用定位服务只要在程序中调用startupdatinglocation方法应用就会询问用户是否允许此应用是否允许使用定位服务,同时在提示过程中可以通过在info.plist中配置通过配置privacy - location usage description告诉用户使用的目的,同时这个配置是可选的。

但是在ios8中配置配置项发生了变化,可以通过配置nslocationalwaysusagedescription或者nslocationwheninuseusagedescription来告诉用户使用定位服务的目的,并且注意这个配置是必须的,如果不进行配置则默认情况下应用无法使用定位服务,打开应用不会给出打开定位服务的提示,除非安装后自己设置此应用的定位服务。同时,在应用程序中需要根据配置对requestalwaysauthorization或locationservicesenabled方法进行请求。由于本人机器已经更新到最新的ios8.1下面的内容主要针对ios8,使用ios7的朋友需要稍作调整。

//
// 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

注意:

1.定位频率和定位精度并不应当越精确越好,需要视实际情况而定,因为越精确越耗性能,也就越费电。

2.定位成功后会根据设置情况频繁调用-(void)locationmanager:(cllocationmanager *)manager didupdatelocations:(nsarray *)locations方法,这个方法返回一组地理位置对象数组,每个元素一个cllocation代表地理位置信息(包含经度、纬度、海报、行走速度等信息),之所以返回数组是因为有些时候一个位置点可能包含多个位置。

3.使用完定位服务后如果不需要实时监控应该立即关闭定位服务以节省资源。

4.除了提供定位功能,cllocationmanager还可以调用startmonitoringforregion:方法对指定区域进行监控。

地理编码

除了提供位置跟踪功能之外,在定位服务中还包含clgeocoder类用于处理地理编码和逆地理编码(又叫反地理编码)功能。

地理编码:根据给定的位置(通常是地名)确定地理坐标(经、纬度)。

逆地理编码:可以根据地理坐标(经、纬度)确定位置信息(街道、门牌等)。

clgeocoder最主要的两个方法就是- (void)geocodeaddressstring:(nsstring *)addressstring completionhandler:(clgeocodecompletionhandler)completionhandler;和- (void)reversegeocodelocation:(cllocation *)location completionhandler:(clgeocodecompletionhandler)completionhandler;,分别用于地理编码和逆地理编码。下面简单演示一下:

//
// 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

地图

ios从6.0开始地图数据不再由谷歌驱动,而是改用自家地图,当然在国内它的数据是由高德地图提供的。这样一来,如果在ios6.0之前进行地图开发的话使用方法会有所不同,基于目前的情况其实使用ios6.0之前版本的系统基本已经寥寥无几了,所有在接下来的内容中不会再针对ios5及之前版本的地图开发进行介绍。

在ios中进行地图开发主要有两种方式,一种是直接利用mapkit框架进行地图开发,利用这种方式可以对地图进行精准的控制;另一种方式是直接调用苹果官方自带的地图应用,主要用于一些简单的地图应用(例如:进行导航覆盖物填充等),无法进行精确的控制。当然,本节重点内容还是前者,后面的内容也会稍加提示。

用mapkit之前需要简单了解一下mapkit中地图展示控件mkmapview的的一些常用属性和方法,具体如下表:

属性 说明
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 渲染地图覆盖物时触发

用户位置跟踪

在很多带有地图的应用中默认打开地图都会显示用户当前位置,同时将当前位置标记出来放到屏幕中点方便用户对周围情况进行查看。如果在ios6或者ios7中实现这个功能只需要添加地图控件、设置用户跟踪模式、在-(void)mapview:(mkmapview *)mapview didupdateuserlocation:(mkuserlocation *)userlocation代理方法中设置地图中心区域及显示范围。但是在ios8中用法稍有不同:

1.由于在地图中进行用户位置跟踪需要使用定位功能,而定位功能在ios8中设计发生了变化,因此必须按照前面定位章节中提到的内容进行配置和请求。

2.ios8中不需要进行中心点的指定,默认会将当前位置设置中心点并自动设置显示区域范围。

了解以上两点,要进行用户位置跟踪其实就相当简单了,值得一提的是-(void)mapview:(mkmapview *)mapview didupdateuserlocation:(mkuserlocation *)userlocation这个代理方法。这个方法只有在定位(利用前面章节中的定位内容)到当前位置之后就会调用,以后每当用户位置发生改变就会触发,调用频率相当频繁。

大头针

在ios开发中经常会标记某个位置,需要使用地图标注,也就是大家俗称的“大头针”。只要一个nsobject类实现mkannotation协议就可以作为一个大头针,通常会重写协议中coordinate(标记位置)、title(标题)、subtitle(子标题)三个属性,然后在程序中创建大头针对象并调用addannotation:方法添加大头针即可(之所以ios没有定义一个基类实现这个协议供开发者使用,多数原因应该是mkannotation是一个模型对象,对于多数应用模型会稍有不同,例如后面的内容中会给大头针模型对象添加其他属性)。

kcannotation.h

//
// 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;

@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"

@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

运行效果:

设置大头针视图

在一些应用中系统默认的大头针样式可能无法满足实际的需求,此时就需要修改大头针视图默认样式。根据前面mapkit的代理方法不难发现- (mkannotationview *)mapview:(mkmapview *)mapview viewforannotation:(id <mkannotation>)annotation;方法可以返回一个大头针视图,只要实现这个方法并在这个方法中定义一个大头针视图mkannotationview对象并设置相关属性就可以改变默认大头针的样式。mkannotationview常用属性:

属性 说明
annotation 大头针模型信息,包括标题、子标题、地理位置。
image 大头针图片
canshowcallout 点击大头针是否显示标题、子标题内容等,注意如果在- (mkannotationview *)mapview:(mkmapview *)mapview viewforannotation:(id <mkannotation>)annotation;方法中重新定义大头针默认情况是无法交互的需要设置为true。
calloutoffset 点击大头针时弹出详情信息视图的偏移量
selected 是否被选中状态
leftcalloutaccessoryview 弹出详情左侧视图
rightcalloutaccessoryview 弹出详情右侧视图

需要注意:

a.这个代理方法的调用时机:每当有大头针显示到系统可视界面中时就会调用此方法返回一个大头针视图放到界面中,同时当前系统位置标注(也就是地图中蓝色的位置点)也是一个大头针,也会调用此方法,因此处理大头针视图时需要区别对待。

b.类似于uitableview的代理方法,此方法调用频繁,开发过程中需要重复利用mapkit的缓存池将大头针视图缓存起来重复利用。

c.自定义大头针默认情况下不允许交互,如果交互需要设置canshowcallout=true

d.如果代理方法返回nil则会使用默认大头针视图,需要根据情况设置。

下面以一个示例进行大头针视图设置,这里设置了大头针的图片、弹出视图、偏移量等信息。

kcannotation.h

//
// 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;

@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"

@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

运行效果:

注意:

在mapkit框架中除了mkannotationview之外还有一个mkpinannotationview,它是mkannotationview的子类,相比mkannotationview多了两个属性pincolor和animationdrop,分别用于设置大头针视图颜色和添加大头针动画。

扩展--自定义大头针弹详情视图

通过上面的示例不难看出mkannotationview足够强大(何况还有mkpinannotationview),很多信息都可以进行设置,但是唯独不能修改大头针描述详情视图(仅仅支持详情中左右视图内容)。要实现这个需求目前开发中普遍采用的思路就是:

a.点击一个大头针a时重新在a的坐标处添加另一个大头针b(注意此时将a对应的大头针视图canshowcallout设置为false)作为大头针详情模型,然后在- (mkannotationview *)mapview:(mkmapview *)mapview viewforannotation:(id <mkannotation>)annotation;代理方法中判断大头针类型,如果是b则重写mkannotationview(可以自定义一个类c继承于mkannotationview),返回自定义大头针视图c。

b.定义大头针视图c继承于mkannotationview(或者mkpinannotationview),在自定义大头针视图中添加自己的控件,完成自定义布局。

在使用百度地图客户端时当点击一个搜索位置时可以看到此位置的评价等信息,视图效果大概如下:

下面不妨试着实现一下这个效果:

大头针模型:kcannotation.h

//
// 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;

@end
kccalloutannotationview.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 

在这个过程中需要注意几点:

1.大头针a作为一个普通大头针,其中最好保存自定义大头针视图c所需要的模型以便根据不同的模型初始化视图。

2.自定义大头针视图c的大头针模型b中不需要title、subtitle属性,最好设置为只读;模型中最后保存自定义大头针视图c所需要的布局模型数据。

3.只有点击非b类大头针时才新增自定义大头针,并且增加时要首先移除其他b类大头针避免重叠(一般建议放到取消大头针选择的代理方法中)。

4.通常在自定义大头针视图c设置大头针模型时布局界面,此时需要注意新增大头针的位置,通常需要偏移一定的距离才能达到理想的效果。

运行效果:

使用自带的地图应用

除了可以使用mapkit框架进行地图开发,对地图有精确的控制和自定义之外,如果对于应用没有特殊要求的话选用苹果自带的地图应用也是一个不错的选择。使用苹果自带的应用时需要用到mapkit中的mkmapitem类,这个类有一个openinmapswithlaunchoptions:动态方法和一个openmapswithitems: launchoptions:静态方法用于打开苹果地图应用。第一个方法用于在地图上标注一个位置,第二个方法除了可以标注多个位置外还可以进行多个位置之间的驾驶导航,使用起来也是相当方便。在熟悉这两个方法使用之前有必要对两个方法中的options参数做一下简单说明:

键(常量) 说明
mklaunchoptionsdirectionsmodekey 路线模式,常量 mklaunchoptionsdirectionsmodedriving  驾车模式
mklaunchoptionsdirectionsmodewalking 步行模式
mklaunchoptionsmaptypekey 地图类型,枚举 mkmaptypestandard :标准模式
mkmaptypesatellite :卫星模式
mkmaptypehybrid  :混合模式
mklaunchoptionsmapcenterkey 中心点坐标,cllocationcoordinate2d类型  
mklaunchoptionsmapspankey 地图显示跨度,mkcoordinatespan 类型  
mklaunchoptionsshowstraffickey 是否 显示交通状况,布尔型  
mklaunchoptionscamerakey 3d地图效果,mkmapcamera类型
注意:此属性从ios7及以后可用,前面的属性从ios6开始可用
 

单个位置的标注

下面的代码演示了如何在苹果自带地图应用上标记一个位置,首先根据反地理编码获得一个clplacemark位置对象,然后将其转换为mkplacemark对象用于mkmapitem初始化,最后调用其openinmapswithlaunchoptions:打开地图应用并标记:

//
// 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

运行效果:

标记多个位置

如果要标记多个位置需要调用mkmapitem的静态方法,下面的代码演示中需要注意,使用clgeocoder进行定位时一次只能定位到一个位置,所以第二个位置定位放到了第一个位置获取成功之后。

//
// 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

运行效果:

注意:其实如果不用苹果自带的地图应用也可以实现地图导航,mapkit中提供了mkdirectionrequest对象用于计算路线,提供了mkdirections用于计算方向,这样一来只需要调用mkmapview的addoverlay等方法添加覆盖物即可实现类似的效果,有兴趣的朋友可以试一下。

由于定位和地图框架中用到了诸多类,有些初学者容易混淆,下面简单对比一下。

cllocation:用于表示位置信息,包含地理坐标、海拔等信息,包含在coreloaction框架中。

mkuserlocation:一个特殊的大头针,表示用户当前位置。

clplacemark:定位框架中地标类,封装了详细的地理信息。

mkplacemark:类似于clplacemark,只是它在mapkit框架中,可以根据clplacemark创建mkplacemark。

原文链接:http://www.cnblogs.com/kenshincui/p/4125570.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网