ispiro
ispiro

Reputation: 27673

Why is the Polyline not showing?

Here is my whole code to show a simple line:

public class MapUIViewController : UIViewController
{
    MKMapView map;

    public override void ViewDidAppear(bool animated)
    {
        base.ViewDidAppear(animated);
        CLLocationCoordinate2D loc = new CLLocationCoordinate2D(38.8895, -77.036168);
        map = new MKMapView()
        {
            MapType = MKMapType.Hybrid,
            Region = new MKCoordinateRegion(loc, new MKCoordinateSpan(0.1, 0.1)),
            Frame = View.Bounds,
        };
        View = map;
        ShowLine(loc, new CLLocationCoordinate2D(loc.Latitude + 1, loc.Longitude + 1));
    }
        
    void ShowLine(CLLocationCoordinate2D start, CLLocationCoordinate2D end)
    {
        MKGeodesicPolyline polyline = MKGeodesicPolyline.FromCoordinates(new CLLocationCoordinate2D[] { start, end });
        map.AddOverlay(polyline);
        map.OverlayRenderer = rend;
    }

    MKOverlayRenderer rend(MKMapView mapView, IMKOverlay overlay)
    {
        if (overlay is MKGeodesicPolyline line)
            return new MKPolylineRenderer(line) { LineWidth = 3, StrokeColor = UIColor.Red, FillColor = UIColor.Brown, Alpha = 1 };
        else
            return null;
    }
}

It shows the location specified, but does not show the line.

(The code is in C# (using Xamarin.ios) but it should be similar in Swift and Objective C, and my question is about the renderer which is an ios feature, not about a language feature).

I must be missing something, but I can't find it.

Upvotes: 0

Views: 65

Answers (1)

Jason
Jason

Reputation: 89102

you need to assign the renderer BEFORE you add the line. Doing it the other way means that no renderer exists when the line is added so it will not be drawn

wrong

map.AddOverlay(polyline);
map.OverlayRenderer = rend;

right

map.OverlayRenderer = rend;
map.AddOverlay(polyline);

Upvotes: 1

Related Questions