Search code examples
swiftannotationsmkmapviewmkannotationmkannotationview

How to add 2 different pins on Map? - Swift


I am trying to use two different pins on a map, this is the code I have:

    func mapView (_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{

    //avoid for user location
    if (annotation is MKUserLocation) {
        return nil
    }

    let reuseId = "annId"
    var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)

    if anView == nil {

        if(annotation.subtitle! == "Offline"){

            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView!.image = UIImage(named:"offIceCream.pdf")!
            anView!.canShowCallout = true

        }

        if(annotation.subtitle! == "Online"){

            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView!.image = UIImage(named:"onIceCream.pdf")!
            anView!.canShowCallout = true
        }

    } else {

        anView!.annotation = annotation
    }

    return anView
}

The problem is that it is not setting the correct icon depending on the subtitle of the annotation. For some reason sometimes it works correctly and sometimes it works the opposite way (sets the online icon on the offline annotations and viceversa). Any idea why this is happening?.

Thanks in advance!


Solution

  • Because you forget to update the .image of already queued annotation views:

    if anView == nil {
      ...
    }
    else {
      anView!.annotation = annotation
    
      if (annotation.subtitle! == "Offline") {
        anView!.image = UIImage(named:"offIceCream.pdf")!
      }
      else if (annotation.subtitle! == "Online") {
        anView!.image = UIImage(named:"onIceCream.pdf")!
      }
    }
    

    A clearer way of writing the entire logic would be:

    func mapView (_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
    {
      if (annotation is MKUserLocation) {
        return nil
      }
      var anView = mapView.dequeueReusableAnnotationView(withIdentifier: "annId")
    
      if anView == nil {
         anView = MKAnnotationView(annotation: annotation, reuseIdentifier: "annId")
      } 
      else {
        anView?.annotation = annotation
      }
    
      anView?.canShowCallout = true
    
      if (annotation.subtitle! == "Offline") {
        anView?.image = UIImage(named: "offIceCream.pdf")
      }
      else if (annotation.subtitle! == "Online") {
        anView?.image = UIImage(named: "onIceCream.pdf")
      }
      return anView
    }