Adam Johnson
Adam Johnson

Reputation: 673

Using coordinates saved in Core Data to draw on a mapview

I have a list of coordinates stored in Core Data, along with the time at which they were saved, in the following format:

game - Integer 16

latitude - Double

longitude - Double

time - Date

I have managed to take the user's location and store it in Core Data without issue, but I am having trouble retrieving it and displaying it on a map. I have tried looking for a suitable tutorial, but I can't find anything that combines the Core Data and the MKPolyline aspects of my query. I'm quite new to coding in general and I can't quite align the two.

So, I know the following code will help me draw on to the map:

var coordinates = locations.map({ (location: CLLocation) -> 
CLLocationCoordinate2D in
    return location.coordinate
})

var polyline = MKPolyline(coordinates: &coordinates, 
                        count: locations.count)

And I already have this in my code to get the Core Data:

@IBOutlet weak var mapView: MKMapView!

var locationsList: [Locations] = []

var contextMap = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!

    var requestMap = NSFetchRequest(entityName: "Locations")
    let predMap = NSPredicate(format: "game = %d", gameNumber)
    requestMap.predicate = predMap
    requestMap.sortDescriptors = [NSSortDescriptor(key:"time", ascending: false)]

    self.locationsList = context.executeFetchRequest(requestMap, error: nil)! as [Locations]

But I just can't marry the two up in order to take my coordinates from Core Data and put them on the map.

Any help would be great - thanks.

Upvotes: 2

Views: 1196

Answers (1)

zisoft
zisoft

Reputation: 23078

You already have an array of CLLocation coordinates and built a MKPolyline. Everything fine so far.

Now you need to tell the MKMapView to draw that polyline on the map:

...
var polyline = MKPolyline(coordinates: &coordinates, count: locations.count)

// add the overlay
self.mapView.addOverlay(polyLine, level: MKOverlayLevel.AboveLabels)
...

To draw the overlay you need to create a MKOverlayRenderer

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
}

Upvotes: 1

Related Questions