ios - 如何在表格 View 中列出距离当前用户位置最近的用户 - iOS swift?

标签 ios swift xcode google-cloud-firestore cllocationmanager

这里我正在计算用户和司机的长途距离(以公里为单位)。现在我想在 TableView 中列出当前用户的驱动程序。目前我可以从驱动程序和用户端检索经纬度并计算它们之间的距离。

这里是使用的代码:

var requestArray     = [requestModel]()
var bookRequestArray = [String]()
var DriverArray      = [String]()
var subLoaclityArray = [String]()
var LocationArray    = [String]()

var doc_ID         : String = ""
var Start_Lat      : String = ""
var Start_Long     : String = ""
var Driver_Lat     : String = ""
var Driver_Long    : String = ""

var DriverLocation : CLLocation?
var userLocation   : CLLocation?
var nearestLoaction   : CLLocationDistance?

在这里获取数组中 firestore 的驱动程序

func loadDriverDoc(){

    self.db.collection("Driver_details").getDocuments() { (querySnapshot, err) in

        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("driverdocument::::::::::\(document.documentID) => \(document.data())")
                self.DriverArray.append(document.documentID)
                let Driver_lat = document.data()["Driver_Lat"] as? String
                print("Driver_lat:::::\(String(describing: Driver_lat))")
                self.Driver_Lat = Driver_lat!
                let Driver_long = document.data()["Driver_Long"] as? String
                print("Driver_long:::::\(String(describing: Driver_long))")
                self.Driver_Long = Driver_long!

                self.DistanceCal()


            }
            DispatchQueue.main.async {


            }


        }

    }


}

此处计算用户与司机之间的距离

func DistanceCal() {

     DriverLocation = CLLocation(latitude: Double(Driver_Lat)!, longitude: Double(Driver_Long)!)
     userLocation   = CLLocation(latitude: Double(Start_Lat)!, longitude: Double(Start_Long)!)

    //this is the distance between driverLocation and startLocation (in km)
    let distance = (DriverLocation?.distance(from: userLocation!))!/1000

    //Display the result in km
    print(String(format: "The distance to driver is %.01fkm", distance))


    if (distance <= 1000) {



    } else if (distance <= 2000) {


    } else if (distance <= 3000) {


    } else {



    }

}//DistanceCal

这里从firestore获取用户数据

func loadDoc() {

    getFireBaseToken { token in


            self.db.collection("Current_booking").getDocuments() { (querySnapshot, err) in
                if let err = err {
                    print("Error getting documents: \(err)")
                } else {
                    for document in querySnapshot!.documents {
                        print("document::::::::::\(document.documentID) => \(document.data())")
                        self.bookRequestArray.append(document.documentID)
                        print("doc::::\(self.bookRequestArray)")
                        let Start_lat = document.data()["Start_Lat"] as? String
                        print("Start_lat::::::\(String(describing: Start_lat))")
                        self.Start_Lat = Start_lat!
                        let Start_long = document.data()["Start_Long"] as? String
                        print("Start_long::::::\(String(describing: Start_long))")
                        self.Start_Long = Start_long!

                         self.loadDriverDoc()
                    }
                    DispatchQueue.main.async {

                        self.requestTableView.reloadData()

                    }
                }
            }


    }//get firebase token

}//loadDoc

最佳答案

我建议创建一个新对象

struct Driver { 
   var docID: String!
   var location: CLLocation!
   var distanceFromUser: CLLocationDistance?
}

同样在变量声明的类之上创建一个驱动程序数组:
var drivers = [Driver]()
您下载所有驱动程序并初始化驱动程序的结构,之后为每个驱动程序计算与当前用户之间的距离,并将 distanceFromUser 分配给每个驱动程序。这样做之后你应该排序

drivers.sort(by: {($0.distanceFromUser ?? 999999.9) < ($1.distanceFromUser ?? 999999.9)})
tableView.reloadData()

我给了 999999.9,因为 distanceFromUser 是可选的,如果没有计算,驱动程序将留在列表的底部。在 tableView(_:cellForRowAt:) 中,您应该访问 drivers[indexPath.row]drivers[indexPath.section],具体取决于您使用哪种方式使用 TableView 。

关于ios - 如何在表格 View 中列出距离当前用户位置最近的用户 - iOS swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894896/

相关文章:

ios - swift |如何以编程方式将尾随空格添加到 UILabel?

iphone - 触摸 uiTabBar 上方

ios - 获取 "Type ' Float' 不符合协议(protocol) 'ForwardIndex' “Xcode Beta 4 中的范围错误

ios - 当我从自定义构建配置存档时缺少文件

ios - fatal error : file has been modified since the precompiled header

iOS Safari 粘性输入底部不需要的空白

ios - 创建应用程序无法下载的ios链接

ios - 收到错误 "Type ViewController does not conform to protocol ' UITableViewDataSource ...“即使我有所需的功能

ios - 如何删除 UIBarButtonItem 的左填充?

Swift:如何在完成体内调用我的函数?