William O'ConnorBlog

Moving an MKPointAnnotation in Swift

02 April, 2018 - 3 min read

If you've been working with MapKit, you may have had to go about moving annotations from one point to another. It's easy to simply remove an annotation and add a new annotation in the second coordinate, but this way will involve you having to set the title and subtitle again. Visually this won't look as appealing.

What you'll want to do first, is to create a new project in xCode and head straight into your ViewController.

Start by importing MapKit.

import MapKit

We’re now going to add a variable to store our annotation.

private let myAnnotation = MKPointAnnotation()

In our viewDidLoad() function will exist the rest of the code.

We’ll create two variables to hold our first and second coordinate. Set the coordinates to whatever, I’ll be using my home of Dublin as my start coordinate.

let startPosition = CLLocationCoordinate2D(latitude: 53.3498, longitude: -6.2603)
let destinationPosition = CLLocationCoordinate2D(latitude: 52.3369, longitude: -6.4633)

When we open the app for the first time, let’s have the map center be our start coordinate so we don’t have to go looking for our two points.

let region = MKCoordinateRegionMakeWithDistance(startPosition, 100000, 100000)
mapView.setRegion(region, animated: true)

We’ll add our annotation directly below this snippet.

myAnnotation.coordinate = startPosition
mapView.addAnnotation(myAnnotation)

Now that the code for the map is done. Let’s add the MKMapView to your storyboard and set the constraints to our ViewController. I’ve set my constraints to zero so the map will take up the full width and height of the ViewController. Be sure to also link your MKMapView to the mapView outlet created earlier and also to link your delegate to your ViewController.

Storyboard of MkPointAnnotation

Now to create the function that will move our annotation. For the purpose of the demo, we’ll add a timer to run this function after 5 seconds from when the user launches the app. Head back to the ViewController and add the following code.

weak var timer: Timer?

func movePosition() {
    // Set timer to run after 5 seconds.
    timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { [weak self] _ in
        // Set animation to last 4 seconds.
        UIView.animate(withDuration: 4, animations: {
            // Update annotation coordinate to be the destination coordinate
            self?.myAnnotation.coordinate = destinationPosition
        }, completion: nil)
    }
}

When you build and run the app, you should now be able to see your MKPointAnnotation move from one coordinate to another like in the video below.

I’ve made the source of this app available on my GitHub if you prefer to clone the project with an MIT license.