在发布的问题中here https://stackoverflow.com/questions/24783442/find-closest-longitude-and-latitude-in-array-from-user-location?answertab=active#tab-top,用户问:
我有一个充满经度和纬度的数组。我的用户位置有两个双变量。我想根据我的阵列测试用户位置之间的距离,看看哪个位置最近。我该怎么做呢?
这将获得两个位置之间的距离,但很难理解我如何针对一系列位置进行测试。
作为回应,他得到了以下代码:
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 中的这段代码可能会很有帮助。
For 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) })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)