我想获取当前位置,我看到这段代码,但是如何在点击按钮时分配这个纬度和经度标签?
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"latitudeAAAAA %f",newLocation.coordinate.latitude );
NSLog(@"longitudeAAAA %f",newLocation.coordinate.longitude);
[corelocation stopUpdatingLocation];
}
答案 0 :(得分:2)
label.text = [NSString stringWithFormat:@"%lf,%lf", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
答案 1 :(得分:1)
您需要将自己的类设置为CLLocationManager
的委托,然后调用startUpdatingLocation
(docs)以使其调用您提到的方法。在您要求它开始更新位置之后,回调将在某个时刻到来,并且在您要求它停止之前一直继续。如果它应该自己启动,你必须弄清楚你的用例,但是当用户点击按钮时,或者如果更新应该开始,那么只保存位置(或者你想用它做什么)当用户点击时(我不太确定你的问题是什么意思)。
答案 2 :(得分:0)
在界面构建器中,将touchUpInside
事件设置为调用- (IBAction)buttonClicked:(id)sender
(或以编程方式设置操作),然后将按钮委托给self。在viewDidLoad
设置locationManager
:
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager startUpdatingLocation];
}
按钮操作:
- (IBAction)buttonClicked:(id)sender {
myLabel.text = [NSString stringWithFormat:@"%+.6f,%+.6f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Button clicked" message:myLabel.text delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
位置管理器委托方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 5.0) {
NSLog(@"New Latitude %+.6f, Longitude %+.6f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
}