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

时间:2015-11-25 22:18:25

标签: ios swift google-maps cllocationmanager cllocationdistance

在发布的问题here中,用户询问:

  

我有一个充满经度和纬度的阵列。我的用户位置有两个双变量。我想测试用户位置与阵列之间的距离,以查看最接近的位置。我该怎么做?

     

这将获得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 个答案:

答案 0 :(得分:20)

对于 Swift 3 ,我创建了一小段“功能”代码:

.whatever-class {
  display: none !important;
}

答案 1 :(得分:18)

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
}

答案 2 :(得分: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)")
}