使用 Swift 从 1 个随机位置找到 300 个目的地中最近的位置
Finding the closest location out of 300 destinations from 1 random location using Swift
我有一组来自世界各地的 1000 个国际机场及其 GPS 位置。用户将输入一个城市,然后我将获得该城市的 GPS 位置。将有一个出发城市和一个国际机场。
我如何才能确定哪个国际机场距离 Swift 的出发城市最近?
我假设我使用 iOS 的位置管理器。
你可以求出这300个位置和用户位置之间的距离,并从这个距离求出最小距离。
即
//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 { [=10=].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
我有一组来自世界各地的 1000 个国际机场及其 GPS 位置。用户将输入一个城市,然后我将获得该城市的 GPS 位置。将有一个出发城市和一个国际机场。
我如何才能确定哪个国际机场距离 Swift 的出发城市最近?
我假设我使用 iOS 的位置管理器。
你可以求出这300个位置和用户位置之间的距离,并从这个距离求出最小距离。
即
//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 { [=10=].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