Today we'll use MapKit to create a map in SwiftUI.
Steps:
First, import MapKit framework.
Make the current struct conform to the UIViewRepresentable protocol. With this protocol, UIView objects can be created and managed in SwiftUI.
Implement the makeUIView method in the protocol to initialize and return a MapKit.
Then implement the updateUIView method in the protocol, which is used to set parameters such as geographic coordinates that MKMapView needs to load.
Enable MKMapView to display the user's geographic location.
Set the type of MKMapView map to satellite mode.
Initialize a two-dimensional coordinate, and set the value of latitude and longitude.
Set the zoom ratio of MKMapView to 0.05.
Initialize a coordinate area object as the geographic area to be displayed by MKMapView.
Set the region of the MKMapView.
Source Code:
struct ContentView: UIViewRepresentable {
func makeUIView(context: UIViewRepresentableContext<ContentView>) -> MKMapView {
MKMapView()
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<ContentView>) {
uiView.showsUserLocation = true
uiView.mapType = .satellite
let coordinate2D = CLLocationCoordinate2D(latitude: 59.3273939, longitude: 18.0627908)
let zoomLevel = 0.05
let coordinateSpan = MKCoordinateSpan(latitudeDelta: zoomLevel, longitudeDelta: zoomLevel)
let region = MKCoordinateRegion(center: coordinate2D, span: coordinateSpan)
uiView.setRegion(uiView.regionThatFits(region), animated: true)
}
}
Follow me on:
Comentários