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

iOS 中實現地理位置定位的常見方法解析

編輯:iOS 相關教學

iOS 系統自帶的定位服務已經能滿足絕大多數需求,例如取得當前經緯度、把座標反查成詳細地址、計算兩地之間的距離等等。

系統的定位共有三種來源:

  1. GPS:精度最高的一種。
  2. 蜂窩基站三角定位:在基站密集的城市環境中相當準確。
  3. Wi-Fi:依賴網路資料庫比對,是三種方式中最不精確的。

使用前,需要在 Xcode 專案中連結 MapKit 與 CoreLocation 兩個函式庫:

Core Location 負責定位,能取得裝置的當前座標與移動資訊,其中最重要的類別是 CLLocationManager(定位管理器)。從 iOS 8 開始,這個框架有幾項值得注意的變化:

  • 在授權狀態中引入 Always 與 WhenInUse 的概念,使用者可以選擇「僅使用 App 時定位」。
  • 加入 Visit Monitoring 特性,特別適合旅行類應用:當使用者抵達某個指定區域時才開始作用。
  • 加入室內定位技術與 CLFloor,在室內還能取得樓層資訊。

一、取得當前經緯度

先導入標頭並宣告定位管理器,同時實現 CLLocationManagerDelegate:

#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager;
}
@end

開始定位:

- (void)startLocating {
    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc] init];
        // 設定定位精度
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        // 移動超過 100 公尺才更新一次
        _locationManager.distanceFilter = 100.0f;
        _locationManager.delegate = self;

        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 的 reverseGeocodeLocation: 就能把座標轉成國家、城市、行政區、街道等資訊:

- (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 *test = [placemark addressDictionary];
            // Country 國家、State 城市、SubLocality 行政區、Street 街道
            NSLog(@"%@", [test objectForKey:@"Country"]);
            NSLog(@"%@", [test objectForKey:@"State"]);
            NSLog(@"%@", [test objectForKey:@"SubLocality"]);
            NSLog(@"%@", [test objectForKey:@"Street"]);
        }
    }];
}

三、由地名取得經緯度(地理編碼)

- (void)getLongitudeAndLatitudeWithCity:(NSString *)city {
    // city 可以是中文
    NSString *address = city;
    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
    [myGeocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0 && error == nil) {
            NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
            NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
            NSLog(@"Latitude  = %f", firstPlacemark.location.coordinate.latitude);
        } else if ([placemarks count] == 0 && error == nil) {
            NSLog(@"Found no placemarks.");
        } else if (error != nil) {
            NSLog(@"An error occurred = %@", error);
        }
    }];
}

四、計算兩地之間的距離

- (double)distanceByLongitude:(double)longitude1
                     latitude:(double)latitude1
                    longitude:(double)longitude2
                     latitude:(double)latitude2 {
    CLLocation *curLocation   = [[CLLocation alloc] initWithLatitude:latitude1 longitude:longitude1];
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:latitude2 longitude:longitude2];
    double distance = [curLocation distanceFromLocation:otherLocation];   // 單位為公尺
    return distance;
}

先用上面的地理編碼取得兩地的座標,再代入計算。以北京(116.405285, 39.904989)與上海(121.472644, 31.231706)為例:

double distance = [self distanceByLongitude:116.405285
                                   latitude:39.904989
                                  longitude:121.472644
                                   latitude:31.231706];
NSLog(@"Distance = %f", distance);

輸出結果約為:

distance = 1066449.749194

也就是一千零六十六公里左右。需要注意的是,這是基於球面座標的直線距離估算,並非實際的陸路里程,用於「距離最近的門店」這類場景綽綽有餘,但不能當作導航里程使用。

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