MapKit SwiftUI

Aymen Afia
3 min readDec 28, 2020

This year we had a great addition in SwiftUI, the integration for frameworks that Apple provides us like MapKit.

As you can see all you need to do is constructing Map view and passing it the binding for an instance of MKCoordinateRegion.

SwiftUI will update the binding $region as soon as the user changes the visible region on the map by zoom or pan gestures.

Also we can change the camera by passing a new region state value.

As you can see above, i created a button with “zoom” title, as soon as we click on it, it trigger the animation of span changing which allows us to change the visible boundaries of the map with animation using the animation system of SwiftUI.

The customization points that map view provides us:

Let’s discuss the customization points one by one.

  1. coordinateRegion represents the currently visible region of the map view. You can easily change it by updating the value of your binding. Remember that it is an animatable parameter of the view.
  2. interactionModes allows us to set allowed gestures for our map view. For example, it might be only zoom or pan gestures. In our case, we use all the available gestures to interact with the map.
  3. showsUserLocation is the boolean parameter that allows us to control whenever we want to show the user’s current location on the map or not. Remember that you have to request permission to access the location.
  4. userTrackingMode is the way to configure map tracking mode. It describes whenever we want to follow the user as soon as location changes.

There is another initializer for the map view that accepts MKMapRect instead of MKCoordinateRegion to control the visible part of the map.

Annotations:

SwiftUI provides us MapAnnotation struct that we can use to build our annotation view. It accepts the center coordinate of the annotation, its anchor point, and the @ViewBuilder closure to create a custom view.

SwiftUI also provides us two standard views that we can use to display our points of interest. These are MapMarker and MapPin.

I am very happy with SwiftUI MapKit!!!!! , but it still miss a lot of featues like tapping MapAnnotations.

--

--