简体   繁体   English

在两点之间获得距离时遇到麻烦

[英]Trouble while getting distance between two points

In my iOS app I've to track the distance from aa start point to my current location. 在我的iOS应用程序中,我要跟踪从起点到我当前位置的距离。 I implemented this code: 我实现了这段代码:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentLocation = [locations lastObject];
    CLLocation *startLocation = [locations firstObject];
    [coordArray addObject:currentLocation];
    float speed = currentLocation.speed * 3.6;
    if (speed > 0) {
        self.labelSpeed.text = [NSString stringWithFormat:@"%.2f Km/h", speed];
        [speedArray addObject:[NSNumber numberWithFloat:speed]];
    }
    CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
}

But when I try to use the app it doesn't get a distance. 但是,当我尝试使用该应用程序时,它没有得到距离。 I need the distance to show it in a label and with distance I will calculate the number of steps by using this equation: 我需要距离在标签中显示它并且距离我将使用以下等式计算步数:

steps = distance / length of human step

I know that it's not accurate, but I can't use accelerometer, because it doesn't work while the display of the iPhone is not active. 我知道它不准确,但我不能使用加速度计,因为它在iPhone显示器不活动时不起作用。 A person suggested me this solution . 一个人建议我这个解决方案 Why my code doesn't give me a distance? 为什么我的代码没有给我一个距离?

The callback 回调

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

does give you at least one location, and locations array hold sonly multiple objects if the location update was deferred before. 确实为您提供了至少一个位置,并且如果之前延迟了位置更新,则位置数组会保留多个对象。 To get the walking/driving distance, you have to store the initial location in a class variable or property. 要获得步行/行驶距离,您必须将初始位置存储在类变量或属性中。 Then, when you want to calculate a distance, do as in your code above, but with the class variable that holds the initial location. 然后,当您想要计算距离时,请按照上面的代码进行操作,但使用保存初始位置的类变量。

Check below code for getting distance: 检查以下代码以获取距离:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {


    if ([coordArray count]>0) {

        CLLocation *currentLocation = manager.location;
        CLLocation *startLocation = [coordArray objectAtIndex:0];
        [coordArray addObject:currentLocation];
        float speed = currentLocation.speed * 3.6;
        if (speed > 0) {
            NSLog(@"\n speed:%@",[NSString stringWithFormat:@"%.2f Km/h", speed]);
        }

        CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];

        if (distance>0) {
            NSLog(@"Distance:%@",[NSString stringWithFormat:@"%lf meters",distance]);
        }

    }
    else{
        [coordArray addObject:manager.location];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM