无法通过Swift中的MapKit绘制折线

时间:2016-07-28 06:43:46

标签: swift mapkit

我正在尝试在地图上的两个注释之间画一条线。代码正在运行,但我没有在地图上看到它。这是我的代码:

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方法(不确定是否使用,我是swift的新手,我没有写这个):

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();
    }
}

1 个答案:

答案 0 :(得分:2)

确保您拥有rendererForOverlay方法,该方法定义了MKPolyline个对象的外观。

您还需要包含MKMapViewDelegate以便工作。

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
}