您的位置:首页 > 移动开发 > IOS开发

iOS地图 -- 地理编码和反地理编码

2016-09-06 11:23 447 查看

地理编码和反地理编码

用到的类和方法

CLGeocoder
--> 地理编码管理器

- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;
--> 地理编码(将地址关键字 >> 经纬度)

- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
--> 反地理编码(将经纬度 >> 详细地址)

CLPlacemark
--> 地标对象;包含对应的位置对象,地址名称,城市等等

地理编码和反地理编码的小练习

简单布局

练习代码

#import "ViewController.h"

#import <CoreLocation/CoreLocation.h>

@interface ViewController ()

/** 地理编码管理器 */
@property (nonatomic, strong) CLGeocoder *geoC;

@property (weak, nonatomic) IBOutlet UITextView *addressTV;

@property (weak, nonatomic) IBOutlet UITextField *latitudeTF;

@property (weak, nonatomic) IBOutlet UITextField *longitudeTF;

@end

@implementation ViewController

#pragma mark - 懒加载
/** 地理编码管理器 */
- (CLGeocoder *)geoC
{
if (!_geoC) {
_geoC = [[CLGeocoder alloc] init];
}
return _geoC;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
// 地理编码(地址关键字 ->经纬度 )
- (IBAction)geoCode {

NSString *address = self.addressTV.text;

// 容错处理
if([address length] == 0)
{
return;
}

// 根据地址关键字, 进行地理编码
[self.geoC geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

/**
*  CLPlacemark : 地标对象
*  location : 对应的位置对象
*  name : 地址全称
*  locality : 城市
*  按相关性进行排序
*/
CLPlacemark *pl = [placemarks firstObject];

if(error == nil)
{
NSLog(@"%f----%f", pl.location.coordinate.latitude, pl.location.coordinate.longitude);

NSLog(@"%@", pl.name);
self.addressTV.text = pl.name;
self.latitudeTF.text = @(pl.location.coordinate.latitude).stringValue;
self.longitudeTF.text = @(pl.location.coordinate.longitude).stringValue;
}
}];
}

// 反地理编码(把经纬度---> 详细地址)
- (IBAction)reverseGeoCode
{
double latitude = [self.latitudeTF.text doubleValue];
double longitude = [self.longitudeTF.text doubleValue];

CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

[self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *pl = [placemarks firstObject];

if(error == nil)
{
NSLog(@"%f----%f", pl.location.coordinate.latitude, pl.location.coordinate.longitude);

NSLog(@"%@", pl.name);
self.addressTV.text = pl.name;
self.latitudeTF.text = @(pl.location.coordinate.latitude).stringValue;
self.longitudeTF.text = @(pl.location.coordinate.longitude).stringValue;
}
}];
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: