iOS

Create MapView in swiftui? How to show marker on MapView

What is MapView in swiftui

What is MapView ?

MapView is the SwiftUi Object that can display a map interface in the iOS App. It is same to the Maps Application provided by the iOS platform. MapView is a instance of the MKMapView class. That is including all the UIView class. In this iOS article  we are create a Map and showing a marker on map using lat long.

What is MapKit ?

Also i am using MapKit to provided your App a sense of place with the location information. You can used MapKit in swiftui to

  • Embed maps directly into your app’s windows and views.
  • Add annotations and overlays to a map to call out points of interest.
  • Add LookAround capabilities to enable users to explore locations at street level.
  • Respond to user interactions with well known points of interest, geographical features, and boundaries.
  • Provide text completion to make it easy for users to search for a destination or point of interest.

 

MapView in swiftui  And show location marker.

Let’s Start to make a iOS Application to show Map and a location marker on MapView. For showing a Marker we need location Lat, Long so that we show the Marker on Map.

MapView in SwiftUI Example Source Code

 

import SwiftUI
import MapKit

struct Marker: Identifiable {
    let id = UUID()
    var location: MapMarker

}

struct MapView: View {

    @State private var coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 28.4595, longitude: 77.0266), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.001))

    
    init() {
            MKMapView.appearance().mapType = .satellite
        }


    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 28.4595, longitude: 77.0266), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
        let markers = [Marker(location: MapMarker(coordinate: CLLocationCoordinate2D(latitude: 28.4595, longitude: 77.0266), tint: .red))]

    
        var body: some View {
            Map(coordinateRegion: $coordinateRegion, showsUserLocation: true,
                annotationItems: markers) { marker in
                marker.location

            }.edgesIgnoringSafeArea(.all)  

        }      
}

#if DEBUG

struct MaoView_Previews: PreviewProvider {

    static var previews: some View {
        MapView()
    }
}

 

Read More Tutorial