获取用户的当前位置

时间:2015-03-30 13:14:13

标签: ios objective-c cllocation

有一个确定用户位置的功能:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{
    NSLog(@"Latitude = %f", newLocation.coordinate.latitude);
    NSLog(@"Longitude = %f", newLocation.coordinate.longitude);
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([CLLocationManager locationServicesEnabled]){
        self.myLocationManager = [[CLLocationManager alloc] init];
        self.myLocationManager.delegate = self;
        [self.myLocationManager startUpdatingLocation];

并且有一个考虑两点之间距离的功能

CLLocation *location1 = [[CLLocation alloc] initWithLatitude:59.957069 longitude:30.323013];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:60.050043 longitude:30.345783];

float betweenDistance = [location1 distanceFromLocation:location2];

NSLog(@"Distance is %f km", betweenDistance/1000);

我希望location2成为用户的当前位置。我如何确定?

3 个答案:

答案 0 :(得分:0)

希望我能正确理解你,但要计算2 CLLocations之间的距离,只需使用内置的distance method

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

答案 1 :(得分:0)

将商标设为@property (nonatomic,strong) CLLocation *userLocation; 并将此didUpdateToLocation方法内的userLocation = newLocation更新为<{1}}。

答案 2 :(得分:0)

locationManager:didUpdateToLocation:期间,您将收到用户的当前位置信息。您需要将其存储在属性中。之后,您可以使用该属性来确定用户的位置。

没有同步调用将获取当前位置。你必须等待它从位置管理员进来,它可能永远不会有很多原因(你可能没有权限访问这些信息,或GPS可能已关闭,或许多其他原因)。您的代码必须能够处理此问题,并在数据到达时自行调整。

相关问题