您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發實戰:用 Core Location 完成地理編碼與反地理編碼

編輯:iOS 開發綜合

一、定位與地圖,是行動 App 的基礎能力

智慧型手機普及之後,愈來愈多生活瑣事被搬進 App:臨時要去一個陌生地址、想找附近的餐廳或電影院、順路查最近的銀行與飯店。這些場景背後其實都繞著兩個問題打轉——「我現在在哪裡」以及「我要去哪裡」。

在 iOS 平台上想實現這類功能,通常得搭配兩個系統框架:

  • Map Kit:負責地圖的顯示、縮放、標註與覆蓋物繪製。
  • Core Location:負責取得裝置的地理座標,以及地名與座標之間的雙向轉換。

另外記兩個業界常用術語:LBS(Location Based Service,基於位置的服務)與 SoLoMo(Social、Local、Mobile 三者結合的產品思維)。

二、接入 Core Location 的兩個步驟

1. 匯入框架與主標頭檔

先在專案設定中把 CoreLocation.framework 加入依賴;Xcode 5 之後已不必手動勾選,編譯器會自動連結。接著在需要使用的地方引入主標頭檔:

#import <CoreLocation/CoreLocation.h>

2. 兩個值得記住的約定

Core Location 內所有型別的前綴都是 CL,看到 CLLocation、CLGeocoder、CLPlacemark 就能立刻認出同系列;而真正負責取得定位的是 CLLocationManager 物件。

三、經緯度常識速覽

經度以通過英國倫敦格林 CONDITIONS 天文台的本初子午線為零度:向東為東經(E),向西為西經(W),各 180°,合計 360°。

緯度以赤道為零度:向北為北緯(N),向南為南緯(S),各 90°,合計 180°。

實務上要注意:跨經緯度的度數越大(1° 約 111 公里),代表地圖涵蓋的範圍越廣,畫面上的地物看起來就越小。

我國的經緯度範圍大致為:緯度 N 3°51′ ~ N 53°33′,經度 E 73°33′ ~ E 135°05′。

四、在模擬器上偽造位置

撰寫與除錯階段不可能真的抱著裝置跑遍各地,Xcode 內建的模擬位置功能就能解決這個問題:執行時指定一組經緯度,App 收到的座標就會是該處。

五、CLGeocoder:地理編碼與反地理編碼

CLGeocoder 是 Core Location 提供的編碼器(Geo 取自 Geography)。它同時包辦兩件事:

  • 地理編碼:給定地名,換算出具體座標與完整地址資訊。
  • 反地理編碼:給定座標,還原出地名與地址描述。
- (void)geocodeAddressString:(NSString *)addressString
           completionHandler:(CLGeocodeCompletionHandler)completionHandler;

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

兩個介面共用同一個 completion block(CLGeocodeCompletionHandler),無論成功或失敗都會被呼叫,並帶回兩個參數: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;         // 城市

六、完整程式碼示範

先用 storyboard 搭出介面:上方一組輸入框與標籤負責地理編碼,下方一組負責反地理編碼。

#import "YYViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface YYViewController ()

@property (nonatomic, strong) CLGeocoder *geocoder;

// 地理編碼
- (IBAction)geocode;
@property (weak, nonatomic) IBOutlet UITextField *addressField;
@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailAddressLabel;

// 反地理編碼
- (IBAction)reverseGeocode;
@property (weak, nonatomic) IBOutlet UITextField *longitudeField;
@property (weak, nonatomic) IBOutlet UITextField *latitudeField;
@property (weak, nonatomic) IBOutlet UILabel *reverdeDetailAddressLabel;

@end

@implementation YYViewController

#pragma mark - 懶載入
- (CLGeocoder *)geocoder {
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - 地理編碼:地名 -> 座標
- (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];
    }];
}

#pragma mark - 反地理編碼:座標 -> 地名
- (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.reverdeDetailAddressLabel.text = @"查無此地,你確定不是寫到月球去了?";
            return;
        }
        CLPlacemark *first = [placemarks firstObject];
        self.reverdeDetailAddressLabel.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];
}

@end

七、實作時容易踩到的細節

地理編碼(地名 → 座標)

主控台會把找到的所有地標欄位都印出來,方便確認解析結果。

反地理編碼(座標 → 地名)

鍵盤處理

經緯度欄位建議把鍵盤型別設為數字鍵盤,並在點擊空白處時呼叫 endEditing: 收合鍵盤。

最後一點常被忽略:在中國境內,Apple 的地圖與地理編碼服務由第三方供應商提供,因此查詢結果僅涵蓋境內範圍,邊界地帶的地址可能會有偏差。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved