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.
We’re now going to add a variable to store our annotation.
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.
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.
We’ll add our annotation directly below this snippet.
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.
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.