2
我試圖在swift中創建一個函數,它準確地計算從地球原點(緯度:0,經度:0)到任何位置的垂直和水平距離)。我知道iOS具有distanceFromLocation函數,但這給了我直接的位置。我正在尋找的是該方向的水平和垂直分量。我試圖提出自己的解決方案,但是當我根據水平和垂直分量測試直接距離時,它與實際距離不匹配。這裏是我的功能:獲取iOS中兩個座標之間距離的垂直和水平分量
func distanceFromOrigin(location:CLLocation) {
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
let earthOriginLocation = CLLocation(coordinate: CLLocationCoordinate2DMake(0.0, 0.0), altitude: CLLocationDistance(0.0), horizontalAccuracy: kCLLocationAccuracyBestForNavigation, verticalAccuracy: kCLLocationAccuracyBestForNavigation, timestamp: NSDate())
var horDistance = earthOriginLocation.distanceFromLocation(CLLocation(latitude: 0.0, longitude: location.coordinate.longitude))
var verDistance = earthOriginLocation.distanceFromLocation(CLLocation(latitude: location.coordinate.latitude, longitude: 0.0))
let overallDistance = earthOriginLocation.distanceFromLocation(location)
if lat < 0 {
print("Object is South of Equator")
verDistance *= -1
} else if lat > 0 {
print("Object is North of Equator")
} else {
print("Object is at the Equator")
}
if lon < 0 {
print("Object is West of Prime Meridian")
horDistance *= -1
} else if lon > 0 {
print("Object is East of Prime Meridian")
} else {
print("Object is at the Prime Meridian")
}
print("Vertical Distance: \(verDistance)")
print("Horizontal Distance: \(horDistance)")
print("Overall Distance: \(overallDistance)")
//Test to see if vertical and horizontal distances are accurate compared to actual distance.
print("Test: \(sqrt((pow(horDistance, 2.0)) + (pow(verDistance, 2.0))))")
}
謝謝!
我認爲你必須接受所有的肯定的價值觀,對嗎? – sargeras
@sargeras distanceFromLocation函數只返回一個正值,但我希望最終結果爲正值或負值,具體取決於經度還是緯度是正值還是負值。我添加了if-else語句來解決這個問題。如果經度或緯度爲負值,則計算的距離爲負值。 – Armin