splitbrain.org

electronic brain surgery since 2001

Calculate a Destination Coordinate based on Distance and Bearing in PHP

Today I had to calculate a bunch of geo coordinates. All I had was a starting point and distance and direction of the destination. I googled a bit and soon found a nice description along with some JavaScript code.

Should be easy to port to PHP. Or so I thought. For some reason it simply didn't work. I got no errors but the resulting points were way off. A bit more googling found me a similar solution in python. But again my port didn't work.

When I started to carefully compare all internal variable values in each step between my port and the Python script, I finally found the problem. PHP's standard modulo operator % does only return integer remainders! Replacing the % with a call to fmod fixed everything. Learned a new thing today :-).

Here's the final code:

/**
 * Calculate a new coordinate based on start, distance and bearing
 *
 * @param $start array - start coordinate as decimal lat/lon pair
 * @param $dist  float - distance in kilometers
 * @param $brng  float - bearing in degrees (compass direction)
 */
function geo_destination($start,$dist,$brng){
    $lat1 = toRad($start[0]);
    $lon1 = toRad($start[1]);
    $dist = $dist/6371.01; //Earth's radius in km
    $brng = toRad($brng);
 
    $lat2 = asin( sin($lat1)*cos($dist) +
                  cos($lat1)*sin($dist)*cos($brng) );
    $lon2 = $lon1 + atan2(sin($brng)*sin($dist)*cos($lat1),
                          cos($dist)-sin($lat1)*sin($lat2));
    $lon2 = fmod(($lon2+3*pi()),(2*pi())) - pi();  
 
    return array(toDeg($lat2),toDeg($lon2));
}
function toRad($deg){
    return $deg * pi() / 180;
}
function toDeg($rad){
    return $rad * 180 / pi();
}
This post was originally published on cosmocode.de
Tags:
php, programming, gis
Similar posts: