2010-10-11 82 views
3

作爲概念證明,我想要創建一個應用程序來檢索當前座標,計算朝向另一個點的方向,並使用指南針旋轉箭頭圖像指向太空中的這一點。使用指南針標題旋轉圖像以指向熟知的點

我知道如何檢索當前座標並通過CGAffineTransformMakeRotation旋轉圖像,但我還沒有找到計算正確角度的公式。

任何提示?

回答

2

首先你需要計算一個方位。本頁面給出了這樣做的一個整潔的公式:

http://www.movable-type.co.uk/scripts/latlong.html

然後,你可以做一些簡單的算術發現軸承和航向的iPhone指向朝之間的差異。按照這種差異旋轉圖像。

+0

OK,感謝該真棒頁,我計算正確的軸承;不幸的是,我嘗試了不同的公式來找出差異,但是我找不到合適的公式:請您指出正確的操作? – 2010-10-12 23:49:26

+1

好吧,找到它,現在它的作品!非常感謝 – 2010-10-13 12:46:01

2

軸承是:

double bearingUsingStartCoordinate(CLLocation *start, CLLocation *end) 
{ 
    double tc1; 
    tc1 = 0.0; 

    //dlat = lat2 - lat1 
    //CLLocationDegrees dlat = end.coordinate.latitude - start.coordinate.latitude; 

    //dlon = lon2 - lon1 
    CLLocationDegrees dlon = end.coordinate.longitude - start.coordinate.longitude; 

    //y = sin(lon2-lon1)*cos(lat2) 
    double y = sin(d2r(dlon)) * cos(d2r(end.coordinate.latitude)); 

    //x = cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1) 
    double x = cos(d2r(start.coordinate.latitude))*sin(d2r(end.coordinate.latitude)) - sin(d2r(start.coordinate.latitude))*cos(d2r(end.coordinate.latitude))*cos(d2r(dlon)); 

    if (y > 0) 
    { 
     if (x > 0) 
      tc1 = r2d(atan(y/x)); 

     if (x < 0) 
      tc1 = 180 - r2d(atan(-y/x)); 

     if (x == 0) 
      tc1 = 90; 

    } else if (y < 0) 
    { 
     if (x > 0) 
      tc1 = r2d(-atan(-y/x)); 

     if (x < 0) 
      tc1 = r2d(atan(y/x)) - 180; 

     if (x == 0) 
      tc1 = 270; 

    } else if (y == 0) 
    { 
     if (x > 0) 
      tc1 = 0; 

     if (x < 0) 
      tc1 = 180; 

     if (x == 0) 
      tc1 = nan(0); 
    } 
    if (tc1 < 0) 
     tc1 +=360.0; 
     return tc1; 
} 

而對於那些兩點之間尋找距離:

double haversine_km(double lat1, double long1, double lat2, double long2) 
{ 
    double dlong = d2r(long2 - long1); 
    double dlat = d2r(lat2 - lat1); 
    double a = pow(sin(dlat/2.0), 2) + cos(d2r(lat1)) * cos(d2r(lat2)) * pow(sin(dlong/2.0), 2); 
    double c = 2 * atan2(sqrt(a), sqrt(1-a)); 
    double d = 6367 * c; 

    return d; 
} 

double haversine_mi(double lat1, double long1, double lat2, double long2) 
{ 
    double dlong = d2r(long2 - long1); 
    double dlat = d2r(lat2 - lat1); 
    double a = pow(sin(dlat/2.0), 2) + cos(d2r(lat1)) * cos(d2r(lat2)) * pow(sin(dlong/2.0), 2); 
    double c = 2 * atan2(sqrt(a), sqrt(1-a)); 
    double d = 3956 * c; 

    return d; 
}