I try to create a map populated with fetched listings from core data. Fetching is perfect, but the map is not centering to listings location. For example all listings are located un USA but my map is showing Romania (my location).
How can i tell the map to show the region of the fetched listings.
import SwiftUI
import UIKit
import MapKit
struct MapView: UIViewRepresentable {
@StateObject var jsonModel = JSONViewModel()
@Environment(\.managedObjectContext) var context
@FetchRequest(entity: Listing.entity(), sortDescriptors:[NSSortDescriptor(keyPath: \Listing.publishdate, ascending: false)])
var results : FetchedResults<Listing>
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) {
@State var center: CLLocationCoordinate2D?
@State var zoom: MKCoordinateSpan
// original
var allAnnotations: [MapAnnotationPin] = []
for data in results {
let title = data.listingtype
let subtitle: String = "\(data.saleprice < 1 ? data.rentprice : data.saleprice) EUR"
let coordinate = CLLocationCoordinate2D(latitude: data.latitude, longitude: data.longitude)
allAnnotations.append(MapAnnotationPin(title: title, subtitle: subtitle, coordinate: coordinate))
}
uiView.annotations.forEach { uiView.removeAnnotation($0) }
uiView.addAnnotations(allAnnotations)
}
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
return MKMapView()
}
}
class MapAnnotationPin: NSObject, MKAnnotation {
let title: String?
let subtitle: String?
let coordinate: CLLocationCoordinate2D
init(title: String?, subtitle: String?, coordinate: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
}
}