You can use this
func getDistanceAndAngle(positionA: CLLocation, positionB: CLLocation) -> (Float, Float, Float){
let distanceInMeters = Float(positionA.distance(from: positionB)) // result is in meters
print(distanceInMeters)
//search for the degree
let angle = bearingFromLocation(fromLocation: positionA.coordinate, toLocation: positionB.coordinate)
print("ANGLE", angle)
let xDistance = abs(distanceInMeters * cos(DegreesToRadians(degrees: angle)))
let yDistance = abs(distanceInMeters * sin(DegreesToRadians(degrees: angle)))
return (xDistance,yDistance,angle)
}
func bearingFromLocation(fromLocation:CLLocationCoordinate2D, toLocation: CLLocationCoordinate2D)-> Float{
let lat1 = DegreesToRadians(degrees: Float(fromLocation.latitude))
let lon1 = DegreesToRadians(degrees: Float(fromLocation.longitude))
let lat2 = DegreesToRadians(degrees: Float(toLocation.latitude))
let lon2 = DegreesToRadians(degrees: Float(toLocation.longitude))
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
let radiansBearing = atan2(y, x)
print("radian", radiansBearing)
let degreesBearing = RadiansToDegrees(radians: radiansBearing)
print("deg", degreesBearing)
if (degreesBearing >= 0) {
return degreesBearing
} else {
return degreesBearing + 360.0
}
}
func DegreesToRadians(degrees: Float)->Float {return degrees * Float.pi / 180.0}
func RadiansToDegrees(radians: Float)->Float {return radians * 180.0/Float.pi}
notes:
the angle is from north to east
so north is 0 degree and east is 90 degree.
the X and Y is always positive. So if you want to make it negative to the left and down, you can try to put use degree to make it right.