Xamarin iOS - MKPinAnnotationView.Image not displaying custom Image

Viewed 769

I am writing a Custom Map Renderer which extends Xamarin's Map class, and am currently trying to add a custom image to some of the pins showing on iOS maps in my application.

I have a folder in my resources folder in my iOS solution called Images, and from there I used Add Existing to add my fire.png file. In my code, when I set a breakpoint where the image is set to my pinAnnotationView, you can see that the image is not null and shouldn't revert back to the generic iOS pin, however my fire image is not displaying and the default pin is.

Here is my code:

public MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
        {
            var myAnnotation = annotation as BasicMapAnnotation;
            var annotationView = new MKPinAnnotationView(myAnnotation, "basic annotation");

            var pinAnnotationView = annotationView as MKPinAnnotationView; 

            if (pinAnnotationView != null)
            {
                if (myAnnotation?.IsEmergency == "1")
                {
                    pinAnnotationView.PinTintColor = UIColor.Blue;

                }
                if (myAnnotation?.IsFireHazard == "1")
                {
                    //show fire image
                    UIImage image = UIImage.FromFile("Images/fire.png");
                    pinAnnotationView.Image = image;
                }
            }
            return pinAnnotationView;
        }

When I debug:

enter image description here

1 Answers

Don't use MKPinAnnotationView to set image , refer to here

I modify your code as below

public MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
    string reuseIdentifier = "basic annotation";

    var myAnnotation = annotation as BasicMapAnnotation;

    var annotationView = new MKAnnotationView(myAnnotation, reuseIdentifier);

    if (annotationView != null)
    {
        if (myAnnotation?.IsEmergency == "1")
        {
            MKPinAnnotationView annotationPinView = annotationView as MKPinAnnotationView;
            annotationPinView.PinTintColor = UIColor.Blue;
            return annotationPinView;
        }
        if (myAnnotation?.IsFireHazard == "1")
        {
            //show fire image
            UIImage image = UIImage.FromFile("Images/fire.png");
            annotationView.Image = image;
            return annotationView;
        }
    }
    return null;
}
Related