天天看點

CLLocationManagerpragma mark - CoreLocation 代理pragma mark 跟蹤定位代理方法,每次位置發生變化即會執行(隻要定位到相應位置)

Core Location是iPhone、iPad等開發定位服務應用程式的架構。我們要在Xcode中添加“CoreLocation.framework”存在的架構。

定位時候主要使用CLLocationManager、 CLLocationManagerDelegate和CLLocation。

CLLocationManager是定位服務管理類,它能夠給我們提供獲得裝置的位置資訊和高度資訊,也可以監控裝置進入或離開某個區域,它還可以幫助獲得裝置的運作方向等。

CLLocationManagerDelegate 是CLLocationManager類委托協定。

CLLocation類是封裝了位置和高度資訊。

實作:

<1>聲明對象

@interface ViewController ()

{

CLLocationManager *_locationManager;

}

//經度

@property (weak, nonatomic) IBOutlet UITextField *txtLng;

//緯度

@property (weak, nonatomic) IBOutlet UITextField *txtLat;

//高度

@property (weak, nonatomic) IBOutlet UITextField *txtAlt;

<2>對象初始化

_locationManager=[[CLLocationManager alloc]init];

<3>詢問使用者是否啟用定位服務

if (![CLLocationManager locationServicesEnabled])

{

NSLog(@”定位服務目前可能尚未打開,請設定打開!”);

return;

}

<4>設定代理

@interface ViewController ()

_locationManager.delegate = self;

<5>設定定位的其他

//設定定位精度 kCLLocationAccuracyBest為最精确定位

_locationManager.desiredAccuracy = kCLLocationAccuracyBest;

//設定定位頻率,每隔多少米定位一次

_locationManager.distanceFilter = 10.0f;

<6>啟動跟蹤定位

[_locationManager startUpdatingLocation];

<7>

pragma mark - CoreLocation 代理

pragma mark 跟蹤定位代理方法,每次位置發生變化即會執行(隻要定位到相應位置)

  • (void)locationManager:(CLLocationManager *)manager

    didUpdateLocations:(NSArray *)locations

    {

    CLLocation *currLocation=[locations lastObject];//取出目前位置

    self.txtLat.text = [NSString stringWithFormat:@”%3.5f”,

    currLocation.coordinate.latitude];

    self.txtLng.text = [NSString stringWithFormat:@”%3.5f”,

    currLocation.coordinate.longitude];

    self.txtAlt.text = [NSString stringWithFormat:@”%3.5f”,

    currLocation.altitude];

    //如果不需要實時定位,使用完即使關閉定位服務

    [_locationManager stopUpdatingLocation];

    }

    %3.5f是輸出整數部分是3位,小數部分是5位的浮點數。

    在locationManager:didUpdateLocations:方法中參數locations是位置變化的集合,它按照時間變化的順序存放。如果想獲得目前裝置的位置,可以使用第①行的[locations lastObject]語句獲得集合中最後一個 元素,它就是裝置目前位置了。

    從集合中傳回的對象類型是CLLocation,CLLocation封裝了位置、高度等資訊。在上面代碼中我們使用了它的 兩個屬性:altitude和coordinate,altitude屬性是高度值,coordinate是封裝了經度和緯度的結構體 CLLocationCoordinate2D