如何在Swift中获得地球上的点之间的距离?

时间:2015-05-13 16:27:41

标签: swift ios8 distance latitude-longitude

我使用了两种方法..苹果的一种

 @IBAction func getDistancePressed(sender: AnyObject) {

    distanceLabel.text = "\(location_2.distanceFromLocation(location_1))m" // Meters

}

和我的

  @IBAction func getDistancePressed(sender: AnyObject) {

    let lat1 = location_1.coordinate.latitude
    let lon1 = location_1.coordinate.longitude
    let lat2 = location_2.coordinate.latitude
    let lon2 = location_2.coordinate.longitude


    distanceLabel.text = "\(getDistanceFromLatLonInMeter(lat1, lon1: lon1, lat2: lat2, lon2: lon2))m"

}
func getDistanceFromLatLonInMeter(lat1 : Double ,lon1 : Double ,lat2 : Double ,lon2 : Double) -> Double{


    var earthRadius : Double = 6372797.560856 //inMeter

    var deltaLAT : Double = deg2rad(lat2 - lat1)
    var deltaLON : Double = deg2rad(lon2 - lon1)

    var latitudeH = sin(deltaLAT * 0.5)
    latitudeH *= latitudeH

    var lontitudeH = sin(deltaLON * 0.5)
    lontitudeH *= lontitudeH

    var tmp = cos(deg2rad(lat2)) * cos(deg2rad(lat1));

    return earthRadius * 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH))

}
func deg2rad(deg : Double) -> Double {

    return deg * 0.017453292519943295769236907684886
}

两者都给我相同的价值,两者都错了..当我移动我的iPhone(1米)它给我11米,当我移动3米它给我20,依此类推 。我不知道问题出在哪里。做这件事的正确方法是什么。如何获得距离?

例如 --->

firstLatitude - > 24.4348484485008

firstLongitude - > 39.6552843828735

lastLatitude - > 24.4349537442103

lastLongitude - > 39.6552204902715

它给出距离 - > 13.379米

它应该是0.7米(实际)

0 个答案:

没有答案