计算指南针到特定坐标而不是北方的航向

时间:2012-11-28 08:17:28

标签: ios algorithm geolocation ios6 mapkit

我无法正确使用此算法。我正试图制作一个指向某个位置的指南针,而不仅仅是指向北方。出了点问题。我花了很多时间试图解决这个问题,但我找不到它。有什么想法吗?

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{

double distanceEast = (location.longitude > 0 && otherLocation.longitude < 0) ? 180 - location.longitude + otherLocation.longitude - -180: otherLocation.longitude - location.longitude;

    if (distanceEast < 0) {
        distanceEast += 360;
    }

    double distanceWest = (location.longitude < 0 && otherLocation.longitude > 0) ? -180 - location.longitude - 180 - otherLocation.longitude : location.longitude - otherLocation.longitude;

    if (distanceWest < 0) {
        distanceWest += 360;
    }

    float latitudinalDifference = (otherLocation.latitude - location.latitude);
    float longitudinalDifference = fmin(distanceEast,distanceWest);

    float arcTan = atan(longitudinalDifference / latitudinalDifference);

        float oldRadian = (-manager.heading.trueHeading *M_PI /180.0f)+arcTan+M_PI;
        float newRadian = (-newHeading.trueHeading *M_PI /180.0f)+arcTan+M_PI;

        CABasicAnimation *animation;
        animation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        animation.fromValue = [NSNumber numberWithFloat:oldRadian];
        animation.toValue = [NSNumber numberWithFloat:newRadian];
        animation.duration = 0.5f;
        directionsArrow.layer.anchorPoint = CGPointMake(0.5, 0.5);

        [directionsArrow.layer addAnimation:animation forKey:@"rotationCompass"];
        directionsArrow.transform = CGAffineTransformMakeRotation(newRadian);
}

2 个答案:

答案 0 :(得分:1)

“Map Coordinates Systems” in the Location Awareness Programming Guide说“具体来说,在墨卡托地图投影上,地图上任意两点之间绘制的直线产生一个可用于地球表面实际导航的航向标题。”我认为你应该将你的地图坐标转换成地图点(MKMapPointForCoordinate)并在地图点之间的差异上调用atan。 (实际上,你应该使用atan2,而不是atan。)你试过吗?

答案 1 :(得分:1)

double lon = location.longitude - otherLocation.longitude;
double y = sin(lon) * cos(otherLocation.latitude);
double x = cos(location.latitude) * sin(otherLocation.latitude) - sin(location.latitude) * cos(otherLocation.latitude) * cos(lon);
double angle = atan2(y, x);

angle是两个地点之间的关系。