MKMapView With Annotations

In this tutorial, we will implement a Mapview and add some annotations with a Callout accessory. Using Swift 5 & Xcode 12.

Sullivan De Carli
Swift Productions
3 min readJan 23, 2021

--

From the author

Difficulty: Beginner | Easy | Normal | Challenging

Environment : Xcode 12 & UIKit

Create a new Xcode project

Open your favourite IDE > App template > Select UIKit life cycle, Storyboard interface and call it MapWithAnnotations.

Xcode > New project

Create the MapView

First, let’s import the MapKit framework, add the line of code below at the top of the ViewController.swift that come up with the project.

Also, declare a mapView over the viewDidLoad method:

Then, create a mapView with constraint to fit the full screen, copy/paste the code below below the viewDidLoad method:

And call the setupMapView() inside the viewDidLoad method, run the app and you will have a map working!

Xcode with the simulator running presenting a map
Screenshot from Xcode

Let’s add some annotations

Let’s create the model for our annotations, create a new swift file and call it Place:

New Swift file from Xcode

Now, copy/paste the following code in it:

We will use this model to create some places to present on our map. Now, create a new Swift file, call it customAnnotationView and copy/paste the following code in it:

Also, register the annotation that we just created inside the viewDidLoad method:

Then, head back to the ViewController.swift file and declare a few places and a region, so we can place our user to the coordinate of the city of Paris at startup.

Now, add these lines of code inside the setupMapView() method:

Run the app and you’re in Paris and there are three annotations on the map, then a callout appear when you click on it!

Screenshot from Xcode

Thanks for reading! I’m always happy to have a chat and collaborate at hello@sullivandecarli.com. Consider subscribing to enjoy unlimited access to my articles and all of Medium through my referral link.

--

--

Sullivan De Carli
Swift Productions

Consultant in iOS Dev at Deloitte. I write about Design & App development. Let’s have a chat at hello@sullivandecarli.com