ios - 在 Swift 上计算我的位置和 MapKit 引脚之间的距离

标签 ios swift geolocation mapkit mapkitannotation

我需要你的帮助,我正在开发一个应用程序,其中有一些图钉(位置),我想要的是获取每个图钉与我的位置之间的距离。我的代码如下

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/

相关文章:

ios - UIButton,左边是文字,右边是图片

ios - TableView 重新加载未从 Backendless 正确更新

javascript - 如何检测 Chrome 是否认为当前页面是安全来源?

linux - HTML5 地理定位在 Windows 上比在 Linux 上更准确(Firefox、Chrome、[Chromium])

iphone - FBRequest委托(delegate)方法请求:didLoad: is not getting called

ios - APNS打开应用程序的某个部分

iOS VoIP 通知在启动前崩溃

ios - 减少 uibarbuttonitem 的宽度

python - 将 Sentinel-1 SAR 图像的像素位置转换为地理坐标(纬度、经度)

iOS 系统图标不尊重 UIButton 的 UIImageInsets