gpt4 book ai didi

swift - 从两个给定点创建一条线

转载 作者:行者123 更新时间:2023-11-30 12:55:40 26 4
gpt4 key购买 nike

我目前正在使用 swift 3 - xcode。

我有一个带有 map 的 View Controller 。

我已经对 map 进行了注释,因此当我长按 map 时,我会添加如下注释:

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)



}









}

map View :

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

// }

}

现在,每次长按 map 时,我想在 map 中的第二个注释和第一个注释之间画一条线。

我怎样才能做到这一点?

编辑:我已经尝试这样做,但我做不到。这就是我到目前为止所拥有的......

最佳答案

要绘制线条,您需要实现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)

关于swift - 从两个给定点创建一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com