【问题标题】:How to calculate distance from user location to annotation and show it in a label如何计算从用户位置到注释的距离并将其显示在标签中
【发布时间】:2017-05-31 21:54:52
【问题描述】:

我的 detailView 中有一个标签,我想计算从当前用户位置(如果用户移动将更新)到某个注释的距离。
并在该标签中显示距离
例如:“距您所在位置 3.6 公里”

【问题讨论】:

标签: ios iphone swift xcode master-detail


【解决方案1】:

我建议使用扩展程序。假设您有自己的注释类(如果没有,只需使用 MKAnnotation 而不是“YourAnnotationClass”) - 您想使用计算属性 distanceToUsersCurrentLocation 扩展它。显然,要访问用户的当前位置,您需要导入 CoreLocation。

import UIKit
import CoreLocation

public class ViewController { //class where you need to set the label's text

    //your code here

    }
}

extension YouAnnotationClass {
    var distanceToUsersCurrentLocation: Double {
        let manager = CLLocationManager() //location manager for user's current location
        let destinationCoordinates = CLLocation(latitude: self.latitude, longitude: self.longitude) //coordinates for destinastion
        let selfCoordinates = CLLocation(latitude: (manager.location?.coordinate.latitude)!, longitude: (manager.location?.coordinate.longitude)!) //user's location
        return selfCoordinates.distance(from: destinationCoordinates) //return distance in **meters**
}

每次您在此类中访问 distanceToUsersCurrentLocation 时,您都会获得以米为单位的距离。我希望这对您的问题有所帮助

【讨论】:

    【解决方案2】:

    您的注释将具有位置属性。两个计算出点之间的距离-

    让 distanceInMeters = coordinateOne.distance(from: coordinateTwo)

    您可以阅读此链接了解更多信息 -

    How to find out distance between coordinates?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2012-01-16
      • 1970-01-01
      相关资源
      最近更新 更多