Tel +49 (30) 814504070

Andreas Gohr
29.06.2010 11:15 Uhr

Calculate a Destination Coordinate based on Distance and Bearing in PHP

Tags:

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();
}
Bookmark and Share

Comments

Older Comments

michael russell
2011/03/25 20:16

thank you so much - i was going through exactly the same difficulties

michael russell
2011/03/25 21:11

hi, what should be values for 'compass direction' be?

My input is 0=north. I'm trying to figure out how to adjust my input so that you function works.

Andreas Gohr
2011/03/28 09:40

Yes, 0 should be North. 90 is East, 180 South and 270 is West.

Rheza Satria
2011/04/13 16:45

Hi, thank you. It helps me a lot.

Jeremy Cook
2011/04/21 18:28

Thanks for this-it helped me a lot too. One small point-there are native PHP functions (deg2rad() and rad2deg()) to confirm degrees to and from radians.

Cosmo coordinates | Yourcomfortcaf
2012/01/27 03:58

[…] Calculate a Destination Coordinate based on Distance and Bearing … […]

About CosmoCode

CosmoCode is a Berlin based IT service provider with a strong emphasis on web applications. We mainly focus on Content Management Systems, Wikis and custom solutions.

Subscribe

Subscribe Like our blog? Stay up to date via RSS
Freie Stelle: Forschungsassistent Freie Stelle: Forschungsassistent