This tutorial was first published on my blog.

At WWDC 2020, Apple announced various improvements to their frameworks and SwiftUI was at the front of the line to receive new API and existing API refinements. In this tutorial, we’ll learn how crazy simple it is to integrate MapViews using the MapKit framework, which is now native, in your SwiftUI Applications. Let’s go

Please note that this tutorial requires you to have Xcode 12 but doesn’t require that you have macOS Big Sur installed in your machine.

The first thing we have to do is to import MapKit in your current SwiftUI file.
Let us create a VStack that will show the map in a nice rounded view along with the name of the place below it. For this tutorial we’ll use San Francisco’s Bay Area’s coordinates which, according to Google is at 37.8272° N, 122.2913° W. This translates to:\

  • Latitude- 37.8272
  • Longitude- -122.2913 (Negative since it’s in the Western Hemisphere of the planet)

Now with this information let’s get into the rather simple code. Below the struct ContentView: View declaration make a new State variable that will be of type MKCoordinateRegion. The constructor that we’ll be using will consist of 2 properties:

  • Center- This is where the MapView will be centered
  • Span- The amount of region shown on the map. The bigger the number the more of the area is shown. This span will change depending on the user interacting with the MapView.
    The coordinateRegion State variable will now look like this:

Making the View

Our view is quite simple. It’s a MapView and a Text with some view modifiers added to it.
Create a VStack and inside that create a Map() (yep, a SwiftUI Map is just called a Map. It can’t get simpler than this). The Map view has a few contractors but for this simple tutorial, we’ll be using the one with the coordinateRegion parameter. In this parameter pass the binding variable that you just created. You can add some view modifiers to shape the MapView any way that you like or use the code that I’ve written below:

This creates a MapView with 300x400 as it’s frame, adds in a corner radius, and adds a slight drop shadow of radius 4 just to give it some cool aesthetics because why not.

Aesthetics

The main part of the tutorial is over. If you’d like to add the “Bay Area, California” Text below the MapView simply add in a Text view and add in some custom view modifiers just like this:

A side note- I really like that the new iOS and macOS design language have moved towards the rounded font design and that is what we’re using in this tutorial. If you want the big title on the top wrap the whole View in a NavigationView and add in thenavigationTitle modifier.

Your whole code should now look like this:

A simple MapView made entirely with SwiftUI

Thank you for reading. If you have any doubts please feel free to @ me on twitter @SwapnanilDhol

•21 • WWDC ’21, ’20, ’19 Scholar •GSoC 2020 with VLC •iOS Engineer •Airplane and Space Enthusiast