iOS功能模块收录iOS收藏iOS开发记录

地理编码与反地理编码

2016-06-30  本文已影响379人  IIronMan

(一)地理编码

地理编码方法:


编码展示

下面是具体的代码:(在storyBoard里面画的,1个button,1个UITextFiled,3个UILabel)

 #import "ViewController.h"
 #import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>

/*
   需要编码的地址容器
*/
@property (weak, nonatomic) IBOutlet UITextField *addressFiled;

/*
    经度容器
*/
 @property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
/*
    纬度容器
*/
@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
/*
    详情容器
*/
@property (weak, nonatomic) IBOutlet UILabel *detailAddressLabel;
/*
    监听地理编码点击事件
*/

- (IBAction)geocoderBtnClick;

@property(nonatomic,strong) CLGeocoder *geocoder;

@end

@implementation ViewController

//1.创建地理编码对象
-(CLGeocoder *)geocoder
{
  if (!_geocoder) {
    
    _geocoder = [[CLGeocoder alloc]init];
}

  return _geocoder;
}

- (void)viewDidLoad {
[super viewDidLoad];

self.addressFiled.clearButtonMode = UITextFieldViewModeAlways;
self.addressFiled.placeholder = @"    请输入地理位置";

}


- (IBAction)geocoderBtnClick {

//获取用户输入的位置
NSString *addressString = self.addressFiled.text;

NSLog(@"%@",addressString);

if (addressString == nil || addressString.length == 0) {
    
    NSLog(@"请输入地址");
    return;
}

//2.利用地理编码对象编码
//根据传入的地址获取该地址的对应的经纬度信息
[self.geocoder geocodeAddressString:self.addressFiled.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
    
    //placemarks 地标  地标数组里面存放着地标,每一个地标包含了该位置的经纬度,以及城市/区域/国家代码/邮编等等....
    if (placemarks.count == 0 || error != nil) {
        
        return;
    }

    //获取数组里面第一个信息
    CLPlacemark *placemark = [placemarks firstObject];
    
    self.latitudeLabel.text = [NSString stringWithFormat:@"   %f", placemark.location.coordinate.latitude];
    
    self.longitudeLabel.text = [NSString stringWithFormat:@"   %f",placemark.location.coordinate.longitude];
    
    NSArray *array = placemark.addressDictionary[@"FormattedAddressLines"];
    
    NSMutableString *stringAddstring = [NSMutableString string];
    
    for (NSString *string in array) {
        [stringAddstring appendString:string];
    }
    
    self.detailAddressLabel.text = stringAddstring;
    
    NSLog(@"%@ %@ %f %f",placemark.name,placemark.addressDictionary,placemark.location.coordinate.latitude,placemark.location.coordinate.longitude);
    
}];

 }
 @end

(二)反地理编码

    1.创建地理编码对象:导入框架#import <CoreLocation/CoreLocation.h>

       CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    2.利用地理编码对象编码:声明一个@property(nonatomic,strong) CLGeocoder *geocoder;属性

调用一个反地理编码方法:(很重要)

[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) 
反编码
上一篇 下一篇

猜你喜欢

热点阅读