#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController<CLLocationManagerDelegate>  {      CLLocationManager *locManager;  }
 @property (retain, nonatomic) IBOutletUILabel *lonLabel;  @property (retain, nonatomic) IBOutletUILabel *latLabel;  @property (retain, nonatomic) CLLocationManager *locManager;
@end
 

 
#import "ViewController.h"
@interfaceViewController ()
@end
@implementation ViewController @synthesize lonLabel; @synthesize latLabel; @synthesize locManager;
- (void)viewDidLoad {     [superviewDidLoad];          //初始化位置管理器     locManager = [[CLLocationManager alloc]init];     //设置代理     locManager.delegate = self;     //设置位置经度     locManager.desiredAccuracy = kCLLocationAccuracyBest;     //设置每隔100米更新位置     locManager.distanceFilter = 100;     //开始定位服务     [locManagerstartUpdatingLocation]; }
- (void)viewDidUnload {     [selfsetLonLabel:nil];     [selfsetLatLabel:nil];     [superviewDidUnload];     // Release any retained subviews of the main view. }
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); }
- (void)dealloc {     //停止定位服务     [locManagerstopUpdatingLocation];     [lonLabelrelease];     [latLabelrelease];     [superdealloc]; }
//协议中的方法,作用是每当位置发生更新时会调用的委托方法 -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {     //结构体,存储位置坐标     CLLocationCoordinate2D loc = [newLocation coordinate];     float longitude = loc.longitude;     float latitude = loc.latitude;     self.lonLabel.text = [NSStringstringWithFormat:@"%f",longitude];     self.latLabel.text = [NSStringstringWithFormat:@"%f",latitude];      }
//当位置获取或更新失败会调用的方法 -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {     NSString *errorMsg = nil;     if ([error code] == kCLErrorDenied) {         errorMsg = @"访问被拒绝";     }     if ([error code] == kCLErrorLocationUnknown) {         errorMsg = @"获取位置信息失败";     }          UIAlertView *alertView = [[UIAlertViewalloc]initWithTitle:@"Location"                                                     message:errorMsg delegate:self cancelButtonTitle:@"Ok"otherButtonTitles:nil, nil];     [alertView show];     [alertView release]; }
@end
