从两个给定点创建一条线

时间:2016-11-04 17:54:57

标签: swift mapkit swift3 xcode8 mkpolyline

我目前正在使用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)



    }









}

mapview:

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

   // }

}

现在我想在每次长按地图时在地图中画第二个注释和第一个注释之间的线。

我该怎么做?

编辑:我已经尝试过这样做,但我无法做到。这就是我到目前为止......

1 个答案:

答案 0 :(得分:0)

要绘制实现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)