生活随笔
收集整理的這篇文章主要介紹了
基于CLGeocoder - 地理编码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
iOS中CoreLocatio框架中的CLGeocoder為我們提供了地理編碼方法:
首先需要導(dǎo)入框架
#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、當(dāng)編碼完成時,會調(diào)用?completionHandler對象,該對象類型為?CLGeocodeCompletionHandler,實際上是一個 block 對象
這個對象中傳遞了2個參數(shù),其中placemark:里面裝了CLPlacemark對象
根據(jù)文檔,可以知道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 - 地理編碼響應(yīng)
- (void)geocodeBtnClick
{// 0.獲取用戶輸入的位置NSString *addressStr = self.addressField.text;if (addressStr == nil || addressStr.length == 0) {NSLog(@"請輸入地址");return;}// 1.創(chuàng)建地理編碼對象// 2.利用地理編碼對象編碼// 根據(jù)傳入的地址獲取該地址對應(yīng)的經(jīng)緯度信息[self.geocoder geocodeAddressString:addressStr completionHandler:^(NSArray *placemarks, NSError *error) {if (placemarks.count == 0 || error != nil) {return ;}// placemarks地標(biāo)數(shù)組, 地標(biāo)數(shù)組中存放著地標(biāo), 每一個地標(biāo)包含了該位置的經(jīng)緯度以及城市/區(qū)域/國家代碼/郵編等等...// 獲取數(shù)組中的第一個地標(biāo)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;
}
效果圖如下:
轉(zhuǎn)載于:https://www.cnblogs.com/knightguang/p/9605822.html
總結(jié)
以上是生活随笔為你收集整理的基于CLGeocoder - 地理编码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。