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

iOS 依地址取得經緯度:CLGeocoder 正向地理編碼

編輯:iOS 相關資訊

把使用者輸入的地址轉換成經緯度座標,在 iOS 上透過 Core Location 的 CLGeocoder 就能完成,這個過程稱為正向地理編碼(forward geocoding)。

程式碼

CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
[myGeocoder geocodeAddressString:_searchBar.text completionHandler:^(NSArray *placemarks, NSError *error) {
    if ([placemarks count] > 0 && error == nil) {
        CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
        NSLog(@"%f", firstPlacemark.location.coordinate.latitude);
        NSLog(@"%f", firstPlacemark.location.coordinate.longitude);
    }
    else if ([placemarks count] == 0 && error == nil) {
        NSLog(@"找不到對應的地標。");
    }
    else if (error != nil) {
        NSLog(@"發生錯誤 = %@", error);
    }
}];

重點說明

  • 三種結果都要處理。completionHandler 共有三種結局:查到結果、查不到結果(placemarks 為空但無錯誤)、以及發生錯誤。只處理第一種是最常見的疏漏,會讓使用者完全得不到任何回饋。
  • 取第一筆即可。geocodeAddressString: 可能回傳多筆候選,一般取 placemarks 的第 0 個物件;若要更精確,可改用 geocodeAddressString:region:completionHandler: 限定國家或區域範圍。
  • 座標在 CLPlacemark 裡。經緯度取自 placemark.location.coordinate,而 placemark 本身還帶有 thoroughfare、locality、administrativeArea、country、postalCode 等結構化欄位,可以反過來組出完整地址。
  • 注意執行緒。handler 在背景執行緒呼叫,若要更新 UI,請回到主執行緒。
  • 有速率限制。Apple 的地理編碼服務不保證免費無限使用,不應把 CLGeocoder 當成大量批次轉換的工具;大量需求請改用自有後端或第三方服務。

反方向:由座標求地址

如果手上已經有經緯度,想反查地址,改用 CLLocation 建立物件後呼叫 reverseGeocodeLocation:completionHandler: 即可,回傳的同樣是 CLPlacemark 陣列,欄位用法完全一致。

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