http://magicalboy.com/ios_gps_location/
在 iOS 平台上使用 CLLocationManager 獲取 GPS 位置信息,比如經度,緯度,海拔高度等是很簡單的事情。
步驟
- 加入 CoreLocation.framework , 導入頭文件。
#import <CoreLocation/CoreLocation.h>
- 在 AppDelegate.m 中加入檢測是否啟用位置服務功能。
CLLocationManager * manager = [[ CLLocationManager alloc ] init ];if ( manager . locationServicesEnabled == NO ) {UIAlertView * servicesDisabledAlert = [[ UIAlertView alloc ] initWithTitle: @"Location Services Disabled" message: @"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled." delegate: nil cancelButtonTitle: @"OK" otherButtonTitles: nil ];[ servicesDisabledAlert show ];[ servicesDisabledAlert release ];}
- 打開位置管理器。
- ( IBAction ) openGPS: ( id ) sender {if ( locationManager == nil ) {locationManager = [[ CLLocationManager alloc ] init ];locationManager . delegate = self ;locationManager . desiredAccuracy = kCLLocationAccuracyBest ; // 越精確,越耗電!}[ locationManager startUpdatingLocation ]; // 開始定位} - 在 CLLocationManagerDelegate 中獲取 GPS 位置信息。
#pragma mark - CLLocationManagerDelegate- ( void ) locationManager: ( CLLocationManager * ) manager didFailWithError: ( NSError * ) error {switch ( error . code ) {case kCLErrorLocationUnknown:NSLog ( @"The location manager was unable to obtain a location value right now." );break ;case kCLErrorDenied:NSLog ( @"Access to the location service was denied by the user." );break ;case kCLErrorNetwork:NSLog ( @"The network was unavailable or a network error occurred." );break ;default :NSLog ( @"未定義錯誤" );break ;}}- ( void ) locationManager: ( CLLocationManager * ) manager didUpdateToLocation: ( CLLocation * ) newLocation fromLocation: ( CLLocation * ) oldLocation{NSLog ( @"oldLocation.coordinate.timestamp:%@" , oldLocation . timestamp );NSLog ( @"oldLocation.coordinate.longitude:%f" , oldLocation . coordinate . longitude );NSLog ( @"oldLocation.coordinate.latitude:%f" , oldLocation . coordinate . latitude );NSLog ( @"newLocation.coordinate.timestamp:%@" , newLocation . timestamp );NSLog ( @"newLocation.coordinate.longitude:%f" , newLocation . coordinate . longitude );NSLog ( @"newLocation.coordinate.latitude:%f" , newLocation . coordinate . latitude );NSTimeInterval interval = [ newLocation . timestamp timeIntervalSinceDate: oldLocation . timestamp ];NSLog ( @"%lf" , interval );// 取到精確GPS位置后停止更新if ( interval < 3 ) {// 停止更新[ locationManager stopUpdatingLocation ];}latitudeLabel . text = [ NSString stringWithFormat: @"%f" , newLocation . coordinate . latitude ];longitudeLabel . text = [ NSString stringWithFormat: @"%f" , newLocation . coordinate . longitude ];}