0

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
     }
}
Riajur Rahman
  • 1,976
  • 19
  • 28
iVvaibhav
  • 105
  • 3
  • 12
  • Not really answering your question, but normally this is resolved by the backend API which will accept current location and radius to cover. So the calculation can be easier done at the server to compare with db data – xmhafiz Dec 21 '17 at 08:41

1 Answers1

0

How about defining function to check if annotation belong to the map region currently displayed, and try returning nil if it is out of region.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
  if !visibleMapRegion(annotation) {
      return nil
  }
  ...

To define this function see also:

Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52