计算两个向量之间的角度?

时间:2013-05-23 14:12:54

标签: iphone ios cllocationmanager compass-geolocation

我正在开发一个iOS应用程序,它必须根据设备标题显示POI(兴趣点)。我使用CLLocationManager来获取用户的位置和标题。我有一对目的地的坐标。基于此,我正在计算哪个季度是那个并且以度为单位返回偏离南(0度)的浮点值。我有 - / +北180度,南有0。这是代码片段:

-(float)updateTargetLongitude:(float)lon Latitude:(float)lat{
//    //longitude = x
//    //latitude = y
      NSLog(@"current location = (%.5f, %.5f)", [[NSUserDefaults standardUserDefaults] doubleForKey:@"currentLongitude"], [[NSUserDefaults standardUserDefaults] doubleForKey:@"currentLatitude"]);
      float x = lon - [[NSUserDefaults standardUserDefaults] doubleForKey:@"currentLongitude"];
      float y = lat - [[NSUserDefaults standardUserDefaults] doubleForKey:@"currentLatitude"];
      float angle;
      NSLog(@"Searching angle from source (%.5f, %.5f) to destination (%.5f, %.5f)", locationManager.location.coordinate.longitude, locationManager.location.coordinate.latitude, lon, lat);
      if (x == 0 && y == 0) {
          NSLog(@"you're there already!");
          return -0.1;
      }
      if(x == 0 && y > 0){
          NSLog(@"look north");
          angle = 180.0;
      }
      if (x == 0 && y < 0) {
          NSLog(@"look south");
          angle = 0;
      }
      if (x > 0 && y == 0) {
          NSLog(@"look east");
          angle = 90.0;
      }
      if (x < 0 && y == 0) {
          NSLog(@"look west");
          angle = -90;
      }
      if (x > 0 && y > 0) {
          NSLog(@"first quarter");
          angle = -atan2f(y, x) - M_PI_2;
      }
      if (x < 0 && y > 0) {
          NSLog(@"second quarter");
          angle = atan2f(y, x) + M_PI_2;
      }
      if (x < 0 && y < 0) {
          NSLog(@"third quarter");
          angle = atan2f(x, y);
      }
      if (x > 0 && y < 0) {
          NSLog(@"fourth quarter");
          angle = -atan2f(x, y);
      }
      NSLog(@"returning radians angle = %.4f for (%.5f, %.5f) :: degrees = %.3f", angle, y, x, angle * 180 / M_PI);
      return angle * 180 / M_PI ;
}

不知何故我有情况,目标是在第四季度,但是从南面是-93度。我迷路了,我不知道如何解决这个问题......

编辑:按季度我的意思是笛卡尔坐标系,其中+ y是北,+ x是东,依此类推!

p.s。:我已经读过iPhone指南针非常糟糕,但如果是这样,谷歌地图的应用程序是如何运作的呢?

edit2 :我在角度方面犯了一个错误。东部为-90度,西部为90度。

3 个答案:

答案 0 :(得分:2)

如果我看得正确,公式

angle = atan2(x, -y) * 180.0/M_PI;

应该适用于所有象限,不需要所有if语句。


atan2(y, x)返回向量(x, y)与正x轴之间的角度,返回值始终在-pipi之间。

在参数中用(y, x)替换(x, -y) 表示矢量旋转90度,因此是上述公式的结果 是测量到负y轴的角度,这是你想要的。


更新(根据问题中的“edit2”):如果要求是“south = 0 deg”,“east = -90 deg”,“west = +90 deg”那么公式将是

angle = atan2(-x, -y) * 180.0/M_PI;

答案 1 :(得分:1)

atan2功能已将象限考虑在内。换句话说,如果xy都是否定的,它“知道”您处于第三象限。知道了,您可以看到atan2(y, x)的角度输出是什么,然后将其更改为您希望它显示的方式。

即使使用相对不准确的指南针,Google地图也能正常工作的主要原因是道路的结构会给你提示,所以你可以得到比你不知道道路在哪里更大的错误。

答案 2 :(得分:0)

实际上,在决定它是什么象限之后我改变了代码以总是用x和y的正值计算atan2 - 现在它可以工作了!

相关问题