CLLocationManager 获取 GPS 位置信息
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];}

浙公网安备 33010602011771号