Swift MKAnnotationView Rotate

custom mkannotationview swift 4
custom annotation view swift

I am trying to rotate my custom annotation while the coordinate is changed. I can successfully change the coordinate but tried everything to rotate it with no luck. The basic idea is to have a plane and set its direction with rotate.

Here is my code:

import UIKit
import MapKit

class CustomPointAnnotation: MKPointAnnotation {
    var imageName: String!
}

class ViewController: UIViewController, MKMapViewDelegate {

var myAnnot : MKPointAnnotation!
var myDegree = 0.0
var mylat = 41.1036

@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
    super.viewDidLoad()


    mapView.delegate = self
    mapView.mapType = MKMapType.Hybrid
    mapView.showsUserLocation = true
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(animated: Bool) {

    println("HOMESET")
    var homeGPSData = CLLocation(latitude: 41.1036, longitude: 29.3822)
    println(homeGPSData)
    self.myAnnot = MKPointAnnotation()

    myAnnot.coordinate = CLLocationCoordinate2DMake(homeGPSData.coordinate.latitude, homeGPSData.coordinate.longitude)
    myAnnot.title = "Base"
    var rangeCircle : MKCircle  = MKCircle(centerCoordinate: homeGPSData.coordinate, radius: 20000)
    mapView.addOverlay(rangeCircle)
    mapView.addAnnotation(myAnnot)

   var myLoop = NSTimer.scheduledTimerWithTimeInterval(0.0004, target: self, selector: "rotateAndMoveAnnotation", userInfo: nil, repeats: true)


}


func rotateAndMoveAnnotation() {


    var lon = 29.3822

    var homeGPSData = CLLocation(latitude: self.mylat, longitude: lon)

    myAnnot.coordinate = CLLocationCoordinate2DMake(homeGPSData.coordinate.latitude, homeGPSData.coordinate.longitude)

    self.mylat = self.mylat + 0.001
    self.myDegree = self.myDegree + 1




}

func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI }

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {



    let reuseId = "test"

    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    if anView == nil {
        anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)

    }

    anView.image = UIImage(named: "sprite.png")


    return anView
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

It works for me in this way (Yes, I used some code part from your example :) The main thing is to get an annotation view and change (rotate) the image then:

for tempAnnotation in self.mapView.annotations as! [RouteAnnotation]
{
    tempAnnotation.angle = annotations[self.annotationIDs[tempAnnotation.routeId]!].angle
    let annotationView: MKAnnotationView = self.mapView.viewForAnnotation(tempAnnotation)!
    var annotationViewImage = annotationView.image
    annotationViewImage = imageResize(image: UIImage(named:"arrowPin.png")!,sizeChange: CGSizeMake(48, 48)).imageRotatedByangles(CGFloat(tempAnnotation.angle), flip: false)
    annotationView.image = annotationViewImage
}

// Route annotation class

class RouteAnnotation : MKPointAnnotation {
    var angle: Int = 0
    var routeId: Int = 0
}

//UIImage extension

extension UIImage {
public func imageRotatedByangles(angles: CGFloat, flip: Bool) -> UIImage {
    let anglesToRadians: (CGFloat) -> CGFloat = {
        return $0 / 180.0 * CGFloat(M_PI)
    }

    // calculate the size of the rotated view's containing box for our drawing space
    let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
    let t = CGAffineTransformMakeRotation(anglesToRadians(angles));
    rotatedViewBox.transform = t
    let rotatedSize = rotatedViewBox.frame.size

    // Create the bitmap context
    UIGraphicsBeginImageContext(rotatedSize)
    let bitmap = UIGraphicsGetCurrentContext()

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);

    //   // Rotate the image context
    CGContextRotateCTM(bitmap, anglesToRadians(angles));

    // Now, draw the rotated/scaled image into the context
    var yFlip: CGFloat

    if(flip){
        yFlip = CGFloat(-1.0)
    } else {
        yFlip = CGFloat(1.0)
    }

    CGContextScaleCTM(bitmap, yFlip, -1.0)
    CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}
}

Hope, it will help somebody, who have the same problems

Swift MKAnnotationView Rotate, mkannotation callout add multiple annotations to mapview ios swift mapkit swift annotation in swift mkannotationview draw. I am trying to rotate my custom  Annotation views are loosely coupled to a corresponding annotation object, which is an object that conforms to the MKAnnotation protocol. When an annotation’s coordinate point is in the map's visible region, the map view asks its delegate to provide a corresponding annotation view.

I added two lines of codes that commented below and rotation worked perfectly in swift 4 :

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let reuseIdentifier = "pin"
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)

    if annotationView == nil {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
        annotationView?.canShowCallout = true
    } else {

        annotationView?.annotation = annotation
    }

    //these two lines rotated the annotation ---------->>
    var rotationInRadian: Double = .pi
    annotationView?.transform = CGAffineTransform(rotationAngle: rotationInRadian)

    return annotationView
}

just noticed that rotationAngle is a CGFloat number in Radian.

MKAnnotationView Only Rotate the Image property, The simplest way is probably to put the image in a UIImageView, add that as a subview to the MKAnnotationView, and affine that. If you are targeting iOS 5.0 you  SwiftUI’s rotationEffect () modifier lets us rotate views freely, using either degrees or radians. For example, if you wanted to rotate some text by -90 degrees so that it reads upwards, you would use this: Text("Up we go") .rotationEffect(.degrees(-90)) If you prefer using radians, just pass in .radians () as your parameter, like this: Text("Up we go") .rotationEffect(.radians(.pi))

Found a dirty solution.. just added the following line to viewforAnnotation method:

anView.boundsRotation = myRotateAngle

Custom annotation image rotates only at the beginning of the , Custom annotation image rotates only at the beginning of the Program (Swift- iOS​). Question MKMapView!, viewForAnnotation annotation: MKAnnotation!) This Swift code example will demonstrate how to add custom image to a MKAnnotationView. The code example below will cover: Import CoreLocation framework, Create MKMapView programmatically, Add MapView as subview Determine user’s current location Set current region on the map Create MKPointAnnotation with custom title Drop MKPointAnnotation as a Pin at user’s current location Create…

ARFlightTracker-iOS-Swift/ARFlightTracker-iOS-Swift , MKAnnotation. An interface for associating your content with a specific map location. SDKs. iOS 3.0+; macOS 10.9+; Mac Catalyst 13.0+; tvOS 9.2+; watchOS 2.0  Switch to the “ViewController.swift” file and implement the following code before the class closing bracket: func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { // 1 if view.annotation is MKUserLocation { // Don't proceed with custom callout return } // 2 let starbucksAnnotation = view.annotation as!

MKAnnotation, iOS 13.0+; Xcode 11.3+ An annotation object conforms to the MKAnnotation protocol and manages the data for the annotation, such as the coordinate , title  Rotate AnnotationView, в частности, координаты с использованием Swift. Я создал приложение apple map и обработал карту местоположения с помощью MKCircle и MKPolyline.

Annotating a Map with Custom Data, Now I'm trying to find a way to rotate that MKAnnotationView image in my custom UserLocationAnnotationView ? Thanks for your help. iOS. Add custom pin on map-view or Map-kit (Swift 4 + Xcode 9.2) Swift Tutorials. MKAnnotationView. Detect which pin or annotation is tapped by user. Swift Tutorials:

Comments
  • Nice one, there's one caveat though: the pop-up window will also rotate :)
  • There's no property like that. Can you please elaborate ?