2011-02-03 183 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 
}