从两个给定点创建一条线

Create a line from two given points

我目前正在使用 swift 3 - xcode。

我有一个 viewcontroller 和一张地图。

我已经对地图进行了注释,所以当我长按地图时,我添加了这样的注释:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

let longPressRec = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))

        longPressRec.minimumPressDuration = 1.5   //time for pressing : seconds

        map.addGestureRecognizer(longPressRec)
}

添加注释:

func longpress(gestureRecognizer: UIGestureRecognizer){


    let touchPoint = gestureRecognizer.location(in: self.map)

    let coord = map.convert(touchPoint, toCoordinateFrom: self.map)




    let annotation = MKPointAnnotation()

    annotation.coordinate = coord

    annotation.title = "Point X"

    map.addAnnotation(annotation)

    print(coord.latitude)
    print(coord.longitude)

    var lastLocation = locationManager.location!       //last location
    var currentLocation = locationManager.location!     //current location


    if locationSet == false {

        let firstLocation = locationManager.location!  //first point

        locationSet = true

    }

    else {  //after second point

        let currentLocation: CLLocation = locationManager.location!

        var locations = [lastLocation, currentLocation]
        var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate})


        var polyline = MKPolyline(coordinates: coordinates, count: locations.count)
        map.add(polyline)



    }









}

地图视图:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

    //if overlay is MKPolyline {
        print("Generating Polyline")
        var renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.blue
        renderer.lineWidth = 4
        return renderer

   // }

}

现在我想,每次长按地图,在地图上,在第二个注释和第一个注释之间画一条线。

我该怎么做?

编辑:我试过这样做但是我做不到。这就是我目前所拥有的...

要画线,您需要实现 mapViewDelegate 方法:

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(polyline: polyLine!)
        renderer.strokeColor = UIColor.blue
        renderer.lineWidth = 1
        return renderer
    }

要将您的触摸点转换为坐标以构建您使用的 MKPolyLine:

    mapView.convert(touchPoint, toCoordinateFrom: mapView)