Search code examples
xamarinxamarin.formspolylinecustom-renderer

Xamarin.Forms.Maps custom polyline renderer does not render when in view


I am trying to follow this guide in order to draw a polyline on a map in a Xamarin.Forms app. It should track the user's position in real-time and update the polyline when new position data comes in.

I wrote a custom map renderer that will render the polyline, but for some reason it does not update when the map is in view. I have to navigate back to the main launch page and navigate to the mapping page again for it to update.

I extracted the minimum code to reproduce the problem, but it is still too much to paste here, so I hosted it on GitHub:

https://github.com/Steztric/MapWithWaylineSample

Please could somebody let me know what I am doing wrong. You can demonstrate the problem by cloning the repo and running it.


Solution

  • You need to create renderer every time, so remove class variable polylineRenderer and use local one.

    MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlayWrapper)
            {
                IMKOverlay overlay = Runtime.GetNSObject(overlayWrapper.Handle) as IMKOverlay;
    
                if (overlay is MKPolyline)
                {
                    var polylineRenderer = new MKPolylineRenderer(overlay as MKPolyline);
                    polylineRenderer.FillColor = UIColor.Blue;
                    polylineRenderer.StrokeColor = UIColor.Red;
                    polylineRenderer.LineWidth = 3;
                    polylineRenderer.Alpha = 0.4f;
                    return polylineRenderer;
                }
                else
                {
                    return null;
                }
            }
    

    Also you can simplify things a little

    Define MKPolyline currentWayline; then

        var wayline = MKPolyline.FromCoordinates(coords.ToArray());
        //IMKOverlay overlay = Runtime.GetNSObject(wayline.Handle) as IMKOverlay;
        nativeMap.AddOverlay(wayline);
        currentWayline = wayline;