我正在构建一个应该向某个位置显示箭头的应用程序。例如,如果我在位置 X 并且目标设置为位置 Y,它应该显示一个直接指向该位置的箭头。
在搜索和搜索之后,我发现有一些花哨的计算公式,但是我似乎一遍又一遍地弄错了。
这是我的问题。虽然它似乎找到了正确的初始位置,但只要我转动我的设备,“箭头”就会转向相反的方向或它应该转向的方向。所以,如果我顺时针转动我的设备,箭头也会顺时针转动……反之亦然。
这是我的一些代码:
@implementation CompassViewController
BOOL firstPositionFound = NO;
float lastPosition = 0;
float currentHeading = 0;
[...]
#pragma mark -
#pragma mark Core Location Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
if (newHeading.headingAccuracy > 0) {
CLLocationDirection theHeading = newHeading.magneticHeading;
currentHeading = theHeading;
[self fixPointer:theHeading];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
self.currentLocation = newLocation;
[self fixPointer:currentHeading];
}
- (void)fixPointer:(float)heading
{
float degree = [self calculateDegree:self.currentLocation];
degree = heading - degree;
NSLog(@"heading: %f, Degree: %f", heading, degree);
NSLog(@"Degree 2: %f", degree);
self.arrowView.transform = CGAffineTransformMakeRotation(degreesToRadians(degree));
}
#pragma mark -
#pragma mark Delegate methods
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Other methods
- (float)calculateDegree:(CLLocation *)newLocation
{
CLLocationCoordinate2D from = newLocation.coordinate;
CLLocationCoordinate2D to;
to.latitude = APP_DESTINATION_LAT;
to.longitude = APP_DESTINATION_LON;
float res = atan2(sin((to.longitude*M_PI/180)-(from.longitude*M_PI/180))*cos(to.latitude*M_PI/180),
cos(from.latitude*M_PI/180)*sin(to.latitude*M_PI/180)-sin(from.latitude*M_PI/180)*cos(to.latitude*M_PI/180)*cos((to.longitude*M_PI/180)-(from.longitude*M_PI/180)));
res = res/M_PI*180;
if (res < 0)
res = 360.0f + res;
return res;
}
#pragma mark -
我只是迷路了,有人可以指出我哪里出错了吗?我想它是一些简单的事情,我目前正在盲目地看到。