Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figuring out distance and course between two coordinates

I have 2 coordinates and would like to do something seemingly straightforward. I want to figure out, given:

1) Coordinate A 2) Course provided by Core Location 3) Coordinate B

the following:

1) Distance between A and B (can currently be done using distanceFromLocation) so ok on that one. 2) The course that should be taken to get from A to B (different from course currently traveling)

Is there a simple way to accomplish this, any third party or built in API?

Apple doesn't seem to provide this but I could be wrong.

Thanks, ~Arash

EDIT:

Thanks for the fast responses, I believe there may have been some confusion, I am looking to get the course (bearing from point a to point b in degrees so that 0 degrees = north, 90 degrees = east, similar to the course value return by CLLocation. Not trying to compute actual turn by turn directions.

like image 709
iOS4Life Avatar asked Nov 15 '25 13:11

iOS4Life


1 Answers

I have some code on github that does that. Take a look at headingInRadians here. It is based on the Spherical Law of Cosines. I derived the code from the algorithm on this page.

/*-------------------------------------------------------------------------
* Given two lat/lon points on earth, calculates the heading
* from lat1/lon1 to lat2/lon2.
*
* lat/lon params in radians
* result in radians
*-------------------------------------------------------------------------*/
double headingInRadians(double lat1, double lon1, double lat2, double lon2)
{
    //-------------------------------------------------------------------------
    // Algorithm found at http://www.movable-type.co.uk/scripts/latlong.html
    //
    // Spherical Law of Cosines
    //
    // Formula: θ = atan2( sin(Δlong) * cos(lat2),
    // cos(lat1) * sin(lat2) − sin(lat1) * cos(lat2) * cos(Δlong) )
    // JavaScript:
    //
    // var y = Math.sin(dLon) * Math.cos(lat2);
    // var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    // var brng = Math.atan2(y, x).toDeg();
    //-------------------------------------------------------------------------
    double dLon = lon2 - lon1;
    double y = sin(dLon) * cos(lat2);
    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);

    return atan2(y, x);
}
like image 186
progrmr Avatar answered Nov 17 '25 08:11

progrmr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!