想用你的iPhone 显示你现在的位置吗?现在就看看小编为大家整理的iOS中进行卫星定位的实例编程吧!
纲要:
- 在程序显示前运行代码 -
- 加入CoreLocation Frameworks -
- 关于iPhone的“Utility Application” 运用 -
- CLLocationManager 代码运用 -
首先运行以安装好的 xCode
选择: File->New Project.
从 "New Project" 窗口
选择 : iPhone OS ->Applications-> Utility Application
命名 : 我这里命名为 “WhereAmI”
(1) 在Project文件上右键点击 Linked Frameworks and Libraries->"+"->Existing Framework;在Frameworks文件夹下选择 CoreLocation.framework, 按Add
#FormatImgID_0#
(2) 在xCode打开 MainView.h 文件,加入下面代码
#import
#import
#import
@interface MainView : UIView {
IBOutlet UITextField *altitude;
IBOutlet UITextField *latitude;
IBOutlet UITextField *longitude;
CLLocationManager *locmanager;
BOOL wasFound;
}
- (IBAction)update;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *) oldLocation ;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *) error;
@end
(3) 在xCode打开 MainView.m 文件,加入下面代码
#import "MainView.h"
@implementation MainView
- (IBAction)update {
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
[locmanager startUpdatingLocation];
}
CLLocationManager* locmanager;
-(void)awakeFromNib {
[self update];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (wasFound) return;
wasFound = YES;
CLLocationCoordinate2D loc = [newLocation coordinate];
latitude.text = [NSString stringWithFormat: @"%f", loc.latitude];
longitude.text = [NSString stringWithFormat: @"%f", loc.longitude];
altitude.text = [NSString stringWithFormat: @"%f", newLocation.altitude];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
}
- (void)dealloc {
[super dealloc];
}
(4) UIView 界面设置
双击文件: "main.xib" ;
然后 "Interface Builder" 会自动打开,在这里我们可以编辑改变界面
(5) 加入Label 在 Attributes 下, Text 内填上"经度"
(6) 加入 Text Field ; 显示:经度
选择: Tools -> Library ; 从Library显示菜单中拖拉一个 Text Field 到 Main View
在主视窗口或文件窗口;点击 Text Field
选择: Tools -> Connection Inspector
移动鼠标在"Referencing Outlets" 后面圆圈上; 圆圈变为(+); 拖向直线连接到"Main View";
放开鼠标选择键出现 "longitude"; 选上它。