iOS开发中最基本的位置功能实现示例

2025-05-29 0 62

定位获取位置位置编码-反编码
我们的应用程序,可以通过添加core location框架所包含的类,获取设备的地图位置
添加corelocation.framework框架,导入#import<corelocation/corelocation.h>。
使用地图服务时,会消耗更多地设备电量.因此,在获取到设备的位置后,应该停止定位来节省电量。
我们通过一个demo来展示内容与效果

复制代码 代码如下:


//
// hmtrootviewcontroller.h
// my-gps-map
//
// created by hmt on 14-4-12.
// copyright (c) 2014年 胡明涛. all rights reserved.
//

#import <uikit/uikit.h>

@interface hmtrootviewcontroller : uiviewcontroller <cllocationmanagerdelegate>

@end

//
// hmtrootviewcontroller.m
// my-gps-map
//
// created by hmt on 14-4-12.
// copyright (c) 2014年 胡明涛. all rights reserved.
//

#import "hmtrootviewcontroller.h"
#import <addressbook/addressbook.h>

@interface hmtrootviewcontroller (){

cllocationmanager * _locationmanage;
}

@property (nonatomic,retain) cllocationmanager * locationmanage;

@end

@implementation hmtrootviewcontroller

– (void)dealloc{

release_safely(_locationmanage);
[super dealloc];

}

– (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil
{
self = [super initwithnibname:nibnameornil bundle:nibbundleornil];
if (self) {
// custom initialization
}
return self;
}

– (void)viewdidload
{
[super viewdidload];
// do any additional setup after loading the view.

[self creategpsmap];
self.view.backgroundcolor = [uicolor redcolor];

}

– (void)creategpsmap{

// 初始化位置服务
self.locationmanage = [[cllocationmanager alloc]init];

// 要求cllocationmanager对象返回全部信息
_locationmanage.distancefilter = kcldistancefilternone;

// 设置定位精度
_locationmanage.desiredaccuracy = kcllocationaccuracybest;

// 设置代理
_locationmanage.delegate = self;

// 开始定位
[_locationmanage startupdatinglocation];

[_locationmanage release];

}

– (void)locationmanager:(cllocationmanager *)manager didupdatelocations:(nsarray *)locations{

cllocation * newlocation = [locations lastobject];
// 停止实时定位
[_locationmanage stopupdatinglocation];

// 取得经纬度
cllocationcoordinate2d coord2d = newlocation.coordinate;
double latitude = coord2d.latitude;
double longitude = coord2d.longitude;
nslog(@"纬度 = %f 经度 = %f",latitude,longitude);

// 取得精度
cllocationaccuracy horizontal = newlocation.horizontalaccuracy;
cllocationaccuracy vertical = newlocation.verticalaccuracy;
nslog(@"水平方 = %f 垂直方 = %f",horizontal,vertical);

// 取得高度
cllocationdistance altitude = newlocation.altitude;
nslog(@"%f",altitude);

// 取得此时时刻
nsdate *timestamp = [newlocation timestamp];
// 实例化一个nsdateformatter对象
nsdateformatter* dateformat = [[nsdateformatter alloc] init];
// 设定时间格式
[dateformat setdateformat:@"yyyy-mm-dd hh:mm:ss a"];
[dateformat setamsymbol:@"am"]; // 显示中文, 改成"上午"
[dateformat setpmsymbol:@"pm"];
// 求出当天的时间字符串,当更改时间格式时,时间字符串也能随之改变
nsstring *datestring = [dateformat stringfromdate:timestamp];
nslog(@"此时此刻时间 = %@",datestring);

// —————————————–位置反编码——————————————–
clgeocoder * geocoder = [[clgeocoder alloc]init];
[geocoder reversegeocodelocation:newlocation completionhandler:^(nsarray *placemarks, nserror *error) {

for (clplacemark * place in placemarks) {

nslog(@"name = %@",place.name); // 位置
nslog(@"thoroughfare = %@",place.thoroughfare); // 街道
nslog(@"subadministrativearea = %@",place.subadministrativearea); // 子街道
nslog(@"locality = %@",place.locality); // 市
nslog(@"sublocality = %@",place.sublocality); // 区
nslog(@"country = %@",place.country); // 国家

nsarray *allkeys = place.addressdictionary.allkeys;
for (nsstring *key in allkeys)
{
nslog(@"key = %@, value = %@",key, place.addressdictionary[key]);
}
#pragma mark – 使用系统定义的字符串直接查询,记得导入addressbook框架
nslog(@"kabpersonaddresscitykey = %@", (nsstring *)kabpersonaddresscitykey);
nslog(@"city = %@", place.addressdictionary[(nsstring *)kabpersonaddresscitykey]);
nsstring *city = place.locality;
if(city == nil)
{
city = place.addressdictionary[(nsstring *)kabpersonaddressstatekey];
}
}
}];
}

– (void)didreceivememorywarning
{
[super didreceivememorywarning];
// dispose of any resources that can be recreated.
}

@end


程序运行结果:(以39.3,116.4为例)

iOS开发中最基本的位置功能实现示例

复制代码 代码如下:


// 判断输入的地址
if (self.locationtextfield.text == nil || [self.locationtextfield.text length] == 0) {
return;
}

clgeocoder *geocoder = [[clgeocoder alloc] init];
/* —————————————–位置编码——————————————– */
[geocoder geocodeaddressstring:_locationtextfield.text completionhandler:^(nsarray *placemarks, nserror *error) {

for (clplacemark *placemark in placemarks) {

cllocationcoordinate2d coordinate = placemark.location.coordinate;
nsstring *strcoordinate = [nsstring stringwithformat:@"纬度 = %3.5f\\n 经度 = %3.5f",coordinate.latitude,coordinate.longitude];
nslog(@"%@",strcoordinate);
nsdictionary *addressdictionary = placemark.addressdictionary;
nsstring *address = [addressdictionary objectforkey:(nsstring *)kabpersonaddressstreetkey];
nsstring *state = [addressdictionary objectforkey:(nsstring *)kabpersonaddressstatekey];
nsstring *city = [addressdictionary objectforkey:(nsstring *)kabpersonaddresscitykey];
nslog(@"街道 = %@\\n 省 = %@\\n 城市 = %@",address,state,city);
}
}];

地图的使用以及标注地图
使用corelocation框架获取了当前设备的位置,这一章介绍地图的使用。
首先,导入<mapkit.framework>框架:

复制代码 代码如下:


#import <mapkit/mapkit.h>


main代码示例

复制代码 代码如下:


main.h

#import <uikit/uikit.h>
#import <mapkit/mapkit.h>
// 引用地图协议
@interface hmtmainviewcontroller : uiviewcontroller<mkmapviewdelegate>

@end

main.m

//
// hmtmainviewcontroller.m
// map
//
// created by hmt on 14-6-21.
// copyright (c) 2014年 humingtao. all rights reserved.
//

#import "hmtmainviewcontroller.h"
#import "hmtannotation.h"

@interface hmtmainviewcontroller ()

@property (nonatomic ,strong) mkmapview *mapview;

@end

@implementation hmtmainviewcontroller

– (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil
{
self = [super initwithnibname:nibnameornil bundle:nibbundleornil];
if (self) {
// custom initialization
}
return self;
}

– (void)viewdidload

{

[super viewdidload];
self.view.backgroundcolor = [uicolor redcolor];

// do any additional setup after loading the view.

self.navigationitem.title = @"地图标注";
self.mapview = [[mkmapview alloc] initwithframe:cgrectmake(0, 0, 320, 568)];

// 是否显示用户当前位置
self.mapview.showsuserlocation = yes;
// 设置代理
self.mapview.delegate = self;

// 地图显示类型
/**
* mkmaptypestandard = 0, // 标准地图
* mkmaptypesatellite, // 卫星地图
* mkmaptypehybrid // 混合地图
*/
self.mapview.maptype = mkmaptypestandard;
// 经纬度
cllocationcoordinate2d coord2d = {39.910650,116.47030};
// 显示范围,数值越大,范围就越大
mkcoordinatespan span = {0.1,0.1};
// 显示区域
mkcoordinateregion region = {coord2d,span};
// 给地图设置显示区域
[self.mapview setregion:region animated:yes];
// 是否允许缩放
//self.mapview.zoomenabled = no;
// 是否允许滚动
//self.mapview.scrollenabled = no;

// 初始化自定义annotation(可以设置多个)
hmtannotation *annotation = [[hmtannotation alloc] initwithcglocation:coord2d];
// 设置标题
annotation.title = @"自定义标注位置";
// 设置子标题
annotation.subtitle = @"子标题";
// 将标注添加到地图上(执行这步,就会执行下面的代理方法viewforannotation)
[self.mapview addannotation:annotation];

[self.view addsubview:_mapview];

}

// 返回标注视图(大头针视图)
– (mkannotationview *)mapview:(mkmapview *)mapview viewforannotation:(id<mkannotation>)annotation{

/**
* 是不是有点像自定义uitableviewcell一样
*/
static nsstring *identifier = @"annotation";
// 复用标注视图(mkpinannotationview是大头针视图,继承自mkannotation)
mkpinannotationview *annotationview = (mkpinannotationview *)[mapview dequeuereusableannotationviewwithidentifier:identifier];
if (annotationview == nil) {
annotationview = [[mkpinannotationview alloc] initwithannotation:annotation reuseidentifier:identifier];
}
// 判断是否为自定义的标注视图
if ([annotation iskindofclass:[hmtannotation class]]) {

// 设置大头针圆圈颜色
annotationview.pincolor = mkpinannotationcolorgreen;
// 点击头针红色圆圈是否显示上面设置好的标题视图
annotationview.canshowcallout = yes;
// 要自定义锚点图片,可考虑使用mkannotationview;mkpinannotationview只能是以大头针形式显示!!!!
annotationview.image = [uiimage imagenamed:@"customimage"];
// 添加标题视图右边视图(还有左边视图,具体可自行查看api)
uibutton *button = [uibutton buttonwithtype:uibuttontypedetaildisclosure];
[button addtarget:self action:@selector(didclickannotationviewrightbuttonaction:) forcontrolevents:uicontroleventtouchupinside];
annotationview.rightcalloutaccessoryview = button;
// 是否以动画形式显示标注(从天而降)
annotationview.animatesdrop = yes;
annotationview.annotation = annotation;

// 返回自定义的标注视图
return annotationview;

}else{

// 当前设备位置的标注视图,返回nil,当前位置会创建一个默认的标注视图
return nil;
}

}

– (void)didclickannotationviewrightbuttonaction:(uibutton *)button{

nslog(@"%d %s",__line__,__function__);
}

// 更新当前位置调用
– (void)mapview:(mkmapview *)mapview didupdateuserlocation:(mkuserlocation *)userlocation{

nslog(@"%d %s",__line__,__function__);
}

// 选中标注视图
– (void)mapview:(mkmapview *)mapview didselectannotationview:(mkannotationview *)view{

nslog(@"%d %s",__line__,__function__);
}

// 地图的现实区域改变了调用
– (void)mapview:(mkmapview *)mapview regiondidchangeanimated:(bool)animated{

nslog(@"%d %s",__line__,__function__);
}

– (void)didreceivememorywarning
{
[super didreceivememorywarning];
// dispose of any resources that can be recreated.
}

@end

自定义mkannotationview

复制代码 代码如下:


#import <foundation/foundation.h>
#import <mapkit/mapkit.h>
// 引入mkannotation协议,切记不能忘记!!!!!!!!!
@interface hmtannotation : nsobject<mkannotation>

@property (nonatomic,readonly) cllocationcoordinate2d coordinate; // 坐标
@property (nonatomic,copy) nsstring *title; // 位置名称
@property (nonatomic,copy) nsstring *subtitle; // 位置子信息(可选)

– (id)initwithcglocation:(cllocationcoordinate2d) coordinate;

@end

#import "hmtannotation.h"

@implementation hmtannotation

– (id)initwithcglocation:(cllocationcoordinate2d)coordinate{

if (self = [super init]) {

_coordinate = coordinate;
}
return self;
}

@end

效果图:

iOS开发中最基本的位置功能实现示例

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS开发中最基本的位置功能实现示例 https://www.kuaiidc.com/94493.html

相关文章

发表评论
暂无评论