swiftxcodemapkitcore-locationmkoverlay

MapKit - Route is found but not displaying


I am creating a route in the iPhone simulator from the user current location to another point. The route is created fine and I am able to grab the time and distance it would take to travel to the destination but the route polyline/overlay isn't displaying. The code is quite large so below are the essential parts I think which are needed to explain the issue.

func tapTocreateRoute(){
    location = CLLocationCoordinate2D(latitude: 37.787359, longitude: -122.41)
    let placemark = MKPlacemark(coordinate: location)
    let mapItem = MKMapItem(placemark: placemark)
    routeCreater(mapItem: mapItem)      
}

 func routeCreater(mapItem: MKMapItem){

    let destinationPin = customPin(pinTitle: "end", pinSubtitle: "testing", location: carLocation)
    self.mapView.addAnnotation(destinationPin)

    let request = MKDirections.Request()
    request.source = MKMapItem.forCurrentLocation()
    request.destination = mapItem
    request.transportType = MKDirectionsTransportType.walking

    let directions = MKDirections(request: request)

    directions.calculate { (response, error) in
        guard let response = response else {
            print("MKDIRECTION error: \(error?.localizedDescription ?? "Error not found")")
            return
        }

        self.route = response.routes[0]
        self.mapView.addOverlay(self.route.polyline, level: .aboveRoads)

        self.mapView.setVisibleMapRect(self.route.polyline.boundingMapRect, animated: true)
        let rect = self.route.polyline.boundingMapRect
        self.mapView.setRegion(MKCoordinateRegion(rect), animated: true)

        self.walkingTime =  self.route.expectedTravelTime //displays correctly
        self.walkingDistance = self.route.distance // displays correctly

    }
}

  //Line Renderer for Route
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let lineRenderer = MKPolylineRenderer(overlay: overlay)
    lineRenderer.strokeColor = UIColor(red: 216/255, green: 71/255, blue: 30/255, alpha: 1)
    lineRenderer.lineWidth = 3.0
    return lineRenderer
}

am I missing something with the rendering? Thanks for the help


Solution

  • Did you make sure to assign the MapView's delegate so it knows where to look for the renderer?