swiftmapsmapkitmapkitannotationmap-directions

Swift - MapKit not showing directions to pin


The annotation is rendered, however, the directions overlay is not displayed as intended. Location is displayed properly via CoreLocation. No errors are shown when the file is executed.

See the implementation below

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

}


Solution

  • Maybe MapView.userLocation.coordinate is nil.

    Check "User Location" of the MapView on Storyboard.

    enter image description here