gpt4 book ai didi

ios - 计算位置的度数

转载 作者:行者123 更新时间:2023-11-29 11:13:04 24 4
gpt4 key购买 nike

我正在构建一个应显示指向特定位置的箭头的应用程序。例如,如果我在位置 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 -

我迷路了,有人可以指出我哪里做错了吗?我猜这是一些我目前无法看到的简单事物。

最佳答案

看看这个 Stack Overflow 问题的答案:

CLLocation Category for Calculating Bearing w/ Haversine function

具体来说,这部分:

如果您获得负方位角,请将 2*M_PI 添加到以弧度方位角为单位的最终结果(如果您在转换为度数后添加,则为 360)。 atan2 返回 -M_PI 到 M_PI(-180 到 180 度)范围内的结果,因此您可能希望使用类似于以下代码的内容将其转换为罗盘方位

if(radiansBearing < 0.0)
radiansBearing += 2*M_PI;**

此外,标题信息需要根据设备的方向和角度进行调整,除非您始终以纵向拿着设备。将您的设备慢慢转到横向模式,您会看到航向值改变 90°。

关于ios - 计算位置的度数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10642759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com