【发布时间】:2021-05-05 13:53:57
【问题描述】:
我尝试创建一个地图,其中填充了从核心数据中提取的列表。抓取是完美的,但地图没有以列表位置为中心。 例如,所有列表都位于美国,但我的地图显示罗马尼亚(我的位置)。
如何让地图显示获取列表的区域。
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
}
}
【问题讨论】:
-
在方法
updateUIView调用uiView.setRegion(myFavoriteRegion, animated: true) -
感谢您的回答!此外,我还想点击图钉以查看列表详情,或在地图顶部显示一个小视图。我怎样才能做到这一点?
-
如果你不想显示太多,标注就是你要找的raywenderlich.com/7738344-mapkit-tutorial-getting-started
标签: core-data swiftui mapkit uiviewrepresentable