我计算2点之间的距离。对于第一点,我正在分配纬度和长度。第二个点坐标用户点击地图的位置。除了答案被打印4次外,每件事情都很完美。
,
let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.longpress(gestureRecognizer:)))
uilpgr.minimumPressDuration = 2
map.addGestureRecognizer(uilpgr)
这是计算距离的函数(在函数viewdidAppear之后):
@objc func longpress(gestureRecognizer: UIGestureRecognizer){
let touchPoint = gestureRecognizer.location(in: self.map)
let coordinates = map.convert(touchPoint, toCoordinateFrom: self.map)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinates
annotation.title = "Destination"
map.addAnnotation(annotation)
let source = CLLocation(latitude: 5, longitude: 5)
let distination = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
let distanceInMeters = source.distance(from: distination)
let distanceInMiles = String(Int(distanceInMeters/1.6))
myArrayDataStructure.myArray.append(distanceInMiles)
UserDefaults.standard.set(myArrayDataStructure.myArray, forKey: "items")
}
答案 0 :(得分:1)
您的问题是如何处理手势。 A"长按"手势(像其他人一样)有几种状态。当手势开始时,手势开始时,手势动作结束时,手势动作被取消,并且在长按"的情况下,手势动作被更新。
您只想在手势的状态结束时才执行距离计算"。
@objc func longpress(gestureRecognizer: UIGestureRecognizer){
if gestureRecognizer.state = .ended {
// your code here
}
}