PvDev
PvDev

Reputation: 829

How to list closest user from current user location in a table view - iOS swift?

Here i am calculating user and driver lat long distance in km. Now i want list driver from user current in table view. Currently i can able to retrieve lat long from driver and user side and calculated distance between them.

here is the code used :

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?

Here getting driver lat long for firestore in array

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 {


            }


        }

    }


}

Here calculating distance between user and driver

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

here getting user data from 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

Upvotes: 0

Views: 134

Answers (1)

DionizB
DionizB

Reputation: 1507

Well I would suggest creating a new object

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

Also on top of class in variable declaration create an array of drivers:
var drivers = [Driver]()
You download all the drivers and init the structures of drivers, after that for every driver you calculate distance between to the current user and you assign to every driver distanceFromUser. After doing that you should sort

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

I gave 999999.9, since distanceFromUser is optional and if it isn't calculated that driver stays on bottom of the list. In tableView(_:cellForRowAt:) you should access drivers[indexPath.row] or drivers[indexPath.section] depending which way are you using the table view.

Upvotes: 2

Related Questions