【发布时间】:2022-11-24 03:41:51
【问题描述】:
我的应用程序请求 JSON 数据(纬度、经度和有关某个地方的其他信息),然后以可点击注释的形式将它们显示在地图上。我收到了大约 30,000 个,所以你可以想象,该应用程序可能会有点“滞后”。
我认为最适合该应用程序的解决方案是仅在特定缩放级别上显示这些注释(例如,当用户缩放以便一次只能看到一个城市时,注释将显示)。由于它们很多,显示所有 30,000 个可能会使应用程序崩溃,这就是为什么我也旨在仅显示靠近用户放大位置的那些。
下面的代码立即显示所有缩放级别的所有注释。有没有办法让它适应我上面描述的事情?
struct Map: UIViewRepresentable {
@EnvironmentObject var model: ContentModel
@ObservedObject var data = FetchData()
var locations:[MKPointAnnotation] {
var annotations = [MKPointAnnotation]()
// Loop through all places
for place in data.dataList {
// If the place does have lat and long, create an annotation
if let lat = place.latitude, let long = place.longitude {
// Create an annotation
let a = MKPointAnnotation()
a.coordinate = CLLocationCoordinate2D(latitude: Double(lat)!, longitude: Double(long)!)
a.title = place.address ?? ""
annotations.append(a)
}
}
return annotations
}
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
// Show user on the map
mapView.showsUserLocation = true
mapView.userTrackingMode = .followWithHeading
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
// Remove all annotations
uiView.removeAnnotations(uiView.annotations)
// HERE'S WHERE I SHOW THE ANNOTATIONS
uiView.showAnnotations(self.locations, animated: true)
}
static func dismantleUIView(_ uiView: MKMapView, coordinator: ()) {
uiView.removeAnnotations(uiView.annotations)
}
// MARK: Coordinator Class
func makeCoordinator() -> Coordinator {
return Coordinator(map: self)
}
class Coordinator: NSObject, MKMapViewDelegate {
var map: Map
init(map: Map) {
self.map = map
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Don't treat user as an annotation
if annotation is MKUserLocation {
return nil
}
// Check for reusable annotations
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: Constants.annotationReusedId)
// If none found, create a new one
if annotationView == nil {
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: Constants.annotationReusedId)
annotationView!.canShowCallout = true
annotationView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
} else {
// Carry on with reusable annotation
annotationView!.annotation = annotation
}
return annotationView
}
}
}
一段时间以来一直在寻找答案,但没有发现任何有效的方法。我想象有一种方法可以获得可见的地图矩形,然后在地图结构中对其进行条件处理,但不知道该怎么做。感谢您阅读到这里!
【问题讨论】:
标签: swiftui mapkit mapkitannotation