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

栏目: Swift · 发布时间: 6年前

内容简介:翻译自: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. Id like to test the distance between my users 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 Id 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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Reversing

Reversing

艾拉姆(Eilam,E.) / 韩琪、杨艳、王玉英、李娜 / 电子工业出版社 / 2007-9 / 79.00元

本书描述的是在逆向与反逆向之间展开的一场旷日持久的拉锯战。作者Eldad Eilam以一个解说人的身份为我们详尽地评述了双方使用的每一招每一式的优点与不足。 书中包含的主要内容有:操作系统的逆向工程;.NET平台上的逆向工程;逆向未公开的文件格式和网络协议;逆向工程的合法性问题;拷贝保护和数字版权管理技术的逆向工程;防止别人对你的代码实施逆向工程的各种技术;恶意程序的逆向工程;反编译器的基本......一起来看看 《Reversing》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具