已知地名,解析为 经纬度 和 高度
#import <CoreLocation/CoreLocation.h>
@interface TwoViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *locationTF;
@property (weak, nonatomic) IBOutlet UILabel *lagLabel;
@property (weak, nonatomic) IBOutlet UILabel *lngLabel;
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@end
@implementation TwoViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (IBAction)searchButtonAction:(UIButton *)sender {
[self.locationTF resignFirstResponder];
NSLog(@"text = %@",self.locationTF.text);
if (self.locationTF.text == nil || [self.locationTF.text length] == 0) {
return;
}
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:self.locationTF.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
NSLog(@"查询记录数:%u",[placemarks count]);
if ([placemarks count] > 0) {
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary = placemark.addressDictionary;
NSLog(@"%@",addressDictionary);
// 属性获得地标的经纬度信息
CLLocationCoordinate2D coordinate = placemark.location.coordinate;
// NSString *strCoordinate = [NSString stringWithFormat:@"经度:%3.5f \n 纬度:%3.5f", coordinate.latitude,coordinate.longitude];
self.lagLabel.text = [NSString stringWithFormat:@"%f",coordinate.latitude];
self.lngLabel.text = [NSString stringWithFormat:@"%f",coordinate.longitude];
// 国家
NSString *address = addressDictionary[@"Country"];
// 省份
NSString *addressState = addressDictionary[@"State"];
// 城市
NSString *addressCity = addressDictionary[@"City"];
// 区域
NSString *addressSubLocality = addressDictionary[@"SubLocality"];
// 街道
NSString *addressThoroughfare = addressDictionary[@"Thoroughfare"];
addressThoroughfare = addressThoroughfare == nil ? @"":addressThoroughfare;
self.cityLabel.text = [NSString stringWithFormat:@"%@ %@ %@ %@ %@",address,addressState,addressCity,addressSubLocality,addressThoroughfare];
}
}];
}