2015-02-04 3 views
2

특정 위치에 대한 나침반처럼 동작하는 화살표 이미지가 있습니다. 때로는 작동하고 다른 때는 미러링됩니다. 그래서 내가 동쪽을 향하고 있고 그 위치가 나와 동쪽이라면, 그것은 가리켜 야하지만 때로는 가리켜 야합니다.위치에 대한 각도 계산

#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0/M_PI)) 

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)heading 
{ 
    // update direction of arrow 
    CGFloat degrees = [self p_calculateAngleBetween:_myLocation 
               and:_otherLocation]; 
    CGFloat rads = (degrees - heading.trueHeading) * M_PI/180; 


    CGAffineTransform tr = CGAffineTransformIdentity; 
    tr = CGAffineTransformConcat(tr, CGAffineTransformMakeRotation(rads)); 

    [_directionArrowView setTransform:tr]; 
} 

-(CGFloat) p_calculateAngleBetween:(CLLocationCoordinate2D)coords0 and:(CLLocationCoordinate2D)coords1 { 
    double x = 0, y = 0 , deg = 0, deltaLon = 0; 

    deltaLon = coords1.longitude - coords0.longitude; 
    y = sin(deltaLon) * cos(coords1.latitude); 
    x = cos(coords0.latitude) * sin(coords1.latitude) - sin(coords0.latitude) * cos(coords1.latitude) * cos(deltaLon); 
    deg = RADIANS_TO_DEGREES(atan2(y, x)); 

    if(deg < 0) 
    { 
     deg = -deg; 
    } 
    else 
    { 
     deg = 360 - deg; 
    } 

    return deg; 
} 

다른 각도로 내 각도를 계산하는 올바른 방법입니까? 아니면 단계가 빠졌습니까? 화살이 직접 반대 방향으로 향하는 경우가 종종 있습니다. 제 가정은 제 수학에 문제가 있다는 것입니다.

+0

'trueHeading'은 때때로 음수 일 수 있습니다. - "음수 값은 제목을 확인할 수 없음을 나타냅니다." – TonyMkenu

답변

0

는 X로부터 & Y를 라디안을 계산하기 : 인수가 정의

경우 X가 제로 일 때 ATAN 함수가 올바르게 처리하기 때문에 0으로 나누는 문제 없다

double r = atan(y/x); 
if (x<0) 
    r = M_PI + r; 
else if (x>0 && y<0) 
    r = 2 * M_PI + r; 

무한대 (음의 무한대), + pi/2 (-pi/2)가 반환됩니다.