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