Mert Köksal
Mert Köksal

Reputation: 901

MapMarker from Binding SwiftUI

I am trying to show a map marker on a map from selectedBus var's longitude and latitude but I just can not solve it.

With below code I am getting error Static method 'buildBlock' requires that 'MapMarker' conform to 'View'

import SwiftUI
import MapKit
import CoreLocation

struct BusView: View {
    @Binding var selectedBus : Bus
    @State private var coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 28), span: MKCoordinateSpan(latitudeDelta: 50, longitudeDelta: 50))

       var body: some View {
           Map(coordinateRegion: $coordinateRegion)
           MapMarker(coordinate: CLLocationCoordinate2D(latitude: selectedBus.location?.latitude ?? 0, longitude: selectedBus.location?.longitude ?? 0), tint: .red)
           
       }
}



    struct Bus: Decodable, Hashable {
    let remainingTime: Int?
    let plate: String?
    let routeCode: String?
    let icon: String?
    let location: Location?
}

struct Location: Decodable, Hashable {
    
    let latitude: Double?
    let longitude: Double?
}

Upvotes: 1

Views: 319

Answers (1)

Yrb
Yrb

Reputation: 9665

You need to have an array of annotations(I just called is annotations) to use a MapMarker, as that is just the View that shows where an annotation is. Your var body should look like this:

   var body: some View {
    Map(coordinateRegion: $coordinateRegion, annotationItems: annotations) {
       MapMarker(coordinate: CLLocationCoordinate2D(latitude: selectedBus.location?.latitude ?? 0, longitude: selectedBus.location?.longitude ?? 0), tint: .red)
       }
   }

Upvotes: 1

Related Questions