一 前言
本章主要介绍地理编码及反地理编码,需要用到CLGeocoder类
二 地理编码
在下图绿框内输入地址,点击地理编码,显示经度和纬度
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextView *addressTV;// 那个绿框textView
@property (weak, nonatomic) IBOutlet UITextField *longTF;//经度的field
@property (weak, nonatomic) IBOutlet UITextField *laTF;//纬度的field
//地理编码
@property (nonatomic, strong) CLGeocoder *geoC;
@end
@implementation ViewController
#pragma mark - 懒加载
- (CLGeocoder *)geoC{
if (!_geoC) {
_geoC = [[CLGeocoder alloc] init];
}
return _geoC;
}
//点击“地理编码”按钮
- (IBAction)geoCode {
NSString *str = self.addressTV.text;
if ([str length] == 0) {
return ;
}
// 编码其实是去向苹果服务器请求数据
[self.geoC geocodeAddressString:str completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
/**
* CLPlacemark
*
*/
if (!error) {
NSLog(@"%@",placemarks);
// 遍历一下这个数组,因为可能有多个查询结果被返回
[placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"name = %@",obj.name);
self.addressTV.text = obj.name;
// self.laTF.text = [NSString stringWithFormat:@"%f",obj.location.coordinate.latitude];
// self.longTF.text = [NSString stringWithFormat:@"%f",obj.location.coordinate.longitude];
self.laTF.text = @(obj.location.coordinate.latitude).stringValue;//获obj.location.coordinate.latitude的字符串格式
self.longTF.text = @(obj.location.coordinate.longitude).stringValue;
}];
}else{
NSLog(@"error = %@",error);
}
}];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
@end
三 反地理编码
在上图输入经度和纬度的地方,分别输入经度和纬度,点击反地理编码,在绿框内显示地址
//点击“反地理编码”按钮
- (IBAction)reverseGeoCode {
CLLocationDegrees latitude = [self.laTF.text doubleValue];
CLLocationDegrees longtitude = [self.longTF.text doubleValue];
// TODO: 容错,防止用户输入非经纬度的内容
// if (!) {
// <#statements#>
// }
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longtitude];
[self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (!error) {
NSLog(@"%@",placemarks);
[placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
self.addressTV.text = obj.name;
}];
}else{
NSLog(@"无法正常编码");
}
}];
}