我想獲得兩個位置之間的距離。 我試過這段代碼:快速計算兩個位置之間的距離
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
CLGeocoder().geocodeAddressString("ADDRESS OF LOC 2") { (placemarks, error) in
guard let placemarks = placemarks, let loc2 = placemarks.first?.location
else {
return
}
let loc1 = CLLocation(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
var distance = loc1.distance(from: loc2)
print((distance/1000).rounded(), " km")
}
}
我的問題是,我得到一個錯誤的距離。 打印結果將是「2公里」
如果我計算出「地圖」在同一地點之間的距離,我得到的長度「2,7公里」和「2.9公里」
兩個Route選項我錯了什麼?
您沒有發現任何問題,您只是通過使用四捨五入()方法丟棄了小數部分,即2.7公里變爲2公里,因爲您捨去了它! –
如果我這樣做:'print(distance/1000)'結果將是:'1.74364568832' - 與2,7或2,9不一樣:/ – Ghost108