gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:47:46 24 4
gpt4 key购买 nike

在发布的问题中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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com