How To Show A Custom Annotation On A Map In Monotouch For iPhone



TODO:

Have you ever wanted to show a custom Map Annotation on a Map using Monotouch for iPhone?

 

SOLUTION:

 

public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, NSObject annotation)
{
	if(!annotation.GetType().Equals(typeof(MyCustomAnnotation)) )
		return null;
				
	var anv = mapView.DequeueReusableAnnotation("myannotation");
				
	if (anv == null)
	{
		anv = new MKAnnotationView(annotation, "myannotation");
		anv.CanShowCallout = true;
		anv.Image = UIImage.FromFile("Images/myannotation.png");
	}
	else
	{
		anv.Annotation = annotation;
		anv.CanShowCallout = true;
	}
				
	//add a right accessory to show details if there are there and are not the same as the title...
	if(!String.IsNullOrEmpty(  ((MyCustomAnnotation)anv.Annotation).Details) && 
		((MyCustomAnnotation)anv.Annotation).Details != ((MyCustomAnnotation)anv.Annotation).Title )
	{
		var accButton = UIButton.FromType(UIButtonType.DetailDisclosure);
		accButton.Title (UIControlState.Normal);
		anv.RightCalloutAccessoryView = accButton;
	}
				
	return anv;
}

 

 

NOTES:

So here I have created a custom MKAnnoatation class called MyCustomAnnotation.  Basically if the type coming into GetViewForAnnotation() is not mine I am ignoring it.  If it is mine, then I am assigning a custom image to it, and also adding a Right Accessory Button, iff the tite is not the same as the details, and details is not null or empty.  You could show additional images too, if you create another class that inherits MyCustomAnnotations.  For instance  public class MyCustomAnnotation2 : MyCustomAnnotation.  You can then check to see if that is the instance coming in, and assign an image accordingly.  Hope this helps, and feel free to contact me for issues.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading