服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS开发中最基本的位置功能实现示例

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

2020-12-24 15:10TommyYaphetS IOS

这篇文章主要介绍了iOS开发中最基本的位置功能实现示例,需要的朋友可以参考下

定位获取位置及位置编码-反编码
我们的应用程序,可以通过添加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开发中最基本的位置功能实现示例

延伸 · 阅读

精彩推荐
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01