【问题标题】:Given two sets of coordinates, how do I calculate the distance between them?给定两组坐标,如何计算它们之间的距离?
【发布时间】:2016-02-01 05:52:23
【问题描述】:

假设我有两点:

var lat1 =  37.7833 
var lon1 = -122.4167
var lat2 =  39.4811 
var lon2 = -118.9558

如何计算它们之间的距离,最简单的方法? (考虑到地球的曲率)

我查看了this 的答案,但CCLocation 在 Swift 2.0 中没有初始化器

【问题讨论】:

标签: ios swift


【解决方案1】:
let coord1 = CLLocation(latitude: 37.7833, longitude: -122.4167)
let coord2 = CLLocation(latitude: 39.4811, longitude: -118.9558)
let distance = coord1.distance(from: coord2)

print("the distance between the two points is: \(distance) meters")

【讨论】:

  • 谢谢!这就是我一直在寻找的。如何将距离转换为浮点值?另外,我尝试将浮点数放入参数中,但它似乎不起作用。
  • 距离是CLLocationDistance,它是Double 的类型别名。转换为浮点数你做let floatDistance = Float(distance)
  • let floatValue: Float = 37.7833 let degreesValue = CLLocationDegrees(floatValue)
【解决方案2】:

我一直在使用它并且非常适合我:-

static let  DEG_TO_RAD = 0.017453292519943295769236907684886
static let  EARTH_RADIUS_IN_METERS = 6372797.560856

static func calculateDistance(fromlat : Double, fromlon : Double, tolat : Double, tolon : Double) -> Double {


    let latitudeArc : Double   = (fromlat - tolat) * DEG_TO_RAD
    let longitudeArc : Double  = (fromlon - tolon) * DEG_TO_RAD
    var latitudeH : Double   = sin(latitudeArc * 0.5)
    latitudeH  *= latitudeH
    var lontitudeH : Double  = sin(longitudeArc * 0.5)
    lontitudeH *= lontitudeH
    let tmp : Double  = cos(fromlat*DEG_TO_RAD) * cos(tolat*DEG_TO_RAD)
    return EARTH_RADIUS_IN_METERS * 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH))


}

【讨论】:

  • 这会返回仪表吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 2020-02-12
相关资源
最近更新 更多