2011-02-03 191 views

回答

3

如果你想从两个坐标,你可以使用这个片段获得距离:

#include <math.h> 
#define DEG2RAD(degrees) (degrees * 0.01745327) 
#define RADIUS_OF_EARTH 6378.1 

+ (float) getDistanceFromStartCoords:(CLLocationCoordinate2D)start andEndCoords:(CLLocationCoordinate2D)end 
{ 
    float dist = acos((cos(DEG2RAD(start.latitude))* 
       cos(DEG2RAD(end.latitude))* 
       cos((-1*DEG2RAD(end.longitude))- 
        (-1*DEG2RAD(start.longitude)))) + 
       (sin(DEG2RAD(start.latitude))* 
       sin(DEG2RAD(end.latitude)))) * 
      RADIUS_OF_EARTH; 

    return dist; 
} 
+0

世界不是球形的。你相对于大地水准面的位置估算误差高达21km。 – 2011-02-03 13:55:40

3

iPhone上没有距离测量功能,可以给你2米的分辨率。您可以使用核心位置的-[CLLocation distanceFromLocation: otherLocation]方法来获得在两个位置之间米的位移,但记住:

  • 无处,我已经看到它的苹果解释是做什么用的Geode他们的坐标,而事实上无论是在用于不同位置计算的相同geode
  • 他们使用的模型没有考虑到高度,这对于计算字段大小区域中人尺寸物体之间的距离非常蹩脚。尽管估算伦敦和莫斯科之间的距离没有问题,但错误很小。
  • 当你的设备没有插好,使用真正的高精度的位置数据与运动检测相结合将会完全吸电池
  • 没有使用动态检测,你只能告诉其中的装置是对within tens of metres
2

这是一个“改良效果”上述解决方案。它增加了高度信息。看起来苹果返回的高度以米为单位。不适合飞行或轨道或类似的情况,但如果有人在另一个人的正上方15层,附近的山上等,则可以工作。未经广泛测试。它假定你不关心20公里以外的高度。然后,当您靠近另一个人时,它会进行高度更正。因此,对于距离彼此20米,但高100米的两个人,你会得到约102米的距离。最后,我切换到公里返回。还在原始代码中发现了一个南方虫。

#define DEG2RAD(degrees) (degrees * 0.01745329251) 
#define RADIUS_OF_EARTH 6371000.0 
// km 
+ (double)getDistanceFromStartCoords:(CLLocationCoordinate2D)start altStart:(double)altStart andEndCoords:(CLLocationCoordinate2D)end altEnd:(double)altEnd; 
{ 
    double argument = (cos(DEG2RAD(start.latitude))* 
       cos(DEG2RAD(end.latitude))* 
       cos((-1*DEG2RAD(end.longitude))- 
        (-1*DEG2RAD(start.longitude)))) + 
       (sin(DEG2RAD(start.latitude))* 
       sin(DEG2RAD(end.latitude))); 

    double dist = 0.0; 
    if (argument < 1.0 && argument > -1.0) // acos will return nan for very small (0) distance 
     dist = acos(argument)*RADIUS_OF_EARTH; 
// else 
//  NSLog(@"found bug, %f", acos(argument)); 


    // Altitude hack. 
    // blend in an altitude correction (blend for smoothness) 
    // add in altitude difference 
    double altDiff = fabs(altStart - altEnd); // altdiff 
    double factor = 1.0 - dist/20000.0; 
    if (factor < 0.0) 
     factor = 0.0; 

    dist += sqrt(dist*dist + factor*altDiff*altDiff); 

    //NSLog(@"distance found, %f", dist); 
    return dist/1000.0; // return km 
}