Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point to location using compass Swift

I am developing a compass that can point from my current location to other location of the object. Currently I am following this link: Point to location using compass

I feel that pointing between my current location to the object isn't correct. Can anyone help me how to develop compass that can point from my current location to other location of the object?

like image 852
Enter Echhean Avatar asked Feb 05 '16 06:02

Enter Echhean


1 Answers

To compute the angle between your location and a target location, you need 4 input variables :

1) current location (obtained from Core Location)

2) target location (known)

3) current heading (relative to true north, obtained from Core Location)

4) bearing, angle between true north and your target, you can get it using the following code:

private func getBearing(point1: CLLocationCoordinate2D, point2: CLLocationCoordinate2D) -> Double {

    let lat1 = point1.latitude.degreesToRadians
    let lon1 = point1.longitude.degreesToRadians

    let lat2 = point2.latitude.degreesToRadians
    let lon2 = point2.longitude.degreesToRadians

    let dLon = lon2 - lon1

    let y = sin(dLon) * cos(lat2)
    let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)

    var radiansBearing = atan2(y, x)
    if radiansBearing < 0 {
        radiansBearing += 2 * Double.pi
    }

    return radiansBearing.radiansToDegrees
}

Then you can compute the angle between you and your target using the following code :

/// Compute the angle between two map points and the from point heading
/// returned angle is between 0 and 360 degrees
private func doComputeAngleBetweenMapPoints(
    fromHeading: CLLocationDirection,
    _ fromPoint: CLLocationCoordinate2D,
    _ toPoint: CLLocationCoordinate2D
) -> CLLocationDirection {
    let bearing = getBearing(point1: fromPoint, point2: toPoint)
    var theta = bearing - fromHeading
    if theta < 0 {
        theta += 360
    }
    return theta
}
like image 60
michael-martinez Avatar answered Oct 27 '22 19:10

michael-martinez