定位 -CLGeocoder - 编码

时间:2023-03-09 18:28:28
定位 -CLGeocoder - 编码

#import "ViewController.h"

#import <CoreLocation/CoreLocation.h>

@interface ViewController ()

/**  地理编码对象 ***/

@property (nonatomic, strong) CLGeocoder *geocoder;

@property (weak, nonatomic) IBOutlet UITextField *addressField; // 地址

@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;   // 经度

@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;    // 纬度

@property (weak, nonatomic) IBOutlet UILabel *detailLabel;      // 具体地址

@end

@implementation ViewController

- (IBAction)codingBtn:(id)sender {

// 0.获取输入位置

NSString *addressStr = self.addressField.text;

if (addressStr == nil || addressStr.length == 0) {

LogGreen(@"请输入地址");

return;

}

// 1. 创建地理编码对象

// 2. 利用地理编码对象编码

[self.geocoder geocodeAddressString:addressStr completionHandler:^(NSArray *placemarks, NSError *error) {

// placemarks: 地标数组, 每一个地标包含了该位置的经纬度以及城市 区域 国家代码 邮编等信息

// 获取数组中第一个 信息

CLPlacemark *placemark = [placemarks firstObject];

self.longitudeLabel.text = [NSString stringWithFormat:@"%f",placemark.location.coordinate.longitude];

self.latitudeLabel.text = [NSString stringWithFormat:@"%f",placemark.location.coordinate.latitude];

NSDictionary *addressDic = placemark.addressDictionary;

/**

*  City = Beijing;

Country = China;

CountryCode = CN;

FormattedAddressLines =     (

"Beijing China"

);

State = Beijing;

*/

NSArray *addresses = addressDic[@"FormattedAddressLines"];

NSMutableString *mutstr = [NSMutableString string];

for (NSString *subStr in addresses) {

[mutstr appendString:subStr];

}

self.detailLabel.text = mutstr; // 模拟器设置成 中文 - 输出显示为中文

LogRed(@"%@ - %@ - %f - %f",placemark.name, placemark.addressDictionary, placemark.location.coordinate.longitude, placemark.location.coordinate.latitude);

}];

// 键盘弹回

[self.view endEditing:YES];

}

/**

* 1. 创建地理编码对象

*/

- (CLGeocoder *)geocoder{

if (!_geocoder) {

_geocoder = [[CLGeocoder alloc] init];

}

return _geocoder;

}

- (void)viewDidLoad {

[super viewDidLoad];

//    NSLocationAlwaysUsageDescription

//    NSLocationWhenInUseDescription

}