我有一组来自世界各地的1000个国际机场及其GPS位置。用户将输入一个城市,然后我将获得该城市的GPS位置。将有一个出发城市和一个国际机场。
如何确定斯威夫特哪个国际机场最靠近出发城市?
我假设我在iOS上使用位置管理器。
答案 0 :(得分:1)
您可以找到这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 { $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