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

 更新时间:2015年09月17日 09:19:01   作者:TommyYaphetS  
这篇文章主要介绍了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为例)

复制代码 代码如下:

//  判断输入的地址 
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 单例的两种方式

    详解IOS 单例的两种方式

    这篇文章主要介绍了详解IOS 单例的两种方式的相关资料,希望通过本文大家能够理解掌握IOS 的两种单例的使用方法,需要的朋友可以参考下
    2017-09-09
  • iOS中UIAlertController设置自定义标题与内容的方法

    iOS中UIAlertController设置自定义标题与内容的方法

    UIAlertController是iOS8推出的新概念,取代了之前的 UIAlertView和UIActionSheet(虽然现在仍可以使用,但是会有警告)。下面这篇文章主要给大家介绍了关于iOS中UIAlertController如何设置自定义标题与内容的相关资料,需要的朋友可以参考下。
    2017-10-10
  • ios启动页强制竖屏(进入App后允许横屏与竖屏)

    ios启动页强制竖屏(进入App后允许横屏与竖屏)

    最近工作遇到这样一个需要,当进入启动页需要强制竖屏,而进入APP后就允许横屏与竖屏,通过查找相关的资料找到了解决的方法,所以将实现的方法整理后分享出来,需要的朋友们可以参考借鉴,下面来一起看看吧。
    2017-03-03
  • 详解iOS开发获取当前控制器的正取方式

    详解iOS开发获取当前控制器的正取方式

    这篇文章主要介绍了iOS开发获取当前控制器的正取方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • iOS的CoreAnimation开发框架中的Layer层动画制作解析

    iOS的CoreAnimation开发框架中的Layer层动画制作解析

    在iOS中UIView层的属性会映射到CoreAnimation框架的CALayer,这里我们来看一下iOS的CoreAnimation开发框架中的Layer层动画制作解析,需要的朋友可以参考下
    2016-07-07
  • 适配iPhoneXS max和iPhoneX R的方法示例

    适配iPhoneXS max和iPhoneX R的方法示例

    这篇文章主要介绍了适配iPhoneXS max和iPhoneX R的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-10-10
  • iOS实现小型计算器

    iOS实现小型计算器

    这篇文章主要为大家详细介绍了iOS实现小型计算器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • IOS开发Swift 与 OC相互调用详解

    IOS开发Swift 与 OC相互调用详解

    这篇文章主要为大家介绍了IOS开发Swift 与 OC相互调用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • iOS开发教程之扇形动画的实现

    iOS开发教程之扇形动画的实现

    实现扇形图大家应该都会的,但是扇形动画大家都会实现吗?下面这篇文章主要给大家介绍了关于iOS开发教程之扇形动画实现的相关资料,文中介绍的非常详细,需要的朋友们下面跟着小编一起来学习学习吧。
    2017-06-06
  • iOS编写下拉刷新控件

    iOS编写下拉刷新控件

    这篇文章主要介绍了iOS编写下拉刷新控件的相关资料,iOS如何写个普通的下拉刷新的控件,需要了解的朋友可以参考下文
    2016-04-04

最新评论