ios中计算两个经纬度的距离

源码 ->

extension CLLocationCoordinate2D {

    /**
     计算两个经纬度的距离 (使用ios自带算法)

     - parameter coor: 第二个经纬度

     - returns: 返回距离(m)
     */
    func distanceFromCoor(coor: CLLocationCoordinate2D) -> Double {
        let curLocation = CLLocation(latitude: latitude, longitude: longitude)
        let otherLocation = CLLocation(latitude: coor.latitude, longitude: coor.longitude)
        let distance = curLocation.distanceFromLocation(otherLocation)
        return distance;
    }

    /**
     计算两个经纬度的距离 (使用第三方算法)

     - parameter coor: 第二个经纬度

     - returns: 返回距离(m)
     */
    func distanceFromCoor2(coor: CLLocationCoordinate2D) -> Double {
        let PI: Double = 3.1415926
        let er: Double = 6378137 // 6378700.0f;
        //ave. radius = 6371.315 (someone said more accurate is 6366.707)
        //equatorial radius = 6378.388
        //nautical mile = 1.15078
        var radlat1 = PI * latitude / 180.0
        var radlat2 = PI * coor.latitude / 180.0
        //now long.
        var radlong1 = PI * longitude / 180.0
        var radlong2 = PI*coor.longitude / 180.0
        if( radlat1 < 0 ) {
            // south
            radlat1 = PI / 2 + fabs(radlat1)
        }
        if( radlat1 > 0 ) {
            // north
            radlat1 = PI / 2 - fabs(radlat1)
        }
        if( radlong1 < 0 ) {
            //west
            radlong1 = PI * 2 - fabs(radlong1)
        }
        if( radlat2 < 0 ) {
            // south
            radlat2 = PI / 2 + fabs(radlat2)
        }
        if( radlat2 > 0 ) {
            // north
            radlat2 = PI / 2 - fabs(radlat2)
        }
        if( radlong2 < 0 ) {
            // west
            radlong2 = PI * 2 - fabs(radlong2)
        }
        //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
        //zero ag is up so reverse lat
        let x1 = er * cos(radlong1) * sin(radlat1)
        let y1 = er * sin(radlong1) * sin(radlat1)
        let z1 = er * cos(radlat1)
        let x2 = er * cos(radlong2) * sin(radlat2)
        let y2 = er * sin(radlong2) * sin(radlat2)
        let z2 = er * cos(radlat2)

        let d = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2) + pow(z1 - z2, 2))
        //side, side, side, law of cosines and arccos
        let theta = acos((pow(er, 2) + pow(er, 2) - pow(d, 2)) / (2 * pow(er, 2)))
        let dist  = theta * er
        return dist
    }

}

测试执行 ->

let coor1 = CLLocationCoordinate2D(latitude: 31.4785977506, longitude: 120.3755036570)
let coor2 = CLLocationCoordinate2D(latitude: 31.4788786668, longitude: 120.3791247841)

print("\(coor1.distanceFromCoor(coor2))")
print("\(coor1.distanceFromCoor2(coor2))")

输出结果 ->

"345.50016065661\n"
"345.198446957566\n"

实地测试 误差可以接受

坚持原创技术分享,您的支持将鼓励我继续创作!