How to compare user'r current location to other locations and display them in UITable View?
When you want to calculate the distance between two locations you can do the following:
let userLocation = CLLocation(latitude: lat, longitude: long)let destinationLocation = CLLocation(latitude: (dest.lat as NSString).doubleValue, longitude: (dest.long as NSString).doubleValue)let distance = userLocation.distanceFromLocation(destinationLocation)
Get the userLocation which is the current location of the user. Then you have the location of the destination and then calculate the distance with the help of the distanceFromLocation
function which is a part of CoreLocation
.
Then I have done a method that rounds the distance to nearest 5 meters:
var distanceToFive = roundToFive(distance)private func roundToFive(x : Double) -> Int { return 5 * Int(round(x / 5.0))}
You can of course change this to 10, 20 etc.
Edit:
And to get the current location:
Add the CLLocationManagerDelegate
to the class inheritance. Declare var locationManager = CLLocationManager()
and two variables one for lat and one for long. In viewDidLoad
do
self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest }
And then to get the location for the user declare the following methods:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location:CLLocationCoordinate2D = manager.location!.coordinate lat = location.latitude long = location.longitude } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Error") }
Edit2:
func CalculateDistance() -> Int{ let userLocation = CLLocation(latitude: lat, longitude: long) let destinationLocation = CLLocation(latitude:latitude, longitude: longitude)// latitude and longitude from the json file let distance = userLocation.distanceFromLocation(destinationLocation) return roundToFive(distance)}private func roundToFive(x : Double) -> Int { return 5 * Int(round(x / 5.0))}