8

我在 Swift 中有以下代码将 MKPolyline 添加到 MapView。XCode 并没有告诉我有问题,据我所知,这应该可以工作。

MapView 的出口:

@IBOutlet weak var mapView: MKMapView!

保存坐标的变量:

var coordinates: [CLLocationCoordinate2D] = []

从 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]

将 Core Data 中的坐标添加到我的新数组中:

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

创建折线:

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

添加叠加层:

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

将其添加到 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
}

我只是得到一个空白的 MapView。我可以将坐标数组打印到控制台,所以我知道数据已添加。有任何想法吗?

4

2 回答 2

8

正如评论中所发布的,问题中的代码很好。我只是没有设置代表。

mapView.delegate = self
于 2015-03-26T13:37:54.693 回答
8

上面的方法在 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()
    }
于 2017-05-11T05:08:44.267 回答