您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS GPS 定位入門:使用 CoreLocation 取得當前座標

編輯:iOS 開發綜合

在 iOS 中取得裝置位置,最常見的方式是使用 CoreLocation Framework。透過 CLLocationManager,可以取得經緯度、精度、高度等資訊,也能計算兩個座標之間的距離。

引入 CoreLocation

首先要把 CoreLocation.framework 加入專案,並在程式碼中引入:

#import <CoreLocation/CoreLocation.h>

若要接收定位更新,ViewController 需要遵循 CLLocationManagerDelegate。

建立定位管理器

@interface GPSViewController : UIViewController <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

啟動定位

- (void)viewDidLoad {
    [super viewDidLoad];

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.delegate = self;

    [self.locationManager startUpdatingLocation];
}

locationManager 建議保存為類別屬性,不要只用區域變數,否則可能因物件被釋放而無法收到後續回呼。

接收位置更新

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    CLLocationCoordinate2D coordinate = newLocation.coordinate;

    NSLog(@"緯度: %f, 經度: %f", coordinate.latitude, coordinate.longitude);

    [self.locationManager stopUpdatingLocation];

    CLLocationDistance distance = [newLocation distanceFromLocation:oldLocation];
    NSLog(@"距離: %f", distance);
}

若只需要取得一次位置,可以在收到座標後呼叫 stopUpdatingLocation。若需要持續追蹤,則可保留更新狀態,並依需求調整 desiredAccuracy 以平衡精度與耗電。

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