【发布时间】:2020-03-04 10:54:18
【问题描述】:
我有以下代码来获取一个最近的位置:
我的数据:
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 个?
谢谢
【问题讨论】:
-
尝试使用与获取最近位置相同的谓词对数组进行排序
标签: arrays swift core-location cllocation