|
学了iPhone的CoreLocation之后,再回想Android的定位开发,真是省事了不少,iPhone对定位功能开发这一模块封装的很好,只需几步,便可以获取到设备所在的位置等多项参数!
1.启动XCode4.3.2,单击菜单项File->New->Project...,以Sigle View Application模板新建项目,并命名为WhereAmI:
2.单击ViewControler.h头文件,因为CoreLocation框架并不属于UIKit框架,所以需要另外引入,并添加协议:
[plain]
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *startPoint;
UILabel *latLabel;
UILabel *lonLabel;
UILabel *distance;
}
@property(retain,nonatomic)CLLocationManager *locationManager;
@property(retain,nonatomic)CLLocation *startPoint;
@property(retain,nonatomic)IBOutlet UILabel *latLabel;
@property(retain,nonatomic)IBOutlet UILabel *lonLabel;
@property(retain,nonatomic)IBOutlet UILabel *distance;
@end
3.单击ViewControler.m文件,添加以下代码:
[plain]
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize startPoint;
@synthesize locationManager;
@synthesize latLabel;
@synthesize lonLabel;
@synthesize distance;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark CLLocationManagerDelegate Methods
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if(startPoint==nil)
startPoint = newLocation;
//经度
NSString *lon = [[NSString alloc]initWithFormat:@"%g",newLocation.coordinate.longitude];
self.lonLabel.text = lon;
[lon release];
//纬度
NSString *lat = [[NSString alloc]initWithFormat:@"%g",newLocation.coordinate.latitude];
self.latLabel.text = lat;
[lat release];
//计算移动距离
CLLocationDistance ld = [newLocation distanceFromLocation:startPoint];
NSString *distanceString = [[NSString alloc]initWithFormat:@"%gm",ld];
self.distance.text = distanceString;
[distanceString release];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSString *errorType = (error.code == kCLErrorDenied)?@"Access Denied":@"Unkown Error";
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error getting location" message:errorType delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
@end
4.运行,效果如下:
作者:js_dada |
|