要拿到使用者目前的位置,最直接的途徑是 CoreLocation。它和地圖元件內建的定位回呼是兩回事——這裡說的是完全自己掌控的定位流程,包含權限檢查、開始定位、座標回報與錯誤處理。
一、專案設定中導入 CoreLocation.framework。
二、引入標頭檔:
#import <CoreLocation/CoreLocation.h>
三、讓類別遵循代理協定 <CLLocationManagerDelegate>。
另外別忘了在 Info.plist 中補上 NSLocationWhenInUseUsageDescription(或 Always 版本)的說明文字,否則 App 會在請求權限時直接崩潰。
CLLocationManager *locationManager; // 宣告 manager
// 先確認定位服務是否被允許
if ([CLLocationManager locationServicesEnabled]) {
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
// iOS 8 之後若要主動詢問權限,還需呼叫 requestWhenInUseAuthorization
} else {
// 提示使用者無法進行定位操作
}
// 開始定位
[locationManager startUpdatingLocation];
把 locationServicesEnabled 的檢查放在最前面很重要,它能過濾掉「使用者關閉了全域定位服務」與「App 未被授權」兩種情況,避免後續拿到一堆錯誤。
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
// latitude 與 longitude 皆為 NSString 型別變數
self.latitude = [NSString stringWithFormat:@"%.4f", newLocation.coordinate.latitude]; // 緯度
self.longitude = [NSString stringWithFormat:@"%.4f", newLocation.coordinate.longitude]; // 經度
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// locations 保存了持續更新的座標序列,取最後一筆即為最新位置
// 若不想持續追蹤,可在取到值之後呼叫 stopUpdatingLocation
CLLocation *currentLocation = [locations lastObject];
CLLocationCoordinate2D coor = currentLocation.coordinate;
self.latitude = coor.latitude;
self.longitude = coor.longitude;
// [self.locationManager stopUpdatingLocation];
}
取 lastObject 是這裡的重點。這個方法會回傳一個「座標歷史陣列」,最後一筆才是當前位置,直接取 [locations firstObject] 會拿到最早的那筆,是很常見的誤用。
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if (error.code == kCLErrorDenied) {
// 使用者拒絕定位。
// 按住 Option 點擊 KCLErrorDenied 可查看詳細說明,或印出 error.code 對照錯誤碼表
}
}
精度與電量的取捨。desiredAccuracy 設為 kCLLocationAccuracyBest 精度最高但也最耗電;若只是要判斷使用者在哪個城市,設 kCLLocationAccuracyThreeKilometers 就夠了。
用完要關。如果只需要一次定位,拿到座標後立刻呼叫 stopUpdatingLocation,否則會持續喚醒 GPS,使用者很快就會發現 App 燙手又耗電。
座標是 WGS-84。CoreLocation 回傳的是 GPS 原始座標系,若要疊在國內地圖(GCJ-02)上顯示,需要做一次座標轉換,否則會有明顯偏移。
以上就是本文的全部內容,希望對大家的學習有所幫助。