iOS 原生地圖地理編碼與反地理編碼


 

  當我們要在App實現功能:輸入地名,編碼為經緯度,實現導航功能。

  那么,我需要用到原生地圖中的地理編碼功能,而在Core Location中主要包含了定位、地理編碼(包括反編碼)功能。

 

 

在文件中導入

 

#import <CoreLocation/CoreLocation.h>

 

地理編碼:

/**
 地理編碼
 */
- (void)geocoder {
    
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    
    NSString *addressStr = @"廣東省深圳市寶安區";//位置信息
    
    [geocoder geocodeAddressString:addressStr completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error!=nil || placemarks.count==0) {
            return ;
        }
        //創建placemark對象
        CLPlacemark *placemark=[placemarks firstObject];
        //經度
        NSString *longitude =[NSString stringWithFormat:@"%f",placemark.location.coordinate.longitude];
        //緯度
        NSString *latitude =[NSString stringWithFormat:@"%f",placemark.location.coordinate.latitude];
        
        NSLog(@"經度:%@,緯度:%@",longitude,latitude);
        
    }];
    
}

 

 

 

地理反編碼:

 

/**
 地理反編碼
 */
- (void)reverseGeocoder{
    //創建地理編碼對象
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    
    //經度
    NSString *longitude = @"113.23";
    //緯度
    NSString *latitude = @"23.16";
    
    
    //創建位置
    CLLocation *location=[[CLLocation alloc]initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
    
    
    //反地理編碼
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //判斷是否有錯誤或者placemarks是否為空
        if (error !=nil || placemarks.count==0) {
            NSLog(@"%@",error);
            return ;
        }
        for (CLPlacemark *placemark in placemarks) {
            //詳細地址
            NSString *addressStr = placemark.name;
            NSLog(@"詳細地址1:%@",addressStr);
            NSLog(@"詳細地址2:%@",placemark.addressDictionary);
            NSLog(@"詳細地址3:%@",placemark.locality);
        }
        
    }];
}

 


Demo:https://github.com/JnKindle/GeocoderAndReverseReocoder

 

/**

 *  Author:Jn

 *  GitHub:https://github.com/JnKindle

 *  cnblogs:http://www.cnblogs.com/JnKindle

 */


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM