Frage

I want to be able to calculate the average speed with core location. I already have the current speed:

- (void)locationUpdate:(CLLocation *)location {
speedLabel.text = [NSString stringWithFormat:@"%.2f", [location speed]*2.236936284];

And also I want to be able to show it in a label and reset it with a button.

I want it to start averaging when a button is pressed and update the average about every 5 seconds and then stop averaging after another button is pressed.

Thank you!

War es hilfreich?

Lösung

As defined: Average refers to the sum of numbers divided by n. That is, when dealing with an average, you usually have at least 2 or more observations from which you wish to calculate an average. The average of your current speed is just, well, your current speed divided by one. I'm sure that's not what you are looking for.

You will need to ask yourself for how long time you wish to average. Five seconds? 10 seconds? The shorter the interval (fewer observations), the more sensitive to significant changes your average will be.

Basically what you would do is to store your observations in a mutable collection, eg NSMutableArray, and then just sum them up and divide the sum by the array's count property, corresponding to the number of observations. Or, as NSHipster has a great article on, you could take advantage of valueForKeyPath:

NSMutableArray *speedObservations = [[NSMutableArray alloc] initWithCapacity:n];
...
CGFloat average = [speedObservations valueForKeyPath:@"@avg.floatValue"];

Andere Tipps

Hmm. I would do this differently.

Average speed is distance traveled from a start time to an end time. I would record the user's location when they start asking for average speed, along with the current date. Then I would periodically get a new location reading and calculate distance traveled from the old location to the new location divided by the elapsed time between the current location reading and the first location reading.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top