Xamarin Forms Maps Add Custom Pin Icon With Click Event

This is how I add a custom pin using Xamarin Forms Maps with no additional Nuget packages other than Xamarin.Forms.Maps

If you havent already, then download the Xamarin Forms Master Samples and look under the CustomRenderers/Map folder
https://github.com/xamarin/xamarin-forms-samples/tree/master/CustomRenderers/Map

*Save your custom icon .png files in the Android project Resources folder and iOS project folder.

In the CustomPin.cs file add an Icon string

public class CustomPin : Pin
{
public string Name { get; set; }
public string Url { get; set; }
public string Icon { get; set; }
}

Then in your Android CustomMapRenderer.cs file in the CreateMarker override add SetIcon

protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
CustomPin p = new CustomPin();
foreach(var cp in customPins)
{
if(cp.Position == pin.Position)
{
p = cp;
}
}
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
//marker.SetSnippet(pin.Address); marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
marker.SetIcon(BitmapDescriptorFactory.FromFile(p.Icon));
return marker;
}

in iOS in the CustomMapRenderer.cs GetViewForAnnotation()

protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
//annotationView.Image = UIImage.FromFile("pin.png");
annotationView.Image = UIImage.FromFile(customPin.Icon);
annotationView.CalloutOffset = new CGPoint(0, 0);
annotationView.LeftCalloutAccessoryView = new
IImageView(UIImage.FromFile("monkey.png"));
annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
}
annotationView.CanShowCallout = true;
return annotationView;
}

And then in the MapPage.xaml.cs file add your custom icon

public MapPage()
{
InitializeComponent();
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(37.79752, -122.40183),
Label = "Xamarin San Francisco Office",
Address = "394 Pacific Ave, San Francisco CA",
Name = "Xamarin",
Url = "http://xamarin.com/about/",
Icon = "pin.png"
};
customMap.CustomPins = new List { pin };
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
12610cookie-checkXamarin Forms Maps Add Custom Pin Icon With Click Event