编码: 位置的名字 ——> 经纬度
反编码:经纬度 ——> 位置的名字(以及相关的信息)
xib对应的界面:
这些控件在类中对应的属性。
则.h 文件是:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
#import <AddressBook/AddressBook.h>
@interface ViewController : UIViewController <CLLocationManagerDelegate>
//经度
@property (weak, nonatomic) IBOutlet UITextField *txtLng;
//纬度
@property (weak, nonatomic) IBOutlet UITextField *txtLat;
//高度
@property (weak, nonatomic) IBOutlet UITextField *txtAlt;
@property(nonatomic, strong) CLLocationManager *locationManager;
@property(nonatomic, strong) CLLocation *currLocation;
@property (weak, nonatomic) IBOutlet UITextView *txtView;
- (IBAction)reverseGeocode:(id)sender;
@end
然后对相应的给出的信息进行反编码:
//
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//定位服务管理对象初始化
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
[_locationManager requestAlwaysAuthorization];
//设置要求的请准度
_locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
//300米会更新一次,
_locationManager.distanceFilter = 300.0f;
//哲理有的时候
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//开始定位
[_locationManager startUpdatingLocation];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//停止定位
[_locationManager stopUpdatingLocation];
}
#pragma mark Core Location委托方法用于实现位置的更新
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
_currLocation = [locations lastObject];
_txtLat.text = [NSString stringWithFormat:@"%3.5f",
_currLocation.coordinate.latitude];
_txtLng.text = [NSString stringWithFormat:@"%3.5f",
_currLocation.coordinate.longitude];
_txtAlt.text = [NSString stringWithFormat:@"%3.5f",
_currLocation.altitude];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@",error);
}
- (IBAction)reverseGeocode:(id)sender {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//注意编码与反编码的过程中需要消耗的时间比较长
//反编码串 将查询的结果返回给placemarks这个数组参数
[geocoder reverseGeocodeLocation:_currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0) {
//这个是定位上的地标,还有对应的是地图上的地标
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary = placemark.addressDictionary;
//这里用到了通讯录
NSString *address = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStreetKey];
address = address == nil ? @"": address;
NSString *state = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStateKey];
state = state == nil ? @"": state;
NSString *city = [addressDictionary
objectForKey:(NSString *)kABPersonAddressCityKey];
city = city == nil ? @"": city;//这个是一个判断的连用
_txtView.text = [NSString stringWithFormat:@"%@ \n%@ \n%@",state, address,city];//编程字符串
}
}];
}
@end
运行之后得到的结果是:
从上面的信息可以查看到结果通过给出经纬度反编码。
编码和反编码几乎没有什么差别,只是使用的函数不同。
其中还涉及到通讯录,可以通过通讯录来存储和获取相应的值。通讯录也是一个快专题,可以研究。