0

I have written code to drop a pin and then show directions to it on a MapKitView and for some reason the pin drops but the directions will not show on the map. All help is welcome, thank you.

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var MapView: MKMapView!

    let locationManager = CLLocationManager()
    var movedToUserLocation = false

    func clean() {
        MapView.removeAnnotations(MapView.annotations)
        MapView.removeOverlays(MapView.overlays)
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .denied, .restricted:
            print("Disable Parental Controles")
        case .notDetermined:
            manager.requestWhenInUseAuthorization()
        default:
            manager.startUpdatingLocation()
        }
    }

    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
        if !movedToUserLocation {
            mapView.region.center = mapView.userLocation.coordinate
            movedToUserLocation = true
        }
    }


    func addDirections(coor: CLLocationCoordinate2D) {
        let directionsRequest = MKDirectionsRequest()
        directionsRequest.source = MKMapItem(placemark: MKPlacemark(coordinate: MapView.userLocation.coordinate))
        directionsRequest.destination = MKMapItem(placemark: MKPlacemark(coordinate: coor))
        directionsRequest.requestsAlternateRoutes = false
        directionsRequest.transportType = .any

        let directions = MKDirections(request: directionsRequest)
        directions.calculate { response, error in
            if let res = response {
                if let route = res.routes.first {
                    self.MapView.add(route.polyline)
                    self.MapView.region.center = coor
                }
            }
            else {
                print(error)
            }
        }
    }

    @IBAction func B1(_ sender: Any) {
        let lat = 30.2817
        let lon = -86.0188

        self.clean()

        let coord = CLLocationCoordinate2DMake(CLLocationDegrees(lat), CLLocationDegrees(lon))
        let annotationView: MKPinAnnotationView!
        let annotationPoint = MKPointAnnotation()

        annotationPoint.coordinate = coord
        annotationPoint.title = "Pizza By The Sea"

        annotationView = MKPinAnnotationView(annotation: annotationPoint, reuseIdentifier: "Annotation")
        MapView.addAnnotation(annotationView.annotation!)
        addDirections(coor: coord)
    }


    @IBAction func B2(_ sender: Any) {
        let lat = 30.2844
        let lon = -86.0272

        self.clean()

        let coord = CLLocationCoordinate2DMake(CLLocationDegrees(lat), CLLocationDegrees(lon))
        let annotationView: MKPinAnnotationView!
        let annotationPoint = MKPointAnnotation()

        annotationPoint.coordinate = coord
        annotationPoint.title = "George's"

        annotationView = MKPinAnnotationView(annotation: annotationPoint, reuseIdentifier: "Annotation")
        MapView.addAnnotation(annotationView.annotation!)
        addDirections(coor: coord)
    }

    @IBAction func B3(_ sender: Any) {
        let lat = 30.2815
        let lon = -86.0191

        self.clean()

        let coord = CLLocationCoordinate2DMake(CLLocationDegrees(lat), CLLocationDegrees(lon))
        let annotationView: MKPinAnnotationView!
        let annotationPoint = MKPointAnnotation()

        annotationPoint.coordinate = coord
        annotationPoint.title = "Ticheli's Pizza"

        annotationView = MKPinAnnotationView(annotation: annotationPoint, reuseIdentifier: "Annotation")
        MapView.addAnnotation(annotationView.annotation!)
        addDirections(coor: coord)
    }

    @IBAction func B4(_ sender: Any) {
        let lat = 30.2794074
        let lon = -86.0816672

        self.clean()

        let coord = CLLocationCoordinate2DMake(CLLocationDegrees(lat), CLLocationDegrees(lon))
        let annotationView: MKPinAnnotationView!
        let annotationPoint = MKPointAnnotation()

        annotationPoint.coordinate = coord
        annotationPoint.title = "Big Bad Breakfast"

        annotationView = MKPinAnnotationView(annotation: annotationPoint, reuseIdentifier: "Annotation")
        MapView.addAnnotation(annotationView.annotation!)
        addDirections(coor: coord)
    }

    @IBAction func B5(_ sender: Any) {
        let lat = 30.3129063
        let lon = -86.1119704

        self.clean()

        let coord = CLLocationCoordinate2DMake(CLLocationDegrees(lat), CLLocationDegrees(lon))
        let annotationView: MKPinAnnotationView!
        let annotationPoint = MKPointAnnotation()

        annotationPoint.coordinate = coord
        annotationPoint.title = "Cafe Thirty-A"

        annotationView = MKPinAnnotationView(annotation: annotationPoint, reuseIdentifier: "Annotation")
        MapView.addAnnotation(annotationView.annotation!)
        addDirections(coor: coord)
    }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKPolylineRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay as! MKPolyline)

        renderer.strokeColor = .yellow
        renderer.lineWidth = 5.0

        return renderer
    }

    @objc func dropAnnotation(gestureRecogniser: UIGestureRecognizer) {
        if gestureRecogniser.state == .began {
            let holdLocation = gestureRecogniser.location(in: MapView)
            let coord = MapView.convert(holdLocation, toCoordinateFrom: MapView)

            let annotationView: MKPinAnnotationView!
            let annotationPoint = MKPointAnnotation()

            self.clean()

            annotationPoint.coordinate = coord
            annotationPoint.title = "\(coord.latitude), \(coord.longitude)"

            annotationView = MKPinAnnotationView(annotation: annotationPoint, reuseIdentifier: "Annotation 2")
            MapView.addAnnotation(annotationView.annotation!)
            addDirections(coor: coord)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        MapView.delegate = self
        locationManager.delegate = self

        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        let span = MKCoordinateSpan(latitudeDelta: MapView.region.span.latitudeDelta/200, longitudeDelta: MapView.region.span.longitudeDelta/200)
        let region = MKCoordinateRegion(center: MapView.region.center, span: span)

        let dropPin = UILongPressGestureRecognizer(target: self, action: #selector(self.dropAnnotation(gestureRecogniser:)))
        dropPin.minimumPressDuration = CFTimeInterval(1.0)
        MapView.addGestureRecognizer(dropPin)

        MapView.setRegion(region, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52
Programmer
  • 61
  • 1
  • 1
  • 8
  • are you sure after selecting location from newViewController values are passes to func where you are adding poly line ? please check using breakpoints and print the selected location Coordinates and user current location coordinates – iOS Geek Jul 28 '17 at 04:15

2 Answers2

1

Maybe MapView.userLocation.coordinate is nil.

Check "User Location" of the MapView on Storyboard.

enter image description here

Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52
1

mapView(_:rendererFor:) returns the MKOverlayRenderer object.

Replace

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

with

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52