Search code examples
iosobjective-cgeolocationcore-locationcllocation

Get course of distant object with CLLocation


I want to know azimuth(course) of distant object (on the map). I have coordinates of this distant object. I tried to do this:

CLLocation *distLoc = [CLLocation alloc] initWithLatitude:40.725405 
                                                longitude:-74.003906]; // NY city

NSLog(@"loc: %f", distLoc.course);

the output is: loc: -1.0...

but why?

I want to know this course from my current direction. I also have location update with startUpdatingLocation method and delegate update.

What I do wrong?

Why I can't just get course of distant object from my current position? Thanks.


Solution

  • -course returns the direction of a moving object. So you would call -course on your users current location. It doesn't give you a direction from your location to another location. So unless NYC is moving, it will always return -1

    If you want the find the compass heading you should be moving you can do this:

    #define RAD_TO_DEG(r) ((r) * (180 / M_PI))
    
    ...    
    
    CLLocationCoordinate2D coord1 = currentLocation.coordinate;
    CLLocationCoordinate2D coord2 = distLoc.coordinate;
    
    CLLocationDegrees deltaLong = coord2.longitude - coord1.longitude;
    CLLocationDegrees yComponent = sin(deltaLong) * cos(coord2.latitude);
    CLLocationDegrees xComponent = (cos(coord1.latitude) * sin(coord2.latitude)) - (sin(coord1.latitude) * cos(coord2.latitude) * cos(deltaLong));
    
    CLLocationDegrees radians = atan2(yComponent, xComponent);
    CLLocationDegrees degrees = RAD_TO_DEG(radians) + 360;
    
    CLLocationDirection heading = fmod(degrees, 360);