質問

New to using the corelocation framework could use some help understanding why my code isnt working how I'd like it too. I want it to track the distance travelled but when the view fires up it does different things everytime. Sometimes itll jump to 1000 or another large value or itll increase by random increments. Can anyone see why this code isnt working for me?

    - (void)viewDidLoad
{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.delegate = self;
    locationManager.distanceFilter = 100; //update every 100 meters
    [locationManager startUpdatingLocation];
    startLocation = nil;

    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if (startLocation == nil)
    {
        totalDistanceBetween = 0;
        self.startLocation = newLocation;
    }
    CLLocationDistance distanceBetween = [newLocation distanceFromLocation:startLocation ];
    startLocation = newLocation;
    totalDistanceBetween += distanceBetween;
    totalDistanceBetween = totalDistanceBetween * 0.001; //convert to m value to km
    NSString *tripString = [[NSString alloc]
                            initWithFormat:@"%.02f",
                            totalDistanceBetween];
    distance.text = tripString;
}
役に立ちましたか?

解決

The first thing that jumps out to me is that you set startLocation to nil after you tell the location manager to start giving you updates.

Depending on how startLocation is defined/initialized/reused, it might not contain the initial value you expect it to.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top