首页 > 代码库 > iOS 地理编码和反地理编码
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 *)event16 {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 }
iOS 地理编码和反地理编码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。