Skip to content

Instantly share code, notes, and snippets.

@pocketkk
Created September 12, 2014 15:16
Show Gist options
  • Save pocketkk/4ca0fd85f410395054d8 to your computer and use it in GitHub Desktop.
Save pocketkk/4ca0fd85f410395054d8 to your computer and use it in GitHub Desktop.
Swift - Distance between two lat and longs.
struct MapPoint {
var lat : Double = 0
var long : Double = 0
}
class DistanceCalculator {
var fromMP : MapPoint
var toMP : MapPoint
var fLat : Double!
var fLong : Double!
var tLat : Double!
var tLong : Double!
init(from: MapPoint, to: MapPoint){
fromMP = from
toMP = to
fLat = dToR(fromMP.lat)
fLong = dToR(fromMP.long)
tLat = dToR(toMP.lat)
tLong = dToR(toMP.long)
}
//Degrees to Radians
func dToR(val: Double) -> Double {
return val * M_PI / 180
}
func inMiles() -> Double {
var dlon = fLong - tLong
var dlat = fLat - tLat
let a = pow(sin(dlat/2), 2) + (cos(fLat) * cos(tLat)) * pow(sin(dlon/2), 2)
let c = 2 * atan2(sqrt(a), sqrt(1-a))
let d = 3961 * c
return d
}
func toString() -> String {
return "The two points are \(self.inMiles()) miles apart"
}
}
var mp1 = MapPoint(lat: 38.898556, long: -77.037852)
var mp2 = MapPoint(lat: 38.897147, long: -77.043934)
var dc = DistanceCalculator(from: mp1, to: mp2)
var distance = dc.inMiles()
println(dc.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment