iOS 地理编码和反地理编码
1.UI搭建,import头文件
#import <CoreLocation/CoreLocation.h>
2.添加成员变量,并连线
1 - (IBAction)geocodeButton; 2 @property (weak, nonatomic) IBOutlet UITextField *inputAddress; 3 @property (weak, nonatomic) IBOutlet UITextField *longitude; 4 @property (weak, nonatomic) IBOutlet UITextField *latitude; 5 @property (weak, nonatomic) IBOutlet UITextView *detailAddress; 6 7 8 - (IBAction)unGeocodeButton; 9 @property (weak, nonatomic) IBOutlet UITextField *reverseLongitude; 10 @property (weak, nonatomic) IBOutlet UITextField *reverseLatitude; 11 @property (weak, nonatomic) IBOutlet UITextView *reverseDetailAddress;
3.添加地理编码和反地理编码的方法
1 /** 2 * 懒加载 3 */ 4 - (CLGeocoder *)geocoder 5 { 6 if (_geocoder == nil) { 7 _geocoder = [[CLGeocoder alloc]init]; 8 } 9 return _geocoder; 10 } 11 12 /** 13 * 键盘处理 14 */ 15 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 16 { 17 [self.view endEditing:YES]; 18 } 19 20 /** 21 * 地理编码 22 */ 23 - (IBAction)geocodeButton { 24 NSString *address = self.inputAddress.text; 25 [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) { 26 // 地址为空,直接返回 27 if (!address) return ; 28 if (error) { // 输入的地址有错误 29 self.detailAddress.text = @"你输入的地址可能不存在"; 30 }else{ 31 // 遍历查询到的地标 32 NSLog(@"总共有%d个地标符合要求",placemarks.count); 33 for (int i = 0; i < placemarks.count; i++) { 34 CLPlacemark *placemark = placemarks[i]; 35 NSLog(@"%@",placemark); 36 } 37 38 // 取地标数组的第一个为最终结果 39 CLPlacemark *placemark = [placemarks firstObject]; 40 self.detailAddress.text = placemark.name; 41 self.latitude.text =[NSString stringWithFormat:@"%.1f", placemark.location.coordinate.latitude]; 42 self.longitude.text = [NSString stringWithFormat:@"%.1f", placemark.location.coordinate.longitude]; 43 } 44 }]; 45 } 46 47 /** 48 * 反地理编码 49 */ 50 - (IBAction)unGeocodeButton { 51 // 经纬度转换 52 CLLocationDegrees longitude = [self.reverseLongitude.text doubleValue]; 53 CLLocationDegrees latitude = [self.reverseLatitude.text doubleValue]; 54 CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude]; 55 56 // 反地理编码 57 [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 58 if (location == nil) return; 59 if (error) { 60 NSLog(@"你输入的经纬度有误"); 61 }else{ 62 // 遍历地标数组 63 NSLog(@"总共有%d个地标符合要求",placemarks.count); 64 for (int i; i < placemarks.count; i++) { 65 CLPlacemark *placemark = placemarks[i]; 66 NSLog(@"%@",placemark); 67 } 68 69 // 取地标数组的第一个为最终结果 70 CLPlacemark *placemark =[placemarks firstObject]; 71 self.reverseDetailAddress.text = placemark.name; 72 } 73 74 }]; 75 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。