从用户位置查找最接近的经度和纬度 - iOS Swift

12

这里发表的问题中,用户问道:

我有一个包含经纬度信息的数组。我有两个双精度变量代表我的用户位置。我希望测试我的用户位置与数组中其他位置之间的距离,以找出最近的位置。该怎么做?

我知道如何获取2个位置之间的距离,但是不清楚如何将其应用到位置数组中。

回答者给出了以下代码:

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);

我在一个应用程序中遇到了完全相同的问题,我认为这段代码可能非常适合。但是,我正在使用Swift,而这段代码是Objective-C。

我的唯一问题是:在Swift中应该看起来怎么样?

谢谢任何帮助。我对所有这些都很新,并且在Swift中看到这段代码可能会有所帮助。

3个回答

26

我为Swift 3创建了这段小的“函数式”代码:

let coord1 = CLLocation(latitude: 52.12345, longitude: 13.54321)
let coord2 = CLLocation(latitude: 52.45678, longitude: 13.98765)
let coord3 = CLLocation(latitude: 53.45678, longitude: 13.54455)

let coordinates = [coord1, coord2, coord3]

let userLocation = CLLocation(latitude: 52.23678, longitude: 13.55555)

let closest = coordinates.min(by: 
{ $0.distance(from: userLocation) < $1.distance(from: userLocation) })

22
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)")

或者作为一个函数:

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
}

现在我可以用这个来与Objective-C进行比较。它有多种帮助。谢谢! - tsteve

0
    func closestLoc(userLocation:CLLocation){
    var distances = [CLLocationDistance]()
    for location in locations{
        let coord = CLLocation(latitude: location.latitude!, longitude: location.longitude!)
        distances.append(coord.distance(from: userLocation))
        print("distance = \(coord.distance(from: userLocation))")
    }

    let closest = distances.min()//shortest distance
    let position = distances.index(of: closest!)//index of shortest distance
    print("closest = \(closest!), index = \(position)")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接