Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MKPolyLine not appearing on MapView in Swift

I have the following code in Swift to add an MKPolyline to a MapView. XCode isn't telling me there's an issue, and as far as I've read, this should be working.

Outlet for the MapView:

@IBOutlet weak var mapView: MKMapView!

Variable to hold the coordinates:

var coordinates: [CLLocationCoordinate2D] = []

Get my saved coordinates from Core Data:

var contextMap = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
var requestMap = NSFetchRequest(entityName: "Locations")
let predMap = NSPredicate(format: "game = %d", passedGameNumber)
requestMap.predicate = predMap
requestMap.sortDescriptors = [NSSortDescriptor(key:"time", ascending: false)]
    self.locationsList = contextMap.executeFetchRequest(requestMap, error: nil)! as [Locations]

Add the coordinates from Core Data to my new array:

for index in 1..<self.locationsList.count{
    var lat = Double(self.locationsList[index].latitude)
    var long = Double(self.locationsList[index].longitude)
    var coordinatesToAppend = CLLocationCoordinate2D(latitude: lat, longitude: long)
    coordinates.append(coordinatesToAppend)
}

Create the polyline:

var polyLine = MKPolyline(coordinates: &coordinates, count: coordinates.count)

Add the overlay:

self.mapView.addOverlay(polyLine, level: MKOverlayLevel.AboveRoads)

Add it to the MapView:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
    if overlay.isKindOfClass(MKPolyline) {
        // draw the track
        let polyLine = overlay
        let polyLineRenderer = MKPolylineRenderer(overlay: polyLine)
        polyLineRenderer.strokeColor = UIColor.blueColor()
        polyLineRenderer.lineWidth = 2.0

        return polyLineRenderer
    }

    return nil
}

I simply get a blank MapView. I can print the coordinates array to the console, so I know the data has been added. Any ideas?

like image 348
Adam Johnson Avatar asked Mar 26 '15 11:03

Adam Johnson


2 Answers

As posted in the comments, the code in the question was fine. I simply wasn't setting the delegate.

mapView.delegate = self
like image 118
Adam Johnson Avatar answered Nov 24 '22 14:11

Adam Johnson


The above method will be written like this in Swift3:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay.isKind(of: MKPolyline.self) {
            // draw the track
            let polyLine = overlay
            let polyLineRenderer = MKPolylineRenderer(overlay: polyLine)
            polyLineRenderer.strokeColor = UIColor.blue
            polyLineRenderer.lineWidth = 2.0

            return polyLineRenderer
        }

        return MKPolylineRenderer()
    }
like image 26
Tripti Kumar Avatar answered Nov 24 '22 15:11

Tripti Kumar