[英]How to make two coordinates match each other?
我正在嘗試獲取兩個坐標並使它們彼此匹配,以便彈出一個按鈕,但我一直遇到錯誤。 到目前為止,這是我的代碼:
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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.