2016-11-04 89 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

我没有设法做到这一点,但无论如何感谢 –