Swift 4 iOS 11.x
运行此代码...以获取GPS方位并希望将其与指南针设置相结合。
func getBearing(toPoint point: CLLocationCoordinate2D, longitude:Double, latitude: Double) -> Double {
func degreesToRadians(degrees: Double) -> Double { return degrees * Double.pi / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / Double.pi }
let lat1 = degreesToRadians(degrees: latitude)
let lon1 = degreesToRadians(degrees: longitude)
let lat2 = degreesToRadians(degrees: point.latitude);
let lon2 = degreesToRadians(degrees: point.longitude);
let dLon = lon2 - lon1;
let y = sin(dLon) * cos(lat2);
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
let radiansBearing = atan2(y, x);
return radiansBearing
}
要获得弧度值,我需要前往..
angle2U = self.getBearing(toPoint: goFigure, longitude: (self.locationManager.location?.coordinate.longitude)!, latitude: (self.locationManager.location?.coordinate.latitude)!)
然后这段代码用它来转换图像并给我一个相对于我指向的方向。我在这次调用中使用了从这个angle2U得到的值...
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading) {
direction2G = CGFloat(heading.magneticHeading * Double.pi/180)
DispatchQueue.main.async {
let direction2GN = CGFloat(self.angle2U) - direction2G
let tr2 = CGAffineTransform.identity.rotated(by: direction2GN)
self.degreeAngle.text = String(describing: direction2GN)
self.directionImage.transform = tr2
}
我认为哪些是有效的,但我想与那些知道他/她正在做什么的人核实,因为我至少部分地从试错中获得了这个,我不确定数学。