2

Suppose I have two points:

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

How can I calculate the distance between them, the simplest way? (taking into account the curvature of the earth)

I looked into this answer, but CCLocation doesn't have an initializer in Swift 2.0

Community
  • 1
  • 1
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • Have a look at this answer http://stackoverflow.com/a/34417444/742298 – Ashutosh Dave Feb 01 '16 at 05:54
  • *"CCLocation doesn't have an initializer in Swift 2.0"* – That is not correct. Just type `CCLocation(` in an Xcode source file and watch autocompletion do its magic. Or lookup the [documentation](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocation_Class/#//apple_ref/occ/instm/CLLocation/initWithLatitude:longitude:). Also your referenced Q&A http://stackoverflow.com/questions/22795059/calculating-distance-between-two-coordinates-using-cllocation has an answer using the Swift language. – Martin R Feb 01 '16 at 07:51

2 Answers2

5
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")
Dmitry
  • 14,306
  • 23
  • 105
  • 189
Casey
  • 6,531
  • 24
  • 43
  • Thanks! This is what I was looking for. How do I turn the distance into a float value? Also, I tried to put floats in the arguments but it doesn't seem to work. – TIMEX Feb 01 '16 at 06:19
  • distance is a ```CLLocationDistance``` which is a typealias for ```Double```. to convert to a float you do ```let floatDistance = Float(distance)``` – Casey Feb 01 '16 at 06:25
  • ```let floatValue: Float = 37.7833``` ```let degreesValue = CLLocationDegrees(floatValue)``` – Casey Feb 01 '16 at 06:27
2

I have been using this and works perfectly for me :-

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))


}
Mr. Bean
  • 4,221
  • 1
  • 19
  • 34