Mapkit in SwiftUI

Samir Rana
2 min readJun 11, 2023

--

To use MapKit in SwiftUI with latitude and longitude coordinates, you can follow these steps:

  1. Import the MapKit framework at the top of your SwiftUI file:
import MapKit
  1. Create a struct or class that conforms to the UIViewRepresentable protocol. This will allow you to wrap the MKMapView and use it in SwiftUI. Here's an example implementation:
struct MapView: UIViewRepresentable {
let latitude: Double
let longitude: Double

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

func updateUIView(_ view: MKMapView, context: Context) {
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

let span = MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: coordinate, span: span)

view.setRegion(region, animated: true)

let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
view.addAnnotation(annotation)
}
}

In the updateUIView method, we create a CLLocationCoordinate2D object using the given latitude and longitude. Then, we define a MKCoordinateSpan for the region we want to display on the map. Next, we create a MKCoordinateRegion using the coordinate and span, and set it on the map view using setRegion. Finally, we create a MKPointAnnotation and add it to the map view.

  1. In your SwiftUI view, you can now use the MapView struct and pass the latitude and longitude values:
struct ContentView: View {
let latitude: Double = 37.33233141
let longitude: Double = -122.0312186

var body: some View {
MapView(latitude: latitude, longitude: longitude)
.frame(height: 300)
}
}

In this example, we’re creating a MapView with latitude 37.33233141 and longitude -122.0312186.

That’s it! You should now see a map view with a pin representing the given latitude and longitude in your SwiftUI preview or when running the app.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Samir Rana
Samir Rana

Written by Samir Rana

iOS Developer and Machine learning Enthusiastic

No responses yet

Write a response