2016-11-04 85 views
0

我目前正在使用swift 3-xcode。從兩個給定點創建一行

我有一個視圖控制器和地圖。

我有註解的地圖,所以當我長按地圖我加的註釋是這樣的:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

let longPressRec = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:))) 

     longPressRec.minimumPressDuration = 1.5 //time for pressing : seconds 

     map.addGestureRecognizer(longPressRec) 
} 

添加註釋:

func longpress(gestureRecognizer: UIGestureRecognizer){ 


    let touchPoint = gestureRecognizer.location(in: self.map) 

    let coord = map.convert(touchPoint, toCoordinateFrom: self.map) 




    let annotation = MKPointAnnotation() 

    annotation.coordinate = coord 

    annotation.title = "Point X" 

    map.addAnnotation(annotation) 

    print(coord.latitude) 
    print(coord.longitude) 

    var lastLocation = locationManager.location!  //last location 
    var currentLocation = locationManager.location!  //current location 


    if locationSet == false { 

     let firstLocation = locationManager.location! //first point 

     locationSet = true 

    } 

    else { //after second point 

     let currentLocation: CLLocation = locationManager.location! 

     var locations = [lastLocation, currentLocation] 
     var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate}) 


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



    } 









} 

的MapView:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { 

    //if overlay is MKPolyline { 
     print("Generating Polyline") 
     var renderer = MKPolylineRenderer(overlay: overlay) 
     renderer.strokeColor = UIColor.blue 
     renderer.lineWidth = 4 
     return renderer 

    // } 

} 

現在我想在地圖上畫一條線,在第二個註釋和第一個註釋之間,每當我長時間注意地圖。

我該怎麼做?

編輯:我試圖做到這一點,但我不能。這是我迄今爲止...

+0

如果你長時間點擊你的地圖3次會怎麼樣?你想在第二點和第三點之間劃一條線嗎? –

+0

有50種不同的方式來做到這一點。你如何試圖自己弄清楚,當你失敗時,向我們展示你的代碼。 – Sethmr

+0

如果我點擊5次,它應該製作4行:點擊1到2,點擊2到3,點擊3到4,點擊4到5.就像一條路徑......我正在嘗試這樣做,但是成功的內部消除 –

回答

0

劃清界線你實現mapViewDelegate方法:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { 
     let renderer = MKPolylineRenderer(polyline: polyLine!) 
     renderer.strokeColor = UIColor.blue 
     renderer.lineWidth = 1 
     return renderer 
    } 

要在觸摸點轉換成座標來構建你的MKPolyLine你使用:

mapView.convert(touchPoint, toCoordinateFrom: mapView) 
+0

您能否給一些幫助,請。我真的不知道該如何實施......我會如此耿耿於懷。我的意思是我嘗試添加此代碼,但沒有任何成功 –

+0

我有點卡在這裏。有人可以幫忙嗎?請 –

+0

我沒有設法做到這一點,但無論如何感謝 –