Thanks for pointing out the PHP's deg2rad requirement. That was the
problem.
...Rene
On 7-Feb-07, at 7:30 PM, Gregory Beaver wrote:
M5 wrote:
I found a nice javascript function that takes two points of
latitude and
longitude and returns a midpoint. I'm now trying to rewrite in
PHP, but
having some problems. Here's the original javascript function, taken
from http://www.movable-type.co.uk/scripts/LatLong.html :
LatLong.midPoint = function(p1, p2) {
var dLon = p2.lon - p1.lon;
var Bx = Math.cos(p2.lat) * Math.cos(dLon);
var By = Math.cos(p2.lat) * Math.sin(dLon);
lat3 = Math.atan2(Math.sin(p1.lat)+Math.sin(p2.lat),
Math.sqrt((Math.cos(p1.lat)+Bx)*(Math.cos(p1.lat)+Bx) + By*By ) );
lon3 = p1.lon + Math.atan2(By, Math.cos(p1.lat) + Bx);
if (isNaN(lat3) || isNaN(lon3)) return null;
return new LatLong(lat3*180/Math.PI, lon3*180/Math.PI);
}
And here's my PHP variant, which isn't working:
function midpoint ($lat1, $lng1, $lat2, $lng2) {
$dlng = $lng2 - $lng1;
$Bx = cos($lat2) * cos($dlng);
$By = cos($lat2) * sin($dlng);
$lat3 = atan2( sin($lat1)+sin($lat2),
sqrt((cos($lat1)+$Bx)*(cos($lat1)+$Bx) + $By*$By ));
$lng3 = $lng1 + atan2($By, (cos($lat1) + $Bx));
$pi = pi();
return ($lat3*180)/$pi .' '. ($lng3*180)/$pi;
}
Any ideas why it's returning wrong values?
Are you converting from degrees to radians? With identical input, the
javascript function is identical to the PHP function (I tested to
verify)
I got this by reading at the bottom of the page:
" * Notes: trig functions take arguments in radians, so latitude,
longitude, and bearings in degrees (either decimal or
degrees/minutes/seconds) need to be converted to radians, rad =
π.deg/180. When converting radians back to degrees (deg = 180.rad/π),
West is negative if using signed decimal degrees. For bearings, values
in the range -π to +π (-180° to +180°) need to be converted to 0 to
+2π
(0°–360°); this can be done by (brng+2.π)%2.π where % is the modulo
operator. View page source to see JavaScript functions to handle these
conversions.
* The atan2() function widely used here takes two arguments,
atan2(y, x), and computes the arc tangent of the ratio y/x. It is more
flexible than atan(y/x), since it handles x=0, and it also returns
values in all 4 quadrants -π to +π (the atan function returns
values in
the range -π/2 to +π/2).
* If you implement any formula involving atan2 in Microsoft Excel,
you will need to reverse the arguments, as Excel has them the opposite
way around from JavaScript – conventional order is atan2(y, x), but
Excel uses atan2(x, y)
* For miles, divide km by 1.609344
* For nautical miles, divide km by 1.852
* Thanks to Ed Williams’ Aviation Formulary for many of the
formulae
"
Greg
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php