Search code examples
xamarin.iosmkmapviewxamarin.formsmkpolyline

Adding multiple polylines to an MKMapView (Xamarin)


I'm extending the example provided @ https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/maps/map-overlay/polyline/ to add multiple polylines to my map.

Everything works fine with a single polyline, but when I add the second, or add a polyline alongside an annotation, GetOverlayRenderer errors out with the error

"Value cannot be null.Parameter name: polyline"

It's erring out on line:

polylineRenderer = new MKPolylineRenderer (overlay as MKPolyline);

And when I look at the overlay object, it is:

{MapKit.MKOverlayWrapper}
BoundingMapRect: {{{62634939.7333333, 111606556.311973}, {745654.044444449, 848491.772016793}}}
Coordinate: {CoreLocation.CLLocationCoordinate2D}
Handle: 0x791ca560
Non-public members: 

I don't understand why it works with one polyline, but when I add anything else to the map, it fails (first time through the method, also)

Here's the entire method where the error is occurring. I can provide more code but it works FINE with one line, just not with two. (I loop through a list of objects... if there's 1, it's fine.. if there is 2, it fails).

MKOverlayRenderer GetOverlayRenderer (MKMapView mapView, IMKOverlay overlay)
    {

        if (polylineRenderer == null) {
            try
            {

            polylineRenderer = new MKPolylineRenderer (overlay as MKPolyline);
            polylineRenderer.FillColor = UIColor.Blue;
            polylineRenderer.StrokeColor = UIColor.Red;
            polylineRenderer.LineWidth = 3;
            polylineRenderer.Alpha = 0.4f;
            }
            catch (Exception ex) {
            }
        }
        return polylineRenderer;
    }

Solution

  • The end result here was that the overlay passed to the method is a wrapper of sorts, and you need to get the "handle" property to get the actual overlay.

    public override MKOverlayView GetViewForOverlay (MKMapView mapView, IMKOverlay overlayWrapper)
        {
        if (overlayWrapper != null) {
        var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as MKOverlay;
        // Do Overlay Functions here
        }
    

    The source of this came from https://forums.xamarin.com/discussion/31616/what-is-mkoverlaywrapper-its-breaking-my-map-renderer