skip to Main Content

I am following the official tutorial for SwiftUI and have run into the error message ‘Use of unresolved identifier ‘Map’. Even when I copy and and paste the code from the tutorial, it is still giving me the error. I have looked at a few solutions for similar issues and can’t seem to find anything that will work. Code below.

import SwiftUI
import MapKit

struct MapView: View {
    @State private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
        span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
    )

    var body: some View {
        Map(coordinateRegion: $region)
    }
    }

    struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}

I apologise if this is really obvious – but I’m new to Swift/SwiftUI, and can’t see where the issue is coming from. Thanks in advance!

2

Answers


  1. Problem is related to import MapKit. Because Map is defined in MapKit. Please verify if you are able to import MapKit properly

    enter image description here

    Login or Signup to reply.
  2. I also got into trouble in this case.
    So, I make View method using UIViewRepresentable with 2 methods: ‘makeUIView’ and ‘updateUIView’.

    MapView

    import SwiftUI
    import MapKit
    
    struct MapViewUI: UIViewRepresentable {
        func makeUIView(context: Context) -> MKMapView {
             MKMapView(frame: .zero)
        }
        func updateUIView(_ view: MKMapView, context: Context) {
                let coordinate = CLLocationCoordinate2D(
                    latitude: 2.6540427, longitude: 98.8932576)
                let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
                let region = MKCoordinateRegion(center: coordinate, span: span)
                view.setRegion(region, animated: true)
        }
    }
    

    And, You can call your View looks like this

    struct MapPageView: View {
        var body: some View {
            VStack {
                MapViewUI()
                    .frame(height: 300)
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search