arrays - 查找用户坐标和坐标数组之间最近的位置
问题描述
我有以下代码来获取一个最近的位置:
我的数据:
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 个?
谢谢
解决方案
您需要做的就是调用sorted(by:)
而不是min(by:)
根据用于查找最小值的相同闭包对数组进行排序,然后您可以获取第一个n
元素以获取n
最接近用户的坐标。
extension Array where Element == CLLocation {
func sortedByDistance(to location: CLLocation) -> [CLLocation] {
return sorted(by: { location.distance(from: $0) < location.distance(from: $1) })
}
}
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)
let coords = [coord1, coord2, coord3]
let sortedCoordinates = coords.sortedByDistance(to: coord3)
print(sortedCoordinates)
let closestTwoCoordinates = sortedCoordinates.prefix(2)
推荐阅读
- javascript - 从 jQuery 函数更新和重新渲染 ACF 古腾堡块
- sql - Postgres 按修剪均值分组
- batch-file - 将 bat 文件中启动的程序置于前台
- ios - 无法创建 IXPlaceholder Xcode 12.5
- vue.js - 如何使用数据创建 BrowserWindow,并在 vue 应用程序中获取该数据?
- reactjs - 反应最终形式 | 具有外部字段依赖项的表单字段验证
- awk - 将标签添加到基本单词后合并两个单词列表
- c# - 我们的应用程序将托管在客户端服务器上。如何保护它发出的 HTTP 调用中的敏感数据?
- r - 在中创建 4 个变量的数据集
- c++ - boost::signals2 函数签名的 Doxygen 文档