Search code examples
swiftmkmapviewcllocationmanagermkpolylinecllocationcoordinate2d

Swift, MKPolyline how to create polyline between coordinate point


Hi I wrote this code to draw a polyline between some point:

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
}

It takes coordinates from a Dictionary, put it in a array(arraToDraw) and I use forpolyline and forpolyline2 to cast values.

Now the problem is that it only draw dots on the coordinates how can I connect that?


Solution

  • You're creating multiple polylines with a single point, instead of a single polyline with multiple points. It's hard to get the code right without knowing your dictionary structure, but this should be more in line with what you're trying to do:

    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
    }