iOS MKMapView - Animate map Pins
Asked Answered
B

1

1

MKAnnotationView animation in iOS using Swift 4

Add animation to pins for adding pins to map smoothly. While adding pins to map, it is not smooth or it has no animation effect. Is there any simple solution to achieve this?

Belton answered 28/3, 2018 at 14:41 Comment(1)
Personally, I think the best solution is to encapsulate this animation logic in a MKAnnotationView type, not bury it in the map view delegate. E.g., https://mcmap.net/q/129547/-how-do-i-animate-mkannotationview-drop. The annotation view should do the animation.Struck
B
1

I tried it with the simple code

enter image description here

I have created a simple code to fix this issue in swift 4.

Here is my code,

Override your viewForAnnotaion method something like this

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

    var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin")

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

    annotationView?.canShowCallout = false

    guard !annotation.isKind(of: MKUserLocation.self) else {
        //for the custom image on current location
            annotationView?.image = #imageLiteral(resourceName: "currentLocationPin")
            return annotationView
    }

 annotationView.image = UIImage(named: "pinGreen")

    let scaleTransform = CGAffineTransform(scaleX: 0.0, y: 0.0)  // Scale
    UIView.animate(withDuration: 0.2, animations: {
        annotationView?.transform = scaleTransform
        annotationView?.layoutIfNeeded()
    }) { (isCompleted) in

        // Nested block of animation
        UIView.animate(withDuration: 0.3, animations: {
            annotationView?.alpha = 1.0
            annotationView?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            AnimationUtility.viewSlideInFromBottom(toTop: annotationView!)
            annotationView?.layoutIfNeeded()
        })
    }

    return annotationView
}

For AnimationUtility class refer this link

https://mcmap.net/q/131301/-how-to-animate-collection-view-cells-using-hero-animation-closed

This code adds pins to map with smooth animation.

Belton answered 28/3, 2018 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.