iOS中CoreLocatio框架中的CLGeocoder為我們提供了地理編碼方法:
首先需要導入框架
#import <CoreLocation/CoreLocation.h>
地理編碼方法有三種:
- (void)geocodeAddressDictionary:(NSDictionary *)addressDictionary completionHandler:(CLGeocodeCompletionHandler)completionHandler;
- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;
- (void)geocodeAddressString:(NSString *)addressString inRegion:(nullable CLRegion *)region completionHandler:(CLGeocodeCompletionHandler)completionHandler;
下面簡單的介紹其中一種常用的方法<上面提到的第二種方法>:步驟:
1莉兰、獲取用戶輸入的地理位置
2、創(chuàng)建地理編碼對象<CLGeocoder
對象>
3捻爷、利用地理編碼對象編碼
3.1荆萤、當編碼完成時魔招,會調(diào)用 completionHandler
對象在塔,該對象類型為 CLGeocodeCompletionHandler
来候,實際上是一個 block 對象
這個對象中傳遞了2個參數(shù)控淡,其中placemark:
里面裝了CLPlacemark
對象
CLPlacemark
對象中包含了 該位置的經(jīng)緯度以及城市/區(qū)域/國家代碼/郵編等等...信息由此我們可以根據(jù)返回參數(shù)
placemark
獲取到我們需要的數(shù)據(jù)< Demo如下 >:
@interface ViewController ()
#pragma mark - 地理編碼
//監(jiān)聽地理編碼點擊事件
- (IBAction)geocodeBtnClick;
// 需要編碼的地址
@property (weak, nonatomic) IBOutlet UITextField *addressField;
//經(jīng)度
@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
//緯度
@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
//詳情
@property (weak, nonatomic) IBOutlet UILabel *detailAddressLabel;
//地理編碼對象
@property (nonatomic ,strong) CLGeocoder *geocoder;
@end
#pragma mark - 地理編碼響應
- (void)geocodeBtnClick
{
// 0.獲取用戶輸入的位置
NSString *addressStr = self.addressField.text;
if (addressStr == nil || addressStr.length == 0) {
NSLog(@"請輸入地址");
return;
}
// 1.創(chuàng)建地理編碼對象
// 2.利用地理編碼對象編碼
// 根據(jù)傳入的地址獲取該地址對應的經(jīng)緯度信息
[self.geocoder geocodeAddressString:addressStr completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count == 0 || error != nil) {
return ;
}
// placemarks地標數(shù)組, 地標數(shù)組中存放著地標, 每一個地標包含了該位置的經(jīng)緯度以及城市/區(qū)域/國家代碼/郵編等等...
// 獲取數(shù)組中的第一個地標
CLPlacemark *placemark = [placemarks firstObject];
self.latitudeLabel.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude];
self.longitudeLabel.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude];
NSArray *address = placemark.addressDictionary[@"FormattedAddressLines"];
NSMutableString *strM = [NSMutableString string];
for (NSString *str in address) {
[strM appendString:str];
}
self.detailAddressLabel.text = strM;
}];
}
#pragma mark - 懶加載, 1.創(chuàng)建地理編碼對象
- (CLGeocoder *)geocoder
{
if (!_geocoder) {
_geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}
效果圖如下: