0

您好我寫了這個代碼來畫一些點之間的折線:斯威夫特,MKPolyline如何創建折線座標點之間

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 
} 

它需要座標從字典,把它放在一個陣列中(arraToDraw)和我使用forpolyline和forpolyline2來投射值。

現在的問題是,它只在座標上畫點,我怎麼連接它?

回答

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 
} 
+0

感謝你這麼多,它的工作原理。 –