开发者

getting current latitude and longitude

I want to get current location, I see with this code but how can I assign to this latitude and longitude to label when click a button?

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation   *)newLocation fromLocation:(CLLocation *)oldLocation {

    NSLog(@"latitudeAAAAA %f",newLocation.coordinate.latitude );
    NSLog(@"longit开发者_StackOverflowudeAAAA %f",newLocation.coordinate.longitude);
    [corelocation stopUpdatingLocation];
}


label.text = [NSString stringWithFormat:@"%lf,%lf", newLocation.coordinate.latitude, newLocation.coordinate.longitude];


You need set your own class as a delegate of the your CLLocationManager and then callstartUpdatingLocation (docs) to make it call the method you mention. The callback will come at some point after you've asked it to start updating location, and keep coming until you ask it to stop. You'll have to figure out for your use case if it should start by itself, but then only save the location (or what ever it is you want to do with it) when the user clicks a button, or if the updates should start when the user clicks (I'm not quite sure what you mean from your question).

https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html#//apple_ref/doc/uid/TP40007125-CH3-SW2


In the interface builder, set the touchUpInside event to call - (IBAction)buttonClicked:(id)sender (or set action programatically) then set your buttons delegate to self. On viewDidLoad setup your locationManager:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager startUpdatingLocation];
}

Button action:

- (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];

}

Location Manager delegate methods:

- (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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜