0

Below is a formula (Great Circle algorithm) that I want to be translated into PHP. I would really appreciate if someone would help me with that?

The input is to different sets of coordinates, e.g:

Place 1 Lat: 59.389057
Place 1 Long: 17.937422

Place 2 Lat: 59.388914
Place 2 Long: 17.920441

The wanted output is the distance between place 1 and place 2.

distance = ((115.1666667 * (lat2-lat1)) ^ 2 + (115.1666667 * (lng2 - lng1) * cos(lat2 / 57.3)) ^ 2) ^ .5

My try:

$distance = pow(((115.1666667 * ($lat2 - $lat1)), 2) + (115.1666667 * pow(($lng2 - $lng1) * cos($lat2 / 57.3)), 2)), 0.5)
hakre
  • 193,403
  • 52
  • 435
  • 836
holyredbeard
  • 19,619
  • 32
  • 105
  • 171
  • Why is your try poor? How could you improve it? How can you test it to show that it is working? Where do you hit the roadblock to translate the formula? What are the input values? What are the expected output values? [delref](http://stackoverflow.com/q/14091549/367456) – hakre Dec 30 '12 at 15:28
  • 2
    This is a pretty good example of "temporary variables make things easier to read". – DCoder Dec 30 '12 at 15:52

2 Answers2

3

As DCoder writes in the comments, temporary variables make things easier to read:

$latD = (691 / 6) * ($lat2 - $lat1);
$lngD = (691 / 6) * ($lng2 - $lng1) * cos($lat2 / 57.3);

$distance = sqrt( $latD * $latD + $lngD * $lngD );

(demo on codepad.org)

Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
1

Here's the corrected code:

$distance = pow((pow((115.1666667 * ($lat2 - $lat1)), 2) + pow((115.1666667 * ($lng2 - $lng1) * cos($lat2 / 57.3)), 2)), 0.5);
Shoe
  • 74,840
  • 36
  • 166
  • 272