一、CLGeocoder 地理編碼 與 反地理編碼
-
地理編碼
:- 根據給定的地名,獲得具體的位置信息(比如經緯度、地址的全稱等)
// 地理編碼方法 -(void)geocodeAddressString:(NSString*)addressStringcompletionHandler:(CLGeocodeCompletionHandler)completionHandler;
-
反地理編碼
:- 根據給定的經緯度,獲得具體的位置信息
// 反地理編碼方法
-(void)reverseGeocodeLocation:(CLLocation*)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
+ 注意:CLGeocodeCompletionHandler
- 當地理\反地理編碼完成時,就會`調用CLGeocodeCompletionHandler`,可以`獲取到CLPlacemark對象`
```objc
// 這個block傳遞2個參數
// error:當編碼出錯時(比如編碼不出具體的信息)有值
// placemarks:里面裝著CLPlacemark對象
typedef void(^CLGeocodeCompletionHandler)
(NSArray*placemarks, NSError*error);
- CLPlacemark(locality:城市名稱 thoroughfare:街道名稱 name:全稱 CLLocation *location)
二、應用場景
- 1、與定位結合使用,用于確定當前用戶所在的具體地址信息
三、實例
#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)geoCoder {
NSString *address = self.addressTV.text;
// 容錯
if([address length] == 0)
return;
[self.geoC geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
// CLPlacemark : 地標
// location : 位置對象
// addressDictionary : 地址字典
// name : 地址詳情
// locality : 城市
if(error == nil)
{
CLPlacemark *pl = [placemarks firstObject];
self.addressTV.text = pl.name;
self.latitudeTF.text = @(pl.location.coordinate.latitude).stringValue;
self.longitudeTF.text = @(pl.location.coordinate.longitude).stringValue;
}else
{
NSLog(@"錯誤");
}
}];
}
- (IBAction)reverseGeoCoder {
// 獲取用戶輸入的經緯度
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) {
if(error == nil)
{
CLPlacemark *pl = [placemarks firstObject];
self.addressTV.text = pl.name;
self.latitudeTF.text = @(pl.location.coordinate.latitude).stringValue;
self.longitudeTF.text = @(pl.location.coordinate.longitude).stringValue;
}else
{
NSLog(@"錯誤");
}
}];
}
@end