内容简介:翻译自:https://stackoverflow.com/questions/33927405/find-closest-longitude-and-latitude-in-array-from-user-location-ios-swift
在 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中的这段代码可能是一个很大的问题.
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
}
翻译自:https://stackoverflow.com/questions/33927405/find-closest-longitude-and-latitude-in-array-from-user-location-ios-swift
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- php – 将纬度/经度转换为城市名称? (反地理定位)
- 如何在iOS上获取变量中的位置(纬度和经度值)?
- Java 根据经纬度获取地理位置
- 多经纬度坐标的中心点计算方法
- python实现百度地图API获取某地址的经纬度
- arcgis for jsapi开发:坐标系、经纬度与平面坐标的互换
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Unity游戏设计与实现
[日]加藤政树 / 罗水东 / 人民邮电出版社 / 2015-2 / 79.00元
本书出自日本知名游戏公司万代南梦宫的资深开发人员之手,面向初级游戏开发人员,通过10个不同类型的游戏实例,展示了真正的游戏设计和实现过程。本书的重点并不在于讲解Unity的各种功能细节,而在于核心玩法的设计和实现思路。每个实例都从一个idea 开始,不断丰富,自然而然地推出各种概念,引导读者思考必要的数据结构和编程方法。掌握了这些思路,即便换成另外一种引擎,也可以轻松地开发出同类型的游戏。 ......一起来看看 《Unity游戏设计与实现》 这本书的介绍吧!
html转js在线工具
html转js在线工具
RGB CMYK 转换工具
RGB CMYK 互转工具