Jamil Jamil - 4 months ago 13
Swift Question

Can't draw a polyline via MapKit in Swift

I'm trying to draw a line between two annotations on my map. The code is working, but i don't see it on map. Here is my code:

func longPressGesture()
{
let lpg = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
lpg.minimumPressDuration = 1;
Map.addGestureRecognizer(lpg)
}

func longPressAction(myRecognizer : UILongPressGestureRecognizer)
{
let currPoint = myRecognizer.locationInView(Map)
let point = Map.convertPoint(currPoint, toCoordinateFromView: Map)
points.append(currPoint);
if(points.count>1)
{
let startPoint = Map.convertPoint(points[points.count-2], toCoordinateFromView: Map)
let endPoint = Map.convertPoint(currPoint, toCoordinateFromView: Map)
var lineCoords = [startPoint,endPoint]
var line = MKPolyline(coordinates: &lineCoords, count: 2)
Map.addOverlay(line)
}
let myAnnotation = MKPointAnnotation();
myAnnotation.coordinate = point
myAnnotation.title = "Test"
myAnnotation.subtitle = "Test subtitle"
Map.addAnnotation(myAnnotation);
}


mapView method(not sure if it is used, i'm new to swift and i didn't write this):

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
print(overlay)
if overlay is MKCircle {
let circle = MKCircleRenderer(overlay: overlay);
circle.strokeColor = UIColor.redColor();
circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1);
circle.lineWidth = 1;
return circle;
}else if overlay is MKTileOverlay {
let carte_Renderer = MKTileOverlayRenderer(overlay: overlay)
carte_Renderer.alpha = 1
return carte_Renderer
}else if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay);
polylineRenderer.strokeColor = UIColor.blueColor();
polylineRenderer.lineWidth = 5;
return polylineRenderer;
}else {
return MKPolylineRenderer();
}
}

Answer

Ensure you've got an rendererForOverlay method, which defines how your MKPolyline objects will look.

You'll need to include theMKMapViewDelegate as well for this to work.

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer!
{
    if overlay is MKPolyline
    {
        let route: MKPolyline = overlay as MKPolyline
        let routeRenderer = MKPolylineRenderer(polyline:route)
        routeRenderer.lineWidth = 3.0
        routeRenderer.strokeColor = UIColor(red: 45.0/255.0, green: 200.0/255.0, blue: 0.0/255.0, alpha: 1);

        return routeRenderer
    }
    return nil
}
Comments