Display a Map View in SwiftUI


Adding Map in the app is a cool thing. In this tutorial, I am going to show you how to display a map view in SwiftUI using MapKit framework.

MapKit makes it easy to show a map in our iOS app. To add a map for a specific location by providing latitude and longitude is quite easy.

To follow this tutorial, we have to import the MapKit framework:

import MapKit

Now see the syntax for adding the map in our SwiftUI view using the Map view:

Map(coordinateRegion: Binding<MKCoordinateRegion>)

In the above code, you can see that, it needs a state variable to store the MKCoordinateRegion. It will store the location information.

The syntax for the MKCoordinateRegion is given below:

MKCoordinateRegion(center: CLLocationCoordinate2D, span: MKCoordinateSpan)

Below is given how we can create an MKCoordinateRegion type state variable:

@State private var mapRegion: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 42.6, longitude: -113.78), span: MKCoordinateSpan(latitudeDelta: 0.3, longitudeDelta: 0.3))

In the above program, we have set our coordination to the CLLocationCoordinate2D() method. The MKCoordinateSpan() is used to set the zoom level. In the MKCoordinateSpan(), you can see latitudeDelta and longitudeDelta parameters. Any one of these will be used. If the values of latitudeDelta and longitudeDelta are different, then the one with a higher value will be used.

Now add the Map view:

Map(coordinateRegion: $mapRegion)

The complete code

Now let’s see the complete code that will show the map in our view:

import SwiftUI
import MapKit

struct ContentView: View {
    
    @State private var mapRegion: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 42.6, longitude: -113.78), span: MKCoordinateSpan(latitudeDelta: 0.3, longitudeDelta: 0.3))

      var body: some View {
          
          Map(coordinateRegion: $mapRegion)
          
      }
    
}

As you can see, we have used the Map() view and provided the location as the parameter. We bind the mapRegion state variable to the Map view coordinateRegion. The mapRegion variable contains the MKCoordinateRegion type data that has the location information by latitude and longitude.

If you run our program, you will able to see the map as you can see below:

SwiftUI Map

That’s it. This is how we can display the map of a specific location using the MapKit in SwiftUI.