iOS中CoreLocatio框架中的CLGeocoder 類(lèi)不但為我們提供了地理編碼方法,而且還提供了反地理編碼:
同樣需要導(dǎo)入框架:
#import <CoreLocation/CoreLocation.h>
反地理編碼方法:
- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
同樣當(dāng)反地理編碼完成時(shí),會(huì)調(diào)用completionHandler
對(duì)象佛吓,該對(duì)象類(lèi)型為 CLGeocodeCompletionHandler
晒他,實(shí)際上是一個(gè) block 對(duì)象
這個(gè)對(duì)象中傳遞了2個(gè)參數(shù)津滞,其中placemark:
里面裝了CLPlacemark
對(duì)象
步驟:
1、創(chuàng)建地理編碼對(duì)象
2、獲取用戶的地理坐標(biāo)(經(jīng)緯度)
3、根據(jù)地理坐標(biāo)創(chuàng)建CLLocation
對(duì)象
4、根據(jù)CLLocation
對(duì)象獲取對(duì)象坐標(biāo)信息
Demo如下 :
@interface ViewController ()
//地理編碼對(duì)象
@property (nonatomic ,strong) CLGeocoder *geocoder;
#pragma mark - 反地理編碼
- (IBAction)reverseGeocode;
@property (weak, nonatomic) IBOutlet UITextField *longtitudeField;
@property (weak, nonatomic) IBOutlet UITextField *latitudeField;
@property (weak, nonatomic) IBOutlet UILabel *reverseDetailAddressLabel;
@end
@implementation ViewController
#pragma mark - 反地理編碼響應(yīng)
- (void)reverseGeocode
{
// 1.獲取用戶輸入的經(jīng)緯度
NSString *longtitude = self.longtitudeField.text;
NSString *latitude = self.latitudeField.text;
if (longtitude.length == 0 ||
longtitude == nil ||
latitude.length == 0 ||
latitude == nil) {
NSLog(@"請(qǐng)輸入經(jīng)緯度");
return;
}
// 2.根據(jù)用戶輸入的經(jīng)緯度創(chuàng)建CLLocation對(duì)象
CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude doubleValue] longitude:[longtitude doubleValue]];
// 116.403857,39.915285
// 3.根據(jù)CLLocation對(duì)象獲取對(duì)應(yīng)的地標(biāo)信息
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
NSLog(@"%@ %@ %f %f", placemark.name, placemark.addressDictionary, placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
self.reverseDetailAddressLabel.text = placemark.locality;
}
}];
}
#pragma mark - 懶加載,創(chuàng)建地理編碼對(duì)象
- (CLGeocoder *)geocoder
{
if (!_geocoder) {
_geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}
效果圖如下: