MapView SwiftUI With AnnotationView and Coordinator

Michael Abadi S.
Mac O’Clock
Published in
4 min readAug 17, 2020

--

SwiftUI is very powerful for building an interactive UI at a fast pace. However, there are a couple of limitations still there such as some native API from UIKit like MKMapView from MapKit or search bar and other UIKit API. I will provide a tutorial for making a MapView in SwiftUI by using UIViewRepresentable as well as putting callback to the SwiftUI if we have clicked the annotation.

Some quick knowledge about several items below:

  1. UIViewRepresentable : A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy
  2. Coordinator : A SwiftUI view that represents a UIKit view controller can define a Coordinator type that SwiftUI manages and provides as part of the representable view’s context
  3. MapKit : UIKit API for Map behavior such as MKMapView and Annotation View and other native Map behavior

First of all, we need to make our Model for displaying the item inside the map. The model we can put title and it’s coordinate (latitude and longitude).

final class Checkpoint: NSObject, MKAnnotation {
let title: String?
let countryCode: String?
let coordinate: CLLocationCoordinate2D

init(title: String?, countryCode: String?, coordinate: CLLocationCoordinate2D) {
self.title = title
self.countryCode = countryCode
self.coordinate = coordinate
}
}

--

--