MapKit lesson in SwiftUI giving compiler errors

395 Views Asked by At

I'm following the "Creating and Combining View" lesson on SwiftUI. However when I tried to use the MapKit, my simulator doesn't work as it is supposed to work (which is show the pin at the assigned Coordinates)

import SwiftUI
import MapKit


struct MapView: View {
    var body: some View {
        Map(initialPosition: .region(region))
    }


    private var region: MKCoordinateRegion {
        MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
            span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
        )
    }
}


#Preview {
    MapView()
}

What I expected to happen: enter image description here

What actually happened enter image description here

image

2

There are 2 best solutions below

0
On

You need to update your Xcode to version 15.0.1. If you don't see available Xcode updates, you need to update your MacOS first to Sonoma 14.0.

Maybe there are other solutions, but this one worked for me.

0
On

Please use the Map and init function as below.

import SwiftUI
import MapKit

struct MapView: View {
    var body: some View {
        Map(coordinateRegion: .constant(region), interactionModes: [])
    }
    
    private var region: MKCoordinateRegion {
        MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
            span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
        )
    }
}

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