Moving an MKPointAnnotation in Swift

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.

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.

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.