Monotouch – Draw a MKPolyline on Map

mkmapviewxamarin.ios

I've a MKPolyline made of CLLocationCoordinate2D array (Points). That's all fine.

I added this line to the Map as an overlay, like so: Map.AddOverlay(line);

I event set this: Map.SetVisibleMapRect(line.BoundingMapRect, true);

But the line does not show up although the Map bounds are correct.

I'm looking into MKPolylineView, but can't get it to work.

Anyone knows to set colour and line width?

Thanks

Best Answer

After much head scratching, here is how to display a MKPolyline on a MKMapView:

Step 1: Create a delegate method for Map GetViewForOverlay

Map.GetViewForOverlay = Map_GetViewForOverlay;

Where Map is the MKMapView.

MKOverlayView Map_GetViewForOverlay(MKMapView mapView, NSObject overlay)
{
    if(overlay.GetType() == typeof(MKPolyline))
    {
       MKPolylineView p = new MKPolylineView((MKPolyline)overlay);
       p.LineWidth = 2.0f;
       p.StrokeColor = UIColor.Green;
       return p;
    }
    else
        return null;
}

Step 2: Create a new instance of MKPolyline

MKPolyline line = MKPolyline.FromCoordinates(polyPoints);

Where polyPoints is an Array of CLLocationCoordinate2D.

Step 3: Add the overlay to the map

Map.AddOverlay(line);

Step 4: Use code below to zoom and change Map bounds to fit route

Map.SetVisibleMapRect(line.BoundingMapRect, true);
Related Topic