我有以下代码来获取一个最接近的位置:
我的数据:
let coord1 = CLLocation(latitude: 52.45678,longitude: 13.98765)
let coord2 = CLLocation(latitude: 52.12345,longitude: 13.54321)
let coord3 = CLLocation(latitude: 48.771896,longitude: 2.270748000000026)
closestLocation(locations: [coord1,coord2,coord3],closestToLocation: coord3)
// This calculates closest location giving out 1 point
func closestLocation(locations: [CLLocation],closestToLocation location: CLLocation) -> CLLocation? {
if let closestLocation = locations.min(by: { location.distance(from: $0) < location.distance(from: $1) }) {
print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
print("Closest location: \(closestLocation),\n distance: \(location.distance(from: closestLocation))")
return closestLocation
} else {
print("coordinates is empty")
return nil
}
}
func locationmanager(_ manager: CLLocationmanager,didUpdateLocations locations: [CLLocation]) {
var userLocation:CLLocation = locations[0]
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
userLocation = CLLocation(latitude: lat,longitude: long)
print("My location: \(userLocation)")
}
我该如何计算,比方说最接近给定第4个数组的2?
我的想法是获取用户的当前位置,将其存储在数据库中,然后按位置对一些帖子进行排序。因此,如果我有用户位置和帖子位置,如何找到距离用户最近的2个?
谢谢