iOS 自帶的定位服務能滿足相當多需求。本文整理四個實務上最常用的小功能:取得經緯度、取得詳細地址、由地名反查座標、以及計算兩地距離。
先引入 <CoreLocation/CoreLocation.h>,宣告 CLLocationManager 並遵循 CLLocationManagerDelegate。
@interface ViewController () <CLLocationManagerDelegate> {
CLLocationManager *_locationManager;
}
@end
開始定位:
- (void)startLocating {
if ([CLLocationManager locationServicesEnabled]) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 定位精度
_locationManager.distanceFilter = 100.0f; // 移動 100 公尺才回報
_locationManager.delegate = self;
// iOS 8 之後需主動請求授權
if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0) {
[_locationManager requestAlwaysAuthorization];
[_locationManager requestWhenInUseAuthorization];
}
[_locationManager startUpdatingLocation];
}
}
取得座標後記得停止定位:
- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
NSLog(@"Longitude = %f", manager.location.coordinate.longitude);
NSLog(@"Latitude = %f", manager.location.coordinate.latitude);
[_locationManager stopUpdatingLocation];
}
用 CLGeocoder 做反向地理編碼:
- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
NSLog(@"Longitude = %f", manager.location.coordinate.longitude);
NSLog(@"Latitude = %f", manager.location.coordinate.latitude);
[_locationManager stopUpdatingLocation];
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:manager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
NSDictionary *info = [placemark addressDictionary];
NSLog(@"國家:%@", [info objectForKey:@"Country"]);
NSLog(@"城市:%@", [info objectForKey:@"State"]);
NSLog(@"區域:%@", [info objectForKey:@"SubLocality"]);
NSLog(@"街道:%@", [info objectForKey:@"Street"]);
}
}];
}
這樣就能拿到國家、城市、行政區、街道等完整資訊。
- (void)getLongitudeAndLatitudeWithCity:(NSString *)city {
// city 可以是中文地名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:city completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count > 0 && error == nil) {
CLPlacemark *first = [placemarks objectAtIndex:0];
NSLog(@"Longitude = %f", first.location.coordinate.longitude);
NSLog(@"Latitude = %f", first.location.coordinate.latitude);
} else if (placemarks.count == 0 && error == nil) {
NSLog(@"查無此地點");
} else if (error != nil) {
NSLog(@"發生錯誤:%@", error);
}
}];
}
CLLocation 本身就提供了 distanceFromLocation:,不必自己推公式:
- (double)distanceByLongitude:(double)longitude1
latitude:(double)latitude1
longitude:(double)longitude2
latitude:(double)latitude2 {
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:latitude1
longitude:longitude1];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:latitude2
longitude:longitude2];
return [loc1 distanceFromLocation:loc2]; // 單位為公尺
}
用上面的方法取得北京(116.405285, 39.904989)與上海(121.472644, 31.231706)的座標後:
double distance = [self distanceByLongitude:116.405285
latitude:39.904989
longitude:121.472644
latitude:31.231706];
NSLog(@"距離 = %f 公尺", distance);
// 輸出:1066449.749194
關於精度:distanceFromLocation: 回傳的是基於球面模型的直線距離(great circle distance),並非道路行駛距離。若需要「開車要多久」,得另外串接地圖 SDK 的路徑規劃服務。
關於授權:requestAlwaysAuthorization 與 requestWhenInUseAuthorization 是兩種不同授權,不該同時呼叫。多數場景只需要 When In Use,且必須在 Info.plist 對應位置加上說明字串,否則程式會直接崩潰。
關於定位精度與耗電的權衡:desiredAccuracy 設為 Best 最耗電;若只需判斷使用者在哪個城市,設為 kCLLocationAccuracyThreeKilometers 綽綽有餘。
關於地理編碼的速率限制:CLGeocoder 有呼叫頻率上限,且需要網路連線。大量批次轉換時務必節流,並快取結果。
完整範例專案可參考:https://github.com/worldligang/MapDistanceMaster.git