首页 > 解决方案 > 无法在指南针 Swift ios 中指向正确的位置

问题描述

我正在开发一个指南针,它可以从我当前的位置指向其他位置,但是在实现它之后,我注意到每次选择一个新的目标位置去或指向时它总是指向同一个方向。

  func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    let heading = newHeading.magneticHeading
    let headingR = Measurement(value: newHeading.trueHeading, unit: UnitAngle.degrees).converted(to: .radians).value

    // To know if the Data that our device is correct, The "horizontalAccuracy" value should be grater then ZERO for valid GPS coordinate Data
    if heading < 0 {return}
    // Get the heading(direction)
    if(heading == -1){
        print("no location")
    }
    self.directionAngel = Double(self.getBearingBetweenTwoPoints1(latDestination: self.desiredLatit,lonDestination: self.desiredLongit))

    let north = -1 * heading.degreesToRadians
    UIView.animate(withDuration: 1) {
        self.imageView.transform = CGAffineTransform(rotationAngle: CGFloat(north))
        self.directionArrowView.transform = CGAffineTransform(rotationAngle: CGFloat(self.directionAngel.degreesToRadians - headingR))
    }
    self.updateHeading(heading: heading)
}


  private  func getBearingBetweenTwoPoints1(latDestination:Double,lonDestination:Double) -> Double {
      
    let lat1 = getMyLocation().latitude.degreesToRadians
    let lon1 = getMyLocation().longitude.degreesToRadians
    
    let lat2 = latDestination.degreesToRadians
    let lon2 = lonDestination.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.0){
          radiansBearing += 2 * Double.pi
      }
    return radiansBearing
  }
let locationManager: CLLocationManager = {
    $0.requestAlwaysAuthorization()
    $0.requestWhenInUseAuthorization()
    $0.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    $0.startUpdatingLocation()
    $0.startUpdatingHeading()
    return $0
}(CLLocationManager())

标签: iosobjective-cswiftlocationcompass

解决方案


推荐阅读