I've over 1000 different annotations that are shown on a MKMapView and depending on where the user is (visibleMapRect) loads in a new set of annotations based on region.center. The problem I'm facing is the MKMapView becomes slow at loading in the annotations
I've tried separating out the annotation types into separate loading methods and calling each one separately on a serial queue and it still loads in the annotations really slow (several seconds)
The method below is called from func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {}
let region = MKCoordinateRegion(center: self.map.centerCoordinate, span: MKCoordinateSpan(latitudeDelta: 0, longitudeDelta: 0))
let group = DispatchGroup()
let queue = DispatchQueue(label: "reload-annotations", attributes: .background)
queue.async(group: group) {
self.firstViewModel.load(coordinates: region.center)
}
queue.async(group: group) {
self.secondViewModel.load(coordinates: region.center)
}
queue.async(group: group) {
self.thirdViewModel.load(coordinates: region.center)
}
group.notify(queue: queue) {
let annotations = self.map.annotations
for annotation in self.firstViewModel.data {
if !annotations.contains(where: { $0.title == annotation.title }) {
DispatchQueue.main.async {
self.map.addAnnotation(annotation)
}
}
}
for annotation in self.secondViewModel.data {
if !annotations.contains(where: { $0.title == annotation.title }) {
DispatchQueue.main.async {
self.map.addAnnotation(annotation)
}
}
}
for annotation in self.thirdViewModel.data {
if !annotations.contains(where: { $0.title == annotation.title }) {
DispatchQueue.main.async {
self.map.addAnnotation(annotation)
}
}
}
}