【问题标题】:Point to location using compass Swift使用指南针 Swift 指向位置
【发布时间】:2016-05-15 01:33:39
【问题描述】:

我正在开发一个指南针,它可以从我当前的位置指向对象的其他位置。目前我正在关注这个链接:Point to location using compass

我觉得在我当前位置与对象之间的指向不正确。 谁能帮助我如何开发可以从我当前位置指向对象其他位置的指南针?

【问题讨论】:

    标签: ios swift mobile compass mobile-development


    【解决方案1】:

    要计算您的位置和目标位置之间的角度,您需要 4 个输入变量:

    1) 当前位置(从核心位置获得)

    2) 目标位置(已知)

    3) 当前航向(相对于真北,从核心位置获得)

    4) 方位角,正北与目标之间的角度,您可以使用以下代码获取:

    private func getBearing(point1: CLLocationCoordinate2D, point2: CLLocationCoordinate2D) -> Double {
    
        let lat1 = point1.latitude.degreesToRadians
        let lon1 = point1.longitude.degreesToRadians
    
        let lat2 = point2.latitude.degreesToRadians
        let lon2 = point2.longitude.degreesToRadians
    
        let dLon = lon2 - lon1
    
        let y = sin(dLon) * cos(lat2)
        let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
    
        var radiansBearing = atan2(y, x)
        if radiansBearing < 0 {
            radiansBearing += 2 * Double.pi
        }
    
        return radiansBearing.radiansToDegrees
    }
    

    然后您可以使用以下代码计算您与目标之间的角度:

    /// Compute the angle between two map points and the from point heading
    /// returned angle is between 0 and 360 degrees
    private func doComputeAngleBetweenMapPoints(
        fromHeading: CLLocationDirection,
        _ fromPoint: CLLocationCoordinate2D,
        _ toPoint: CLLocationCoordinate2D
    ) -> CLLocationDirection {
        let bearing = getBearing(point1: fromPoint, point2: toPoint)
        var theta = bearing - fromHeading
        if theta < 0 {
            theta += 360
        }
        return theta
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 2023-04-08
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多