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

前端 未结 3 1100
长发绾君心
长发绾君心 2021-02-08 12:16

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

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-08 12:56

    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
    }
    

提交回复
热议问题