Search code examples
iosobjective-ccllocation

Getting CLLocation course and translate to user


I'm trying to get information about the direction taken by the user (N-S-W-O) via CLLocation's course method. I'm using this code:

double course;
bool isNord;

course = currentLocation.course;
NSLog(@"Current course: %f", course);
NSInteger courseString = course;
//_labelCompass.text = [NSString stringWithFormat:@"%d", courseString];

if (courseString == -1) {
    _labelCompass.text = @"N/A";
}
if (courseString >= 22 && courseString <= 67) {
    isNord = false;
    _labelCompass.text = @"NE";
}
if (courseString >=67 && courseString <= 112) {
    isNord = false;
    _labelCompass.text = @"E";
}
if (courseString >= 112 && courseString <= 157) {
    isNord = false;
    _labelCompass.text = @"SE";
}
if (courseString >= 157 && courseString <= 208) {
    isNord = false;
    _labelCompass.text = @"S";
}
if (courseString >= 208 && courseString <= 247) {
    isNord = false;
    _labelCompass.text = @"SW";
}
if (courseString >= 247 && courseString <= 292) {
    isNord = false;
    _labelCompass.text = @"W";
}

if (courseString >= 292 && courseString <= 337) {
    isNord = false;
    _labelCompass.text = @"NW";
}

if (isNord == true) {
    _labelCompass.text = @"N";
}

Of course I'm putting this into

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

and the course information is update successfully. Using this algorithm I cannot know when the course is North like I do for the others so I've built this. There are any other methods better than this? Thanks a lot.


Solution

  • The wrong thing is that with <= 67 of the first if and the second >= 67 of the second if, if the value is 67, ALWAYS the first if will be triggered. Also, as stated by rmaddy please use else if, it's kind more efficent. Finally use the best syntax min < myVal && myVal < max to emulate the Mathematical range min < MyVal < max.