2011-05-26 50 views
3

如何計算iPhone地圖應用程序上兩個興趣點座標(興趣點)之間的角度度數?如何獲得兩個POI之間的角度?

+2

什麼是POI,什麼是 「iPhone應用放」? – 2011-05-26 14:19:17

+0

@Radek S:@Jano更新了原始問題 – 2011-05-26 14:59:38

回答

12

我猜你試着計算兩個興趣點(POI)的座標之間的度數。

計算一個great circle的弧線:

+(float) greatCircleFrom:(CLLocation*)first 
         to:(CLLocation*)second { 

    int radius = 6371; // 6371km is the radius of the earth 
    float dLat = second.coordinate.latitude-first.coordinate.latitude; 
    float dLon = second.coordinate.longitude-first.coordinate.longitude; 
    float a = pow(sin(dLat/2),2) + cos(first.coordinate.latitude)*cos(second.coordinate.latitude) * pow(sin(dLon/2),2); 
    float c = 2 * atan2(sqrt(a),sqrt(1-a)); 
    float d = radius * c; 

    return d; 
} 

另一種選擇是假裝你是在直角座標系(速度較快,但並非沒有對長距離錯誤):

+(float)angleFromCoordinate:(CLLocationCoordinate2D)first 
       toCoordinate:(CLLocationCoordinate2D)second { 

    float deltaLongitude = second.longitude - first.longitude; 
    float deltaLatitude = second.latitude - first.latitude; 
    float angle = (M_PI * .5f) - atan(deltaLatitude/deltaLongitude); 

    if (deltaLongitude > 0)  return angle; 
    else if (deltaLongitude < 0) return angle + M_PI; 
    else if (deltaLatitude < 0) return M_PI; 

    return 0.0f; 
} 

如果你想導致度數而不是弧度,您必須應用以下轉換:

#define RADIANS_TO_DEGREES(radians) ((radians) * 180.0/M_PI) 
+0

非常感謝Jano :) – 2011-05-27 14:14:48

+0

輝煌的東西,謝謝! – 2013-04-29 09:13:02

+0

GreatCircle不會將輸入轉換爲弧度 – gjpc 2015-07-16 16:21:29

2

您正在計算從一點到另一點的'方位'。有公式爲的一大堆,和許多其它地理數量像距離和跨軌跡誤差的,這個網頁上:

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

的公式的幾種格式,所以你可以很容易地轉換到任何您需要iPhone的語言。也有JavaScript計算器,所以你可以測試你的代碼獲得與他們相同的答案。

+0

確實Jano的東西沒有在這裏工作,但您提到的網站確實幫了很大忙。但要小心:他們忘記提及在Javascript的軸承示例中lat/long必須是輻射格式。 – brainray 2014-02-11 11:05:35

1

如果其他解決方案不爲你工作嘗試:

- (int)getInitialBearingFrom:(CLLocation *)first 
         to:(CLLocation *)second 
{ 
    float lat1 = [self degreesToRad:first.coordinate.latitude]; 
    float lat2 = [self degreesToRad:second.coordinate.latitude]; 
    float lon1 = [self degreesToRad:first.coordinate.longitude]; 
    float lon2 = [self degreesToRad:second.coordinate.longitude]; 
    float dLon = lon2 - lon1; 
    float y = sin (dLon) * cos (lat2); 
    float x1 = cos (lat1) * sin (lat2); 
    float x2 = sin (lat1) * cos (lat2) * cos (dLon); 
    float x = x1 - x2; 
    float bearingRadRaw = atan2f (y, x); 
    float bearingDegRaw = bearingRadRaw * 180/M_PI; 
    int bearing = ((int) bearingDegRaw + 360) % 360; // +- 180 deg to 360 deg 

    return bearing; 
} 

對於最終軸承,簡單地採取從終點的初始軸承到開始點和反向它(使用θ=(θ+ 180 )%360)。

你需要這2名助手:

-(float)radToDegrees:(float)radians 
{ 
    return radians * 180/M_PI; 
} 
-(float)degreesToRad:(float)degrees 
{ 
    return degrees * M_PI /180; 
} 
+0

是否將輸入轉換爲弧度 – gjpc 2015-07-16 16:23:03

相關問題