首先通過拖控件的方法
添加系統庫 CoreGraphics.framework
導入頭文件
#import <CoreLocation/CoreLocation.h>
//拖得控件
//地址
@property (weak, nonatomic) IBOutlet UITextField *dizhiTf;
//緯度
@property (weak, nonatomic) IBOutlet UITextField *weiduTf;
//經度
@property (weak, nonatomic) IBOutlet UITextField *jingduTf;
//結果
@property (weak, nonatomic) IBOutlet UITextView *jieguo;
@property (strong, nonatomic) CLGeocoder* geocoder;
- (void)viewDidLoad {
[super viewDidLoad];
// 創建地址解析器
self.geocoder = [[CLGeocoder alloc] init];
}
正解
//解析
- (IBAction)dizhi:(id)sender {
// 獲取用戶輸入的地址字符串
NSString* addr = self.dizhiTf.text;
if(addr != nil && addr.length > 0)
{
[self.geocoder geocodeAddressString:addr
completionHandler: ^(NSArray *placemarks, NSError *error)
{
// 如果解析結果的集合元素的個數大于1,表明解析得到了經度、緯度信息
if (placemarks.count > 0)
{
// 只處理第一個解析結果,實際項目中可使用列表讓用戶選擇
CLPlacemark* placemark = placemarks[0];
CLLocation* location = placemark.location;
self.jieguo.text = [NSString stringWithFormat:
@"%@的緯度為:%g,經度為:%g" , addr ,location.coordinate.latitude,
location.coordinate.longitude
];
}
// 沒有得到解析結果。
else
{
// 使用UIAlertView提醒用戶
[[[UIAlertView alloc] initWithTitle:@"提醒"
message:@"您輸入的地址無法解析" delegate:nil
cancelButtonTitle:@"確定" otherButtonTitles: nil]
show];
}
}];
}
}
反解析
//反解析
//托的控件
- (IBAction)fanjie:(id)sender {
//經度
NSString* longitudeStr = self. jingduTf.text;
//緯度
NSString* latitudeStr = self.weiduTf.text;
if(longitudeStr != nil && longitudeStr.length > 0
&& latitudeStr != nil && latitudeStr.length > 0)
{
// 將用戶輸入的經度、緯度封裝成CLLocation對象
CLLocation* location = [[CLLocation alloc]
initWithLatitude:[latitudeStr floatValue]
longitude:[longitudeStr floatValue]];
[self.geocoder reverseGeocodeLocation:location completionHandler:
^(NSArray *placemarks, NSError *error)
{
// 如果解析結果的集合元素的個數大于1,表明解析得到了經度、緯度信息
if (placemarks.count > 0)
{
// 只處理第一個解析結果,實際項目可使用列表讓用戶選擇
CLPlacemark* placemark = placemarks[0];
// 獲取詳細地址信息
NSArray* addrArray = [placemark.addressDictionary
objectForKey:@"FormattedAddressLines"];
// 將詳細地址拼接成一個字符串
NSMutableString* addr = [[NSMutableString alloc] init];
for(int i = 0 ; i < addrArray.count ; i ++)
{
[addr appendString:addrArray[i]];
}
self.jieguo.text = [NSString stringWithFormat:
@"經度:%g,緯度:%g的地址為:%@" ,
location.coordinate.longitude ,
location.coordinate.latitude , addr];
}
// 沒有得到解析結果。
else
{
// 使用UIAlertView提醒用戶
[[[UIAlertView alloc] initWithTitle:@"提醒"
message:@"您輸入的地址無法解析" delegate:nil
cancelButtonTitle:@"確定" otherButtonTitles: nil]
show];
}
}];
}
}