Swift,MKPolyline如何在坐标点之间创建折线

时间:2017-06-03 17:23:23

标签: swift mkmapview cllocationmanager mkpolyline cllocationcoordinate2d

您好我写了这段代码在某点之间绘制折线:

var arrayToDraw: Array<Any> = []
var forpolyline: Array<CLLocationDegrees> = []
var forpolyline2: CLLocationCoordinate2D = CLLocationCoordinate2D.init()


func showRoute() {
    for h in 0...(orderFinalDictionary.count - 1){
        arrayToDraw = orderFinalDictionary[h].value
        print(arrayToDraw)
        var arrayToDrawCount = arrayToDraw.count
        for n in 0...(arrayToDrawCount - 1){
            forpolyline = (arrayToDraw[n] as! Array<CLLocationDegrees>)
            forpolyline2.latitude = (forpolyline[0])
            forpolyline2.longitude = (forpolyline[1])
            print(forpolyline2)
                var geodesic = MKPolyline(coordinates: &forpolyline2, count: 1)
                self.mapView.add(geodesic)
        }
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.red
    renderer.lineWidth = 3

    return renderer
}

它从一个Dictionary中获取坐标,将它放在一个数组(arraToDraw)中,然后使用forpolyline和forpolyline2来转换值。

现在问题是它只在坐标上绘制点我该怎么连接?

1 个答案:

答案 0 :(得分:1)

您使用单个点创建多条折线,而不是使用多个点创建单个折线。在不知道你的字典结构的情况下很难得到正确的代码,但这应该更符合你想要做的事情:

var arrayToDraw: Array<Any> = []
var forpolyline: Array<CLLocationDegrees> = []
var forpolyline2: CLLocationCoordinate2D = [CLLocationCoordinate2D]()

func showRoute() {
    for h in 0...(orderFinalDictionary.count - 1){
        arrayToDraw = orderFinalDictionary[h].value
        print(arrayToDraw)
        var arrayToDrawCount = arrayToDraw.count
        for n in 0...(arrayToDrawCount - 1){
            forpolyline = (arrayToDraw[n] as! Array<CLLocationDegrees>)
            forpolyline2.append(CLLocationCoordinate2D(latitude: forpolyline[0], longitude: forpolyline[1]))
        }
        print(forpolyline2)
        let geodesic = MKPolyline(coordinates: &forpolyline2, count: forpolyline2.count)
        self.mapView.add(geodesic)
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.red
    renderer.lineWidth = 3

    return renderer
}