我需要你的帮助,我正在开发一个应用程序,其中有一些图钉(位置),我想要的是获取每个图钉与我的位置之间的距离。我的代码如下
let annotation = MKPointAnnotation()
let annotationTwo = MKPointAnnotation()
let saintPaulHospitalBC = MKPointAnnotation()
override func viewDidLoad() {
super.viewDidLoad()
mapita.showsUserLocation = true // Mapita is the name of the MapView.
annotation.coordinate = CLLocationCoordinate2D(latitude: 25.647399800, longitude: -100.334304500)
mapita.addAnnotation(annotation)
annotationTwo.coordinate = CLLocationCoordinate2D(latitude: 25.589339000, longitude: -100.257724800)
mapita.addAnnotation(annotationTwo)
saintPaulHospitalBC.coordinate = CLLocationCoordinate2D(latitude: 49.280524700, longitude: -123.128232600)
mapita.addAnnotation(SaintPaulHospitalBC)
}
当我运行代码时, map 显示了引脚,但我还能做些什么来开始计算距离?谢谢!
最佳答案
您必须将注释的坐标转换为 CLLocation 类型,然后获取它们之间的距离。要忽略坐标的高度,因为它们是二维的,只需使用二维坐标的纬度和经度属性,如下所示:
let loc1 = CLLocation(latitude: coord1.latitude, longitude: coord1.longitude)
但是,CLLocation 具有一些其他属性,例如速度和高度,因此如果您想将这些因素考虑在内,则必须提供更多信息。要查找两个位置之间的距离,请执行以下操作:
let distance = loc1.distance(from: loc2)
您的答案将以米为单位的两倍。
关于ios - 在 Swift 上计算我的位置和 MapKit 引脚之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44139786/