Swift 根據經緯度計算距離
阿新 • • 發佈:2018-11-02
//根據角度計算弧度
func radian(d:Double) -> Double {
return d * Double.pi/180.0
}
//根據弧度計算角度
func angle(r:Double) -> Double {
return r * 180/Double.pi
}
OC也是一樣的方法,轉換成對應的OC方法即可//根據兩點經緯度計算兩點距離 func getDistance(lat1:Double,lng1:Double,lat2:Double,lng2:Double) -> Double { let EARTH_RADIUS:Double = 6378137.0 let radLat1:Double = self.radian(d: lat1) let radLat2:Double = self.radian(d: lat2) let radLng1:Double = self.radian(d: lng1) let radLng2:Double = self.radian(d: lng2) let a:Double = radLat1 - radLat2 let b:Double = radLng1 - radLng2 var s:Double = 2 * asin(sqrt(pow(sin(a/2), 2) + cos(radLat1) * cos(radLat2) * pow(sin(b/2), 2))) s = s * EARTH_RADIUS return s }