我一直在尝试显示tableView上的距离,但我无法让它发生。这个问题跟随这个问题:CLLocationDistance conversion。我检查了距离。在我Location
类使用此功能:显示与mapKit Swift用户的距离(英里/公里)
// Get distance
func distance(to location: CLLocation) -> CLLocationDistance {
return location.distance(from: self.location)
}
如何获取用户当前的位置:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
// Add a lastUserLocation to LocationManager and update it every time that the delegate receives a new location
LocationManager.shared.lastUserLocation = locations.last
LocationManager.shared.sortLocationsInPlace()
self.mapView.showsUserLocation = true
}
排序功能的LocationManager:
func getSortedLocations(userLocation: CLLocation) -> [Location] {
return locations.sorted { (l1, l2) -> Bool in
return l1.distance(to: userLocation) < l2.distance(to: userLocation)
}
}
func sortLocationsInPlace() {
if let validLocation = lastUserLocation {
locations.sort { (l1, l2) -> Bool in
return l1.distance(to: validLocation) < l2.distance(to: validLocation)
}
}
}
cellForRowAt:
var sortedLocations = [Location]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath)
let location = sortedLocations[indexPath.row]
cell.textLabel?.text = location.name
return cell
}
更新
内Location
类:
class Location {
var name: String
var latitude: Double
var longitude: Double
var location:CLLocation {
return CLLocation(latitude: latitude, longitude: longitude)
}
init?(json: JSON) {
guard let name = json["name"] as? String, let latitude = json["latitude"] as? Double, let longitude = json["longitude"] as? Double else { return nil }
self.name = name
self.latitude = latitude
self.longitude = longitude
}
func distance(to location: CLLocation) -> CLLocationDistance {
return location.distance(from: self.location)
}
}
您的问题未提供足够的信息。您在表格视图中显示的数组中的条目是什么?不同对象的CLLocation位置?你是否应该计算一系列位置和用户当前位置之间的距离?你的函数'distance()'如何被调用?请编辑您的问题以提供有关上述信息。 –
你在'LocationManager.shared.location'中有什么?在我看来,你使用它而不是'lastUserLocation'做你的比较 – jvrmed
@JavierMedina请看我的更新的问题 – mninety5