首页 > 解决方案 > 使用 Swift 从 1 个随机位置中找到 300 个目的地中最近的位置

问题描述

我有一组来自世界各地的 1000 个国际机场及其 GPS 位置。用户将输入一个城市,然后我将获得该城市的 GPS 位置。将有一个出发城市和一个国际机场。

我如何才能确定哪个国际机场离斯威夫特的出发城市最近?

我假设我使用 iOS 的位置管理器。

标签: swiftapilocation

解决方案


您可以找到这 300 个位置和用户位置之间的距离,并找到这个距离的最小距离。

IE

 //User Location
    var userLocation = CLLocation(latitude: 40.23432, longitude: -90.23423)

    //Airport locations
    var airportLocations = [CLLocation(latitude: 32.838383, longitude: -116.973915),
                            CLLocation(latitude: 38.033878, longitude: -121.960709),
                            CLLocation(latitude: 40.167206, longitude: -105.101929),
                            CLLocation(latitude: 47.530102, longitude: -122.032616),
                            CLLocation(latitude: 41.081757, longitude: -81.511452),
                            CLLocation(latitude: 41.584660, longitude: -87.500160)]

    //Return distance array according to user location from airport
    let distance = airportLocations.map { $0.distance(from: userLocation) / 1000 }

    print(distance)  //Distance in KM
   // [2519.6894818028723, 2739.3624011808256, 1264.4208604451956, 2659.4695966766976, 743.32894364251479, 274.85755129294074]

  // Find the minimum value is your nearest location from user location

推荐阅读