2011-08-03 65 views
1

這是一種計算從一個CLLocation到另一個CLLocation的角度(弧度)的有效方法嗎?計算2個CLLocations之間角度的有效方法?

-(float)angleFromLocation:(CLLocationCoordinate2D)start toLocation:(CLLocationCoordinate2D)end { 
float deltaX = start.latitude - end.latitude; 
float deltaY = start.longitude - end.longitude; 
float ang = atan2(deltaY, deltaX); 

return ang;} 

請指教!

任何幫助將不勝感激。

+0

你已經很接近了。看看這個答案的解決方案 - http://stackoverflow.com/questions/6140045/how-to-get-degree-of-poi-from-another-poi – olo

回答

0

我發現這個計算的最佳方法是使用餘弦的球形定律。有一個C函數可以做到這一點here on github稱爲headingInDegrees。它有兩個緯度/經度對,並返回標題:

/*------------------------------------------------------------------------- 
* Given two lat/lon points on earth, calculates the heading 
* from lat1/lon1 to lat2/lon2. 
* 
* lat/lon params in degrees 
* result in degrees 
*-------------------------------------------------------------------------*/ 
double headingInDegrees(double lat1, double lon1, double lat2, double lon2); 

由於CLLocationCoordinate2d包含經度和緯度,很容易對那些兩個領域通過這一功能,並取回了航向。

2

我用這個question and answer的一個變種,它工作得很好:

double DegreesToRadians(double degrees) {return degrees * M_PI/180.0;}; 
double RadiansToDegrees(double radians) {return radians * 180.0/M_PI;}; 

- (double)bearingFromLocation:(CLLocation *)fromLocation toLocation:(CLLocation *)toLocation 
{ 

    double lat1 = DegreesToRadians(fromLocation.coordinate.latitude); 
    double lon1 = DegreesToRadians(fromLocation.coordinate.longitude); 

    double lat2 = DegreesToRadians(toLocation.coordinate.latitude); 
    double lon2 = DegreesToRadians(toLocation.coordinate.longitude); 

    double dLon = lon2 - lon1; 

    double y = sin(dLon) * cos(lat2); 
    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon); 
    double radiansBearing = atan2(y, x); 

    double degreesBearing = RadiansToDegrees(radiansBearing); 

    if (degreesBearing >= 0) { 
     return degreesBearing; 
    } else { 
     return degreesBearing + 360.0; 
    } 
} 
+0

完美的作品!謝謝! – coolbeet

+1

我有類似的問題。我正在根據GPS讀數跟蹤用戶的位置。 GPS讀數爲我提供了一個「航向」值,它決定了以度爲單位的正北方向。當我計算兩個座標之間的角度差時,如果用戶從0度移動到359度,情況會變得很糟糕。實時,它可能是一個1度的變化,但我的代碼是給359度的變化。有任何想法嗎? – Nil

0

斯威夫特4版本:

extension FloatingPoint { 

    var degreesToRadians: Self { return self * .pi/180 } 
    var radiansToDegrees: Self { return self * 180/.pi } 
} 

extension CLLocationCoordinate2D: Equatable { 

    func heading(to: CLLocationCoordinate2D) -> Double { 
     let lat1 = self.latitude.degreesToRadians 
     let lon1 = self.longitude.degreesToRadians 

     let lat2 = to.latitude.degreesToRadians 
     let lon2 = to.longitude.degreesToRadians 

     let dLon = lon2 - lon1 
     let y = sin(dLon) * cos(lat2) 
     let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon) 

     let headingDegrees = atan2(y, x).radiansToDegrees 
     if headingDegrees >= 0 { 
      return headingDegrees 
     } else { 
      return headingDegrees + 360 
     } 
    } 
} 
相關問題