I am trying to make an Uber clone in which there are a lot of annotation for passengers and driver. I want to only load and show the annotation which belong to the map region currently displayed, so that all the annotations are not added to the mapview and does not consume much memory.
I have two types of annotations: driver and passenger. I have different images for their annotation.
Here is how I am trying to do it:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? DriverAnnotation {
guard let dequeuedDriverAnnotation = mapView.dequeueReusableAnnotationView(withIdentifier: "driver") else {
let driverAnnotation = MKAnnotationView(annotation: annotation, reuseIdentifier: "driver")
driverAnnotation.image = UIImage(named: "driverAnnotation")
return driverAnnotation
}
dequeuedDriverAnnotation.annotation = annotation
return dequeuedDriverAnnotation
} else if let annotation = annotation as? PassengerAnnotation {
guard let dequeuedPassengerAnnotation = mapView.dequeueReusableAnnotationView(withIdentifier: "passenger") else {
let passengerAnnotation = MKAnnotationView(annotation: annotation, reuseIdentifier: "passenger")
passengerAnnotation.image = UIImage(named: "currentLocationAnnotation")
return passengerAnnotation
}
dequeuedPassengerAnnotation.annotation = annotation
return dequeuedPassengerAnnotation
}
return nil
}
}