a swiftui map in swift

To display a map in SwiftUI, we can use the MapKit framework provided by Apple. Conforming to the MapKit framework, we can add maps and annotations to a SwiftUI view by using an MKMapView. Here is an example code snippet to display a map with a pin point annotation in SwiftUI:

main.swift
import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {
        
    let annotation = MKPointAnnotation()
    
    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        let coordinate = CLLocationCoordinate2D(latitude: 37.7793, longitude: -122.419)
        let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        mapView.setRegion(region, animated: true)

        annotation.coordinate = coordinate
        mapView.addAnnotation(annotation)

        return mapView
    }
    
    func updateUIView(_ view: MKMapView, context: Context) {
        
    }
    
}

struct ContentView: View {
    var body: some View {
        MapView()
    }
}
781 chars
32 lines

This MapView struct conforms to the UIViewRepresentable protocol which allows us to return a UIKit-based MKMapView as the MapView SwiftUI view.

Inside makeUIView, we set up the map view to center on the specified coordinate with a zoom level of 0.1 degrees in both directions. We also set up a MKPointAnnotation to show a pin point at the specified coordinate.

Finally, we add the MKPointAnnotation to the MKMapView and return it from the makeUIView method to be displayed in the SwiftUI view.

gistlibby LogSnag