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

2016-02-19 11:24 13 1 收藏

图老师小编精心整理的iOS开发中最基本的位置功能实现示例希望大家喜欢,觉得好的亲们记得收藏起来哦!您的支持就是小编更新的动力~

【 tulaoshi.com - 编程语言 】

定位获取位置及位置编码-反编码
我们的应用程序,可以通过添加Core Location框架所包含的类,获取设备的地图位置。
添加CoreLocation.framework框架,导入#importCoreLocation/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.5fn 经度 = %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 : UIViewControllerMKMapViewDelegate 
 
@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:(idMKAnnotation)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 

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

自定义MKAnnotationView
代码如下:

#import Foundation/Foundation.h 
#import MapKit/MapKit.h 
//  引入MKAnnotation协议,切记不能忘记!!!!!!!!! 
@interface HMTAnnotation : NSObjectMKAnnotation 
 
@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 

效果图:

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

来源:https://www.tulaoshi.com/n/20160219/1597378.html

延伸阅读
我们知道Gif是由一阵阵画面组成的,而且每一帧画面播放的时常可能会不相等,观察上面两个例子,发现他们都没有对Gif中每一帧的显示时常做处理,这样的结果就是整个Gif中每一帧画面都是以固定的速度向前播放,很显然这并不总会符合需求。   于是自己写一个解析Gif的工具类,解决每一帧画面并遵循每一帧所对应的显示时间进行播放。 &nbs...
预备知识 iOS处理屏幕上的触摸动作,主要涉及到以下几个方法: 代码如下: touchesBegan:withEvent:          //触摸屏幕的最开始被调用 touchesMoved:withEvent:         //移动过程中被调用 touchesEnded:withEvent:    &nbs...
太极拳视频 太极拳技法中最基本的原理 太极拳博大精深,当中的一招一式都有着深刻的道理所在,在太极拳中运用较为普遍的就是平衡性的原理,今天图老师小编就为大家讲一讲太极拳运动中的基本原理,掌握这些,相信会对大家的太极拳学习有所提高的。 学习太极拳,关键就是在于重心的把握,太极拳的技击和推手中都体现的较为突出...
一、简单介绍 在iOS中,你能看得见摸得着的东西基本上都是UIView,比如一个按钮、一个文本标签、一个文本输入框、一个图标等等,这些都是UIView。 其实UIView之所以能显示在屏幕上,完全是因为它内部的一个图层,在创建UIView对象时,UIView内部会自动创建一个图层(即CALayer对象),通过UIView的layer属性可以访问这个层 @property(nonatom...
Method Swizzling 原理 在Objective-C中调用一个方法,其实是向一个对象发送消息,查找消息的唯一依据是selector的名字。利用Objective-C的动态特性,可以实现在运行时偷换selector对应的方法实现,达到给方法挂钩的目的。 每个类都有一个方法列表,存放着selector的名字和方法实现的映射关系。IMP有点类似函数指针,指向具体的Method实现。...

经验教程

28

收藏

39
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部