Search code examples
swiftmapkitswift3xcode8mkpolyline

Create a line from two given points


I am currently working with swift 3 - xcode.

I have a viewcontroller with a map.

I have had annotations to the map, so when I longpress the map I add an annotation like this:

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

to add annotations:

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)



    }









}

The 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

   // }

}

Now I'd like, to draw a line, in the map, between second annotion and first annotation, every time I long press the map.

How can I do that?

EDIT: I've tried to do this buts I am not being able. THis is what I have so far...


Solution

  • To draw the line you implement the mapViewDelegate method:

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

    To convert your touch point into coordinates to construct your MKPolyLine you use:

        mapView.convert(touchPoint, toCoordinateFrom: mapView)