我正在尝试添加带有始终指向自定义方向的自定义图片的MKAnnotation。 MKAnnotationView的image属性没有提供关于此主题的清晰信息。
我有两个主要要求:
1)相机必须遵循用户的标题
2)箭头必须始终相对于真北指向30°
这是我的最低测试代码:
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
let targetDirection: CLLocationDirection = 30.0
var headingAnnotationView: MKAnnotationView?
var currentHeading: CLLocationDegrees = 0.0
var mapView: MKMapView!
private let id = "FixedRotation"
let targetCoordinates = CLLocationCoordinate2D(latitude: 48.847229, longitude: 2.361474)
override func viewDidLoad() {
super.viewDidLoad()
self.mapView = MKMapView(frame: UIScreen.main.bounds)
self.mapView.delegate = self
self.view.addSubview(self.mapView)
let annotation = MKPointAnnotation.init()
annotation.title = id
annotation.coordinate = self.targetCoordinates
self.mapView.addAnnotation(annotation)
self.mapView.setRegion(MKCoordinateRegion(center: self.targetCoordinates, latitudinalMeters: 1000, longitudinalMeters: 1000), animated: false)
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingHeading()
}
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
guard let annotationView = views.last else { return }
if annotationView.reuseIdentifier == id {
self.headingAnnotationView = annotationView
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView: MKAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: id) ?? MKAnnotationView.init(annotation: annotation, reuseIdentifier: id)
let image = UIImage(named: "guidance-arrow")!
annotationView.image = image
return annotationView
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
self.currentHeading = newHeading.trueHeading
let rotationRad = atan2(self.mapView.transform.b, self.mapView.transform.a)
DispatchQueue.main.async {
self.mapView.camera.heading = CLLocationDirection(rotationRad)
self.headingAnnotationView?.transform = CGAffineTransform(rotationAngle: CGFloat(targetDirection.degreesToRadians) - rotationRad)
}
}
}
我不知道如何解决它。