Show Map in SwiftUI

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

With SwiftUI, displaying maps in your app is made easy through the use of the Map view. It allows for seamless integration of maps within the rest of your app’s views and gives you control over various aspects such as user interactions, annotations, and more.

To begin, you’ll need to create a state that tracks the coordinates to be displayed on the map. This can be done using the MKCoordinateRegion class, which takes a latitude and longitude pair for the center of the map and a MKCoordinateSpan to control the area visible on the map.

For example, the following code will create a map centered on the city of New York:

import MapKit

struct ContentView: View {
    @State private var newYourRegion = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 40.730610, longitude: -73.935242),
        span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
    )

    var body: some View {
        Map(coordinateRegion: $newYourRegion)
            .ignoresSafeArea()
    }
}

As the user interacts with the map and scrolls around, the coordinates displayed on the map will automatically update according to the region state you have created. You can also control how much interaction the user has with the map by providing a MKMapViewInteraction parameter to your Map view. For example, if you want to allow the user to zoom in and out, but not pan to new locations, you can set the interactionMode to .zoom.

Additionally, you can enable the display of the user’s location on the map by setting the showsUserLocation parameter to true. The userTrackingMode can also be set to .follow which will automatically follow the user’s location as they move.

However, keep in mind that in order to access the user’s location, you will need to request and receive location permission from the user. This means adding the necessary values to the Info.plist file, such as “Privacy – Location When In Use Usage Description” and “Privacy – Location Always and When In Use Usage Description”. You will also need to create an instance of CLLocationManager and request authorization through it, using a method such as requestAlwaysAuthorization().

import MapKit

struct ContentView: View {
    @State private var newYourRegion = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 40.730610, longitude: -73.935242),
        span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
    )

    var body: some View {
        Map(coordinateRegion: $newYourRegion, showsUserLocation: true, userTrackingMode: .constant(.follow))
          .ignoresSafeArea()
    }
}

Using UIViewRepresentable and MapKit

In order to display a map in a SwiftUI app, one of the options you can use is the MapKit framework provided by Apple. This framework provides a MapView struct which can be used as any other SwiftUI view.

To display a map in SwiftUI using MapKit, you first need to import the framework.

Then, create a struct that conforms to the UIViewRepresentable protocol and defines the behavior of the map view.

import MapKit

struct MapView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ view: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(
            latitude: 34.011286, longitude: -116.166868)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)
    }
}

Using MapView from SwiftUI which is introduced in iOS 14 and macOS 11, it is a native MapView that allows you to show map views directly in SwiftUI and you can use it without any additional wrapper.

import MapKit
import SwiftUI

struct MapView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ view: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(
            latitude: 34.011286, longitude: -116.166868)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)
    }
}

struct ContentView: View {
    var body: some View {
        MapView()
    }
}

Using MKMapView from MapKit and wrap it into UIViewRepresentable as I’ve mentioned before. we can use the MapView struct in a SwiftUI view and set the region to display on the map and can set the center of the map to a specific location and also set the span to zoom in/out of the map

Using a third-party library, such as Google Maps SDK for iOS or MapBox SDK for iOS. These libraries provide their own map views that can be wrapped in a UIViewRepresentable wrapper and used in a SwiftUI app.

Keep in mind that in order to use the map, you need an internet connection. You should also check the terms and conditions of the service before using it in your app.



✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.