Home > Software design >  I can't print the api I pulled on the mapmarker
I can't print the api I pulled on the mapmarker

Time:04-07

I pulled the data from the mapmarker, when I print, I see all of them, but I cannot get them from the example ( quake.latitude ). Error. Even if it was a list, I had taken it by typing "(quakes) { quake in" in parentheses, but now I don't know how to do it through mapview.

struct MapAnnotationsView: View {

@State var quakes: [EarthQuake] = []

@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 38.9520281, longitude: 35.6980142), span: MKCoordinateSpan(latitudeDelta: 30, longitudeDelta: 10))

let placeArray: [Place] = [Place(title: {quake.latitude}, coordinate: CLLocationCoordinate2D(latitude: 37.8008, longitude: 27.2465))]

var body: some View {
    Map(coordinateRegion: $region, annotationItems: placeArray) { annotation in
        // This makes a generic annotation that takes a View
        MapAnnotation(coordinate: annotation.coordinate) {
            // This is your custom view
            AnnotationView(placeName: annotation.title)
        }
    } .onAppear {
        Api().getEarthQuake { (quakes) in
            self.quakes = quakes
            
        }
    }
}
}

Error code screenshot

CodePudding user response:

Try this:

struct MapAnnotationsView: View {

@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 38.9520281, longitude: 35.6980142), span: MKCoordinateSpan(latitudeDelta: 30, longitudeDelta: 10))

@State private var placeArray: [Place] = []

var body: some View {
    Map(coordinateRegion: $region, annotationItems: placeArray) { annotation in
        // This makes a generic annotation that takes a View
        MapAnnotation(coordinate: annotation.coordinate) {
            // This is your custom view
            AnnotationView(placeName: annotation.title)
        }
    } .onAppear {
        Api().getEarthQuake { (quakes) in
            let tempArray = quakes.map{ quake in
                 Place(title: "\(quake.latitude)", coordinate: CLLocationCoordinate2D(latitude: 37.8008, longitude: 27.2465))
            }
            self.placeArray = tempArray
        }
    }
}
}

As this is not a reproducible example there might be some typos involved here which you would have to address yourself.


Explenation: Your property placeArray cannot depend on another property. To get an array of places to provide to your map you need to create these after you loaded the earthquakes from your API and assign them. Using a @State var ensures your View gets updated.

  • Related