取得使用者位置只是第一步,要在界面上顯示「台北市大安區某路」這種人類看得懂的地址,還需要一層反向地理編碼。本文整理完整的實作流程與兩種可用的解析途徑。
先判斷裝置是否允許定位服務,再建立 CLLocationManager:
if ([CLLocationManager locationServicesEnabled]) {
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; // 精度設為最佳
locationManager.distanceFilter = 1000.0f; // 距離篩選器
[locationManager startUpdatingLocation];
}
兩個參數值得說明。desiredAccuracy 設為 kCLLocationAccuracyBest 精度最高,但耗電也最兇;若只需要判斷使用者在哪個城市,設成 kCLLocationAccuracyThreeKilometers 之類的較粗粒度會省很多電。distanceFilter 則是「移動超過幾公尺才再次回報」,設 1000 代表每移動一公里才更新一次,靜止不動時幾乎不會觸發回呼。
#pragma mark - CLLocationManager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
location = [newLocation coordinate];
lat = location.latitude;
lon = location.longitude;
MKCoordinateSpan theSpan;
theSpan.latitudeDelta = 0.01f;
theSpan.longitudeDelta = 0.01f;
theRegion.center = location; // 定義地圖顯示範圍
theRegion.span = theSpan;
}
span 的 delta 值代表顯示範圍的跨度,數值越小地圖放得越大。0.01 度大約是 1 公里出頭的量級,適合展示周邊店家;若要顯示整個城市,可以放大到 0.5 以上。
// 根據經緯度反向解析成位置
CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark, NSError *error) {
CLPlacemark *mark = [placemark objectAtIndex:0];
place.title = @"沒有當前位置的詳細信息";
place.subTitle = @"詳細信息請點擊'附近'查看";
place.title = [NSString stringWithFormat:@"%@%@%@",
mark.subLocality, mark.thoroughfare, mark.subThoroughfare];
place.subTitle = [NSString stringWithFormat:@"%@", mark.name];
[self.myMapView selectAnnotation:place animated:YES];
}];
CLPlacemark 提供的欄位中,thoroughfare 是街路名、subThoroughfare 是門牌號、subLocality 是行政區、locality 是城市、name 則是場所名稱。
這裡有兩個要留意的問題。第一,placemark 陣列可能為空,直接取 objectAtIndex:0 會越界崩潰,實務上必須先檢查 count 與 error。第二,範例先把 title 設為「沒有詳細資訊」再立刻覆寫,這個寫法只有在後續格式化成功時才合理,若 mark 各欄位皆為 nil,畫面上就會出現一片空白而非提示文字——正確做法應該是在 if 分支裡才覆寫。
https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true
把 latlng 換成實際座標即可,回傳 JSON 格式,解析後取得 formatted_address。
系統 CLGeocoder 的缺點是部分地區解析不出結果,尤其是地址資料不完整的區域,容易拿到空陣列。Google API 的缺點則是中國大陸地區常常連不上,網路環境受限時請求會 timeout。
兩者都有明顯的適用範圍限制,因此實務上常見的處理策略是「以系統 API 為主,失敗時降級到其他來源」,並在 UI 上預留「無法取得詳細地址」的狀態,而不是讓使用者看到空白。
若主要市場在中國,可以考慮高德或百度地圖 SDK,這類服務在本土地理資料覆蓋率與存取穩定性上都更有優勢,值得後續評估。
網路上流傳較廣的「找附近」功能,多數是基於 Google Places API:
#define SEARCH_GOOGLE @"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=1000&types=%@&sensor=true&key=YOUR_API_KEY"
jsonString = [NSString stringWithFormat:SEARCH_GOOGLE,
location.coordinate.latitude,
location.coordinate.longitude, @"food"];
jsonString = [NSString stringWithFormat:SEARCH_GOOGLE,
location.coordinate.latitude,
location.coordinate.longitude, @"bus_station"];
jsonString = [NSString stringWithFormat:SEARCH_GOOGLE,
location.coordinate.latitude,
location.coordinate.longitude, @"hospital"];
types 支援的種類很多,餐飲、交通站、醫院、銀行、加油站等都有對應值。提醒:請不要把 API key 寫在前端或客戶端程式碼中,建議改由自己的伺服器代為轉發請求,並在伺服器端控管配額與來源。
讓使用者長按地圖任意位置並對該處做反向解析:
// 只在 gesture 開始時處理,否則會執行兩次
if (sender.state == UIGestureRecognizerStateBegan) {
CGPoint touchPoint = [sender locationInView:self.myMapView];
// 將觸控點轉換為經緯度
CLLocationCoordinate2D touchCoordinate =
[self.myMapView convertPoint:touchPoint toCoordinateFromView:self.myMapView];
location = [[CLLocation alloc] initWithLatitude:touchCoordinate.latitude
longitude:touchCoordinate.longitude];
// 後續可對 location 做反向地理編碼
}
UIGestureRecognizerStateBegan 的判斷是關鍵:手勢的生命週期會經歷 Began、Changed、Ended 等多個階段,若不過濾,長按過程中會連續觸發多次網路請求,既浪費配額又可能造成畫面閃動。
最後補充一個實務上常被忽略的環節:iOS 的定位權限需要 App 主動請求,且使用者可以隨時在設定中撤銷。呼叫 startUpdatingLocation 之前應先呼叫 requestWhenInUseAuthorization,並在 Info.plist 中設定 NSLocationWhenInUseUsageDescription 說明用途——缺少這段說明文字,App 會在請求權限時直接崩潰。此外,didUpdateToLocation:fromLocation: 這個 delegate 在後續 iOS 版本中已被 didUpdateLocations: 取代,新專案建議採用後者。