您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS CoreLocation 實戰:地理編碼與反地理編碼

編輯:iOS 相關資訊

一、CLGeocoder 是什麼

CLGeocoder 是 CoreLocation 提供的地理編碼器,Geo 取自 Geography。它負責在「地名」與「座標」之間雙向轉換:

  • 地理編碼(Geocode):給定一段地址文字,換算出經緯度與標準化的完整地址。
  • 反地理編碼(Reverse Geocode):給定一組經緯度,查出對應的地名資訊。

兩個核心方法:

- (void)geocodeAddressString:(NSString *)addressString
           completionHandler:(CLGeocodeCompletionHandler)completionHandler;

- (void)reverseGeocodeLocation:(CLLocation *)location
             completionHandler:(CLGeocodeCompletionHandler)completionHandler;

二、理解回呼與結果物件

無論成功或失敗,操作結束後都會觸發 CLGeocodeCompletionHandler 這個 block,它帶回兩個參數:

  • error:出錯時有值,例如查不到對應資訊、網路不可用。
  • placemarks:一個陣列,裡頭裝著 CLPlacemark 物件。

CLPlacemark 字面意思是「地標」,封裝了完整的地址資訊,常用屬性包括:

@property (nonatomic, readonly) CLLocation   *location;         // 地理座標
@property (nonatomic, readonly) CLRegion     *region;           // 行政區域
@property (nonatomic, readonly) NSDictionary *addressDictionary; // 完整地址字典
@property (nonatomic, readonly) NSString     *name;             // 地址名稱
@property (nonatomic, readonly) NSString     *locality;         // 城市
@property (nonatomic, readonly) NSString     *country;          // 國家
@property (nonatomic, readonly) NSString     *postalCode;       // 郵遞區號

三、地理編碼:地名 → 座標

#import <CoreLocation/CoreLocation.h>

@interface YYViewController ()
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (weak, nonatomic) IBOutlet UITextField *addressField;
@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailAddressLabel;
@end

@implementation YYViewController

// 懶載入:用到時才建立
- (CLGeocoder *)geocoder
{
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (IBAction)geocode
{
    NSString *address = self.addressField.text;
    if (address.length == 0) return;

    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {

        // 有錯誤或查無結果,都視為找不到
        if (error || placemarks.count == 0) {
            self.detailAddressLabel.text = @"你輸入的地址沒找到,可能在月球上";
            return;
        }

        // 逐一檢視所有候選地標
        for (CLPlacemark *pm in placemarks) {
            NSLog(@"name=%@ locality=%@ country=%@ postalCode=%@",
                  pm.name, pm.locality, pm.country, pm.postalCode);
        }

        // 取第一筆顯示
        CLPlacemark *first = [placemarks firstObject];
        self.detailAddressLabel.text = first.name;

        CLLocationDegrees latitude  = first.location.coordinate.latitude;
        CLLocationDegrees longitude = first.location.coordinate.longitude;
        self.latitudeLabel.text  = [NSString stringWithFormat:@"%.2f", latitude];
        self.longitudeLabel.text = [NSString stringWithFormat:@"%.2f", longitude];
    }];
}
@end

四、反地理編碼:座標 → 地名

- (IBAction)reverseGeocode
{
    NSString *longitudeText = self.longitudeField.text;
    NSString *latitudeText  = self.latitudeField.text;
    if (longitudeText.length == 0 || latitudeText.length == 0) return;

    CLLocationDegrees latitude  = [latitudeText doubleValue];
    CLLocationDegrees longitude = [longitudeText doubleValue];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {

        if (error || placemarks.count == 0) {
            self.reverseDetailAddressLabel.text = @"你輸入的地址沒找到,可能在月球上";
            return;
        }

        CLPlacemark *first = [placemarks firstObject];
        self.reverseDetailAddressLabel.text = first.name;

        // 把系統解析後的座標回填到輸入框
        self.latitudeField.text  = [NSString stringWithFormat:@"%.2f", first.location.coordinate.latitude];
        self.longitudeField.text = [NSString stringWithFormat:@"%.2f", first.location.coordinate.longitude];
    }];
}

// 點擊空白處收起鍵盤
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

五、實務上必須注意的事

  • 回呼執行緒:block 不一定在主執行緒被呼叫,更新 UI 前請切回主線程。
  • 循環參考:block 中強引用 self,而 self 持有 geocoder,容易形成迴圈,必要時使用 weak 引用。
  • 網路依賴:CLGeocoder 需要連網,離線時會回傳錯誤,務必把 error 分支處理好。
  • 請求頻率:系統對編碼次數有節流限制,連續輸入就連續呼叫會被拒絕,實務上常加上 debounce 或手動觸發。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved