0

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
    }
}
  • In method `updateUIView` call `uiView.setRegion(myFavoriteRegion, animated: true)` – Gerd Castan May 05 '21 at 14:59
  • Thank you for the answer! Further more i want to tap on the pin to go on the listing detail, orto show a small view on top of the map. How can i achive this? – Marius Geageac May 06 '21 at 03:56
  • If you don't want to display too much, a callout is what you are looking for https://www.raywenderlich.com/7738344-mapkit-tutorial-getting-started – Gerd Castan May 06 '21 at 14:12

1 Answers1

0

Thank you Gerd!

final code to get it work:

let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)     
let myFavoriteRegion = MKCoordinateRegion(center: coordinate, span: span)
uiView.setRegion(myFavoriteRegion, animated: true)