一 前言
本章主要介紹地理編碼及反地理編碼伶氢,需要用到CLGeocoder類
二 地理編碼
在下圖綠框內(nèi)輸入地址趟径,點擊地理編碼,顯示經(jīng)度和緯度
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextView *addressTV;// 那個綠框textView
@property (weak, nonatomic) IBOutlet UITextField *longTF;//經(jīng)度的field
@property (weak, nonatomic) IBOutlet UITextField *laTF;//緯度的field
//地理編碼
@property (nonatomic, strong) CLGeocoder *geoC;
@end
@implementation ViewController
#pragma mark - 懶加載
- (CLGeocoder *)geoC{
if (!_geoC) {
_geoC = [[CLGeocoder alloc] init];
}
return _geoC;
}
//點擊“地理編碼”按鈕
- (IBAction)geoCode {
NSString *str = self.addressTV.text;
if ([str length] == 0) {
return ;
}
// 編碼其實是去向蘋果服務(wù)器請求數(shù)據(jù)
[self.geoC geocodeAddressString:str completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
/**
* CLPlacemark
*
*/
if (!error) {
NSLog(@"%@",placemarks);
// 遍歷一下這個數(shù)組癣防,因為可能有多個查詢結(jié)果被返回
[placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"name = %@",obj.name);
self.addressTV.text = obj.name;
// self.laTF.text = [NSString stringWithFormat:@"%f",obj.location.coordinate.latitude];
// self.longTF.text = [NSString stringWithFormat:@"%f",obj.location.coordinate.longitude];
self.laTF.text = @(obj.location.coordinate.latitude).stringValue;//獲obj.location.coordinate.latitude的字符串格式
self.longTF.text = @(obj.location.coordinate.longitude).stringValue;
}];
}else{
NSLog(@"error = %@",error);
}
}];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
@end
三 反地理編碼
在上圖輸入經(jīng)度和緯度的地方蜗巧,分別輸入經(jīng)度和緯度,點擊反地理編碼蕾盯,在綠框內(nèi)顯示地址
//點擊“反地理編碼”按鈕
- (IBAction)reverseGeoCode {
CLLocationDegrees latitude = [self.laTF.text doubleValue];
CLLocationDegrees longtitude = [self.longTF.text doubleValue];
// TODO: 容錯幕屹,防止用戶輸入非經(jīng)緯度的內(nèi)容
// if (!) {
// <#statements#>
// }
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longtitude];
[self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (!error) {
NSLog(@"%@",placemarks);
[placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
self.addressTV.text = obj.name;
}];
}else{
NSLog(@"無法正常編碼");
}
}];
}