Search code examples
iosswiftgoogle-mapscllocationmanagercllocationdistance

Find closest longitude and latitude in array from user location - iOS Swift


In the question posted here, the user asked:

I have an array full of longitudes and latitudes. I have two double variables with my users location. I'd like to test the distance between my user's locations against my array to see which location is the closest. How do I do this?

This will get the distance between 2 location but stuggeling to understand how I'd test it against an array of locations.

In response, he got the following code:

NSArray *locations = //your array of CLLocation objects
CLLocation *currentLocation = //current device Location

CLLocation *closestLocation;
CLLocationDistance smallestDistance = DBL_MAX; // set the max value

for (CLLocation *location in locations) {
    CLLocationDistance distance = [currentLocation  distanceFromLocation:location];

    if (distance < smallestDistance) {
        smallestDistance = distance;
        closestLocation = location;
    }
}
NSLog(@"smallestDistance = %f", smallestDistance);

I have the exact same problem in an application I'm working on, and I think this piece of code could work perfectly. However, I'm using Swift, and this code is in Objective-C.

My only question is: how should it look in Swift?

Thanks for any help. I'm new to all of this, and seeing this piece of code in Swift could be a big leg up.


Solution

  • var closestLocation: CLLocation?
    var smallestDistance: CLLocationDistance?
    
    for location in locations {
      let distance = currentLocation.distanceFromLocation(location)
      if smallestDistance == nil || distance < smallestDistance {
        closestLocation = location
        smallestDistance = distance
      }
    }
    
    print("smallestDistance = \(smallestDistance)")
    

    or as a function:

    func locationInLocations(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? {
      if locations.count == 0 {
        return nil
      }
    
      var closestLocation: CLLocation?
      var smallestDistance: CLLocationDistance?
    
      for location in locations {
        let distance = location.distanceFromLocation(location)
        if smallestDistance == nil || distance < smallestDistance {
          closestLocation = location
          smallestDistance = distance
        }
      }
    
      print("closestLocation: \(closestLocation), distance: \(smallestDistance)")
      return closestLocation
    }