地理編碼與反編碼

首先我們要了解地理編碼和反編碼的含義和作用:
<1>地理編碼:把地名轉換成位置信息
作用:把文字描述的 位置轉換成地圖上的經緯度;
<2>反編碼:把位置信息轉換成文字
作用:可以點擊地圖上的某個位置 來獲得文字的描述
<3>地理編解碼在編解碼的時候 是一個耗時的操作 可以采用異步操作

//編碼
- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;
//反編碼
- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;

*****注:在工程運行開始時,都必須要添加定位框架#import <CoreLocation/CoreLocation.h>
1、地理編碼:文字描述的位置 轉換成 地圖上的經緯度

CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder geocodeAddressString:@"鄭州" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placemark = placemarks.firstObject;
        CLLocation *loc = placemark.location;
        
        NSLog(@"緯度%f 經度%f",loc.coordinate.latitude,loc.coordinate.longitude);   
    }];

輸出結果:緯度34.707001 經度113.509167

#pragma mark 根據地名確定地理坐標
-(void)getCoordinateByAddress:(NSString *)address{ 
//地理編碼 
[_geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) { 
//取得第一個地標,地標中存儲了詳細的地址信息,注意:一個地名可能搜索出多個地址 
CLPlacemark *placemark=[placemarks firstObject]; CLLocation *location=placemark.location;//位置 CLRegion *region=placemark.region;//區域 NSDictionary *addressDic= placemark.addressDictionary;//詳細地址信息字典,包含以下部分信息 //
 NSString *name=placemark.name;//地名 // NSString *thoroughfare=placemark.thoroughfare;//街道 
// NSString *subThoroughfare=placemark.subThoroughfare; //街道相關信息,例如門牌等 
// NSString *locality=placemark.locality; // 城市
 // NSString *subLocality=placemark.subLocality; // 城市相關信息,例如標志性建筑 
// NSString *administrativeArea=placemark.administrativeArea; // 州 
// NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政區域信息 
// NSString *postalCode=placemark.postalCode; //郵編 
// NSString *ISOcountryCode=placemark.ISOcountryCode; //國家編碼 
// NSString *country=placemark.country; //國家 // NSString *inlandWater=placemark.inlandWater; //水源、湖泊 
// NSString *ocean=placemark.ocean; // 海洋 
// NSArray *areasOfInterest=placemark.areasOfInterest; //關聯的或利益相關的地標
 NSLog(@"位置:%@,區域:%@,詳細信息:%@",location,region,addressDic); }];
}
#pragma mark 根據坐標取得地名-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{ //反地理編碼 CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude]; 
[_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 
CLPlacemark *placemark=[placemarks firstObject]; NSLog(@"詳細信息:%@",placemark.addressDictionary); }];
}
@end

總結我們目前在地圖上接觸到的幾個類:

CLLocationManager:定位管理器,用來設置管理定位,設置定位的精度、定位頻率、后臺運行等。

CLGeocoder:主要用來編碼與反編碼。

CLLocation:用于表示位置信息,包含地理坐標、海拔等信息,包含在CoreLoaction框架中。

CLPlacemark:定位框架中地標類,封裝了詳細的地理信息。

CLLocationCoordinate2D:他是一個結構體,用來表示經緯度。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容