ios - 如何使两个坐标相互匹配?

标签 ios swift coordinates

我试图获取两个坐标并使它们相互匹配,以便弹出一个按钮,但我一直收到错误消息。到目前为止,这是我的代码:

var userLocation: CLLocationCoordinate2D?
var driverLocation: CLLocationCoordinate2D?

func payTime() {
        if driverLocation == userLocation {
            payNowButton.isHidden = false
        }
    }

我正在使用 Swift 3、Firebase 和 Xcode 8。

最佳答案

要比较两个 CLLocationCoordinate2D,您可以检查它们的纬度和经度。

func payTime() {
    if driverLocation?.latitude == userLocation?.latitude && driverLocation?.longitude == userLocation?.longitude {
        // Overlapping
    }
}

然而,这只有在它们位于完全相同的位置时才有效。或者你可以使用这样的东西:

func payTime() {
    if let driverLocation = driverLocation, let userLocation = userLocation{
        let driverLoc = CLLocation(latitude: driverLocation.latitude, longitude: driverLocation.longitude)
        let userLoc = CLLocation(latitude: userLocation.latitude, longitude: userLocation.longitude)
        if driverLoc.distance(from: userLoc) < 10{
            // Overlapping
        }
    }
}

这会将两个点转换为 CLLocation,然后检查它们之间的距离(以米为单位)。您可以调整阈值以获得所需的结果。

编辑 1:

这是一个扩展程序,可以更轻松地比较位置。

extension CLLocationCoordinate2D{
    func isWithin(meters: Double, of: CLLocationCoordinate2D) -> Bool{
        let currentLoc = CLLocation(latitude: self.latitude, longitude: self.longitude)
        let comparingLoc = CLLocation(latitude: of.latitude, longitude: of.longitude)
        return currentLoc.distance(from: comparingLoc) < meters
    }
}

func payTime() {
    if let driverLocation = driverLocation, let userLocation = userLocation{
        if driverLocation.isWithin(meters: 10, of: userLocation){
            // Overlapping
        }
    }
}

关于ios - 如何使两个坐标相互匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45384332/

相关文章:

iphone - Sprite 以抛物线方式从position(x, y)跳到position(width-x, y)

objective-c - UIGestureRecognizer 或 touchesBegan 没有响应

ios - 启用 use_frameworks 后安装 cocoapods 后无法构建 FBParseUtilsV4

json - 处理 SwiftyJSON 中可选元素的最佳方法是什么?

ios - UIView的阴影路径颜色不变

mysql - 网站;让用户添加位置并获取坐标

ios - iOS 上的 Firebase 崩溃报告不会在崩溃后发送报告

iOS蓝牙设备在输入错误密码后无法取消配对或忘记

java - 如何在所有显示器和分辨率下保持 Java 游戏中的所有对象相同?

javascript - 检查对象是否在 css border/css wrapper 内