2015-04-03 63 views
1

我想計算Swift中兩個位置之間的方位。我嘗試了一些代碼,但它不起作用。我搜索了這個問題,但是我沒有找到任何有關這方面的結果。計算兩個位置之間的方位

func calculat(userlocation:CLLocation){ 

    let latuserlocation:() = DegreesToRadians(userlocation.coordinate.latitude) 

    let lonuserlocatioc:() = DegreesToRadians(userlocation.coordinate.longitude) 


    latitude = NSString (string: places[activePlace]["lat"]!).doubleValue 

    longitude = NSString (string: places[activePlace]["lon"]!).doubleValue 


    let targetedPointLatitude:() = DegreesToRadians(latitude) 

    let targetedPointlongitude:() = DegreesToRadians(longitude) 


    let dlon = lonuserlocatioc - targetedPointlongitude 


    let y = sin(dLon) * cos(targetedPointLatitude); 

    let x = cos(latuserlocation) * sin(targetedPointLatitude) - sin(latuserlocation) * cos(targetedPointLatitude) * cos(dLon); 

    let radiansBearing = atan2(y, x); 

return RadiansToDegrees(radiansBearing) 

let dlon = lonuserlocatioc - targetedPointlongitude錯誤是:

(不能調用 ' - ' 類型的參數列表 '((),())')

+0

[2個CLLocation點之間的夫特計算軸承]的可能重複(http://stackoverflow.com/questions/26998029/calculating-bearing-between-two-cllocation-points-in-swift) – Moritz 2015-04-03 12:16:37

+0

我試試這個,但不工作(計算Swift中兩個CLLocation點之間的方位)[重複] – user3432650 2015-04-03 12:21:04

+1

代碼沒有意義。有一個return語句,但func沒有說它會返回一個值。爲什麼要將經度和緯度變量聲明爲元組,然後嘗試對它們進行算術(減法)?不要說「不行」,你應該說什麼_exact_錯誤或問題,因爲有無數的方式可能「不起作用」。 – Anna 2015-04-03 12:26:38

回答

0

相比CLLocation Category for Calculating Bearing w/ Haversine function ,你的dlon是不同的。這個答案有

let dlon = targetedPointlongitude - lonuserlocatioc 

我不知道這是你的問題,但它看起來很奇怪。

+0

Accualy我將此代碼從JavaScript代碼轉換而來。奇怪的地方在哪裏?如果你給我詳細的信息,我可以編輯它。我檢查你的鏈接,這對我來說看起來是一樣的。也許我看不出有什麼不同。 – 2016-09-07 07:35:38

+0

我給出的鏈接上的代碼有dlon等於上述問題代碼的-1倍。 – emrys57 2016-09-07 08:59:35

-2

像這樣的Swift函數;

func radians(n: Double) -> Double{ 
    return n * (M_PI/180); 
} 

func degrees(n: Double) -> Double{ 
    return n * (180/M_PI); 
} 

func logC(val:Double,forBase base:Double) -> Double { 
    return log(val)/log(base); 
} 

func getBearing(startLat: Double,startLon:Double,endLat: Double,endLon: Double) -> Double{ 
    var s_LAT: Double , s_LON: Double, e_LAT: Double, e_LON: Double, d_LONG: Double, d_PHI: Double; 

    s_LAT = startLat; 
    s_LON = startLon; 
    e_LAT = endLat; 
    e_LON = endLon; 

    d_LONG = e_LON - s_LON; 

    d_PHI = logC(tan(e_LAT/2.0+M_PI/4.0)/tan(s_LAT/2.0+M_PI/4.0),forBase :M_E); 
    if (abs(d_LONG)>M_PI){ 
     if(d_LONG>0.0){ 
      d_LONG = -(2.0 * M_PI - d_LONG); 
     }else{ 
      d_LONG = (2.0 * M_PI - d_LONG); 
     } 
    } 
    return degrees(atan2(d_LONG, d_PHI)+360.0)%360.0; 
} 
+0

@EricAya好的,我會在幾個小時後轉換並編輯我的答案。對此感到抱歉。 – 2016-09-06 14:56:56

+0

@EricAya轉換爲swift和更新的答案。 – 2016-09-06 21:42:02

相關問題