我创建了两个函数来计算从我的位置到x汽车的距离
func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
return from.distance(from: to)
}
func selT(car:Car) {
guard let coordinates = car.location else {
return
}
self.destination = coordinates
if currentLocation != nil {
let dist = distance(from: currentLocation!, to: coordinates)
}
}
我有一个下载汽车的功能
func getOkToDownload(download:CarsToDownload?, error : Error?) -> Void {
if let download = download {
self.download = download
if download.status == "OK" {
if let carsDownloaded = download.cars {
var number = numberCars / (categories?.count)!
number = number == 0 ? 1 : number
let distanceC = carsDownloaded
cars.append(contentsOf: carsDownloaded)
}
self.tableView?.reloadData()
} else {
let alert = UIAlertController.init(title: "Error", message: response.status, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction.init(title: "Retry", style: .default, handler: { (action) in
DispatchQueue.main.async {
self.showCars(true)
}
}))
self.present(viewController: alert)
}
showing = false
} else {
print("response is nil")
}
}
其中"汽车"是var cars: [Car] = []
和"下载"属于CarsToDownload
类型,因此download.cars
是我要下载的汽车,现在我要做的是创建一个按此功能排序的过滤器(getOkToDownload
)我从最近到最公平的车下载,为此我认为我必须创建一个计算carsDownloaded
的所有距离的循环,一旦我获得了值,请使用过滤器对数组进行排序但是我怎么能做到了吗?考虑到我得到了ax车的距离值与我向你展示的那些外部功能,现在我只在我的Car
课程中添加了这个参数var distanceT: Float?
(不知道它是否有用)
答案 0 :(得分:0)
实际所需的计算只有两件事:过滤距离的集合以及按距离对集合进行排序。我在Playground中投入了一些东西来说明该过程。下面唯一真正的提升是两行代码:过滤和排序。
let mileMultiplier = 0.000621371
let home = CLLocation(latitude: 34.043017, longitude: -118.267254)
let loc1 = CLLocation(latitude: 32.689596, longitude: -117.999806)
let loc2 = CLLocation(latitude: 33.556666, longitude: -117.659812)
let loc3 = CLLocation(latitude: 34.043017, longitude: -118.467254)
let loc4 = CLLocation(latitude: 35.501326, longitude: -116.751808)
let loc5 = CLLocation(latitude: 33.986546, longitude: -117.454548)
let collection = [loc1, loc2, loc3, loc4, loc5]
func geoQueryCollection(collection: [CLLocation], radiusInMiles: Double, sorted: Bool) -> [CLLocation] {
let results = collection.filter { $0.distance(from: home) * mileMultiplier < radiusInMiles }
return sorted ? results.sorted { $0.distance(from: home) < $1.distance(from: home) } : results
}
let results = geoQueryCollection(collection: collection, radiusInMiles: 200, sorted: false)
results.map { print(Int($0.distance(from: home) * mileMultiplier)) }
// prints: 94, 48, 11, 132, 46
let results2 = geoQueryCollection(collection: collection, radiusInMiles: 50, sorted: true)
results2.map { print(Int($0.distance(from: home) * mileMultiplier)) }
// prints: 11, 46, 48
您可能希望缓存距离计算,因此除了适合您需要的其他可能的细化之外,不要重复两次。但这是起点。