2017-11-11 99 views
0

我計算2點之間的距離。對於第一點,我分配了緯度和經度。第二個座標點在用戶點擊地圖的任何位置進行協調。每件事情都很完美,除了四次打印的答案。斯威夫特:地圖返回4個值作爲2點之間的距離,爲什麼?

  • 我試着返回第一個索引(原來第一個索引是4 的值)。
  • 我試圖將這些值添加到一個集以刪除重複的(它沒有工作)。
  • 我試圖做一個循環,並在第一次後中斷(仍然返回4個值)。 這裏我在哪裏創建用戶點擊(內viewdidAppear)註釋:

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") 
} 

回答

1

你的問題是你如何處理手勢。 「長按」手勢(與其他人一樣)有幾種狀態。當手勢開始時,手勢結束時,手勢被取消時以及在「長按」情況下手勢被更新時,會調用手勢動作。

只有當手勢狀態爲「結束」時,纔想執行距離計算。

@objc func longpress(gestureRecognizer: UIGestureRecognizer){ 
    if gestureRecognizer.state = .ended { 
     // your code here 
    } 
}