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

标签 ios swift google-maps cllocationmanager cllocationdistance

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

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.

作为回应,他得到了如下代码:

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 代码可能会大有作为。

最佳答案

对于 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) })

关于ios - 从用户位置查找数组中最近的经度和纬度 - iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33927405/

相关文章:

swift - 在 Swift3 中没有更多上下文的表达式类型不明确

ios - 使用 Swift 协议(protocol)时短路

android - 使用 getLastKnownLocation() 获取位置无法获得正确的位置

objective-c - ios 替换 url 中的数据值

iOS Facebook : Fetching user data using storyboard

ios - 使用 CTMessageCenter 发送短信 (iOS 7)

ios - 将图像文件从 Parse 保存到 iPhone

ios - 使用 UIModalPresentationStyleCurrentContext 呈现 View Controller 时的布局问题

javascript - 使用 loadGeoJSON 时未捕获类型错误

ios - Google Maps iOS 选择所有标记