scrap pad

distance between geographic coordinates

I did this by converting the spherical (ish) longitude and latitude coordinates to vectors, finding the angle between the vectors, then finding the arc length based on that angle and the Earth's radius. It involved conversion between spherical and rectangular coordinates, dot products, and the arc length formula. Because doing this more than once by hand stinks, I fed a space-delineated list of longitudes and latitudes to this php script:


// $text_coords = "longitude1,latitude1 longitude2,latitude2 ...";

$coords = explode(' ', $text_coords);

$last_lat = NULL;
$last_long = NULL;
$total_dist = 0;

foreach ($coords as $co) {
  list($long, $lat) = explode(',', $co);

  if ($last_lat !== NULL) {
    // calculate distance, add to total
    $a_lat= deg2rad(90-$lat);
    $a_long = deg2rad(360+$long);
    $a[0] = sin($a_lat) * cos($a_long);
    $a[1] = sin($a_lat) * sin($a_long);
    $a[2] = cos($a_lat);

    $b_lat = deg2rad(90-$last_lat);
    $b_long = deg2rad(360+$last_long);
    $b[0] = sin($b_lat) * cos($b_long);
    $b[1] = sin($b_lat) * sin($b_long);
    $b[2] = cos($b_lat);
    $angle = abs(acos($a[0]*$b[0] + $a[1]*$b[1] + $a[2]*$b[2]));
    $total_dist += 6378.1 * $angle;
  $last_lat = $lat;
  $last_long = $long;

printf("distance in kilometers: %s\ndistance in miles: %s\n", 
  $total_dist, $total_dist/1.609344);

The space-delimited list of longitudes and latitudes just happens to be the way paths are stored in KML files. The point of this whole exercise was to find out how far I biked Monday morning: 19.7 miles, if my math is any good. For distances this short, factoring the curvature of the Earth is pretty silly; I'd tell you how silly, but not tonight.

notes after finding out how silly: if the points are close together (mine are less than half a mile apart), the straight line between them is basically indistinguishable from the arc between them. But after converting to rectangular coordinates, it's easier and makes more sense to calculate angle and arc length.

notes after talking to Evan: yes, the Pythagorean Theorem is a easy and fairly accurate way to find the distance between points using their latitude and longitude (rather than converting lat and long to sperical coords), but you have to find an approximate factor of degrees longitude to miles in a particular latitude, and it only works for that particular latitude (and the corresponding latitude on the other side of the equator). And good luck finding the distance between far away places.


who I am