<?php

// Utility functions dealing with GPS coordinates from EXIF data

define('NO_ALTITUDE', -1024);

// Convert a lat or lon 3-array to decimal degrees
function exif_degrees($a) {
  @eval("\$deg = $a[0]; \$min = $a[1]; \$sec = $a[2];");
  return $deg + $min / 60.0 + $sec / 3600.0;
}

// Extract lat, lon and altitude from an EXIF GPS array
function exif_gps_vars($exif, &$lat, &$lon, &$alt) {
  $gps = $exif['GPS'];
  $lat = exif_degrees($gps['GPSLatitude']);
  if ($gps['GPSLatitudeRef'] == 'S')
    $lat *= -1;
  $lon = exif_degrees($gps['GPSLongitude']);
  if ($gps['GPSLongitudeRef'] == 'W')
    $lon *= -1;
  if (isset($gps['GPSAltitude']))
    @eval("\$alt = {$gps['GPSAltitude']};");
  else
    $alt = NO_ALTITUDE;
}

// Convert decimal degrees to deg° min' sec" H
function exif_dec_to_DMS($dec, $hemi_pos, $hemi_neg) {
  $absdec = abs($dec);
  $deg = intval($absdec);
  $absdec = ($absdec - $deg) * 60;
  $min = intval($absdec);
  $sec = ($absdec - $min) * 60;
  return sprintf("%d° %02d′ %05.2f″ %s",
    $deg, $min, $sec, $dec >= 0 ? $hemi_pos : $hemi_neg
  );
}

// Convert an EXIF GPS array to HTML-usable text, optionally adorned
// with a geo microformat; see http://microformats.org/wiki/geo
function exif_to_html($exif, $geo=false) {
  exif_gps_vars($exif, $lat, $lon, $alt);
  $hlat = exif_dec_to_DMS($lat, 'N', 'S');
  $hlon = exif_dec_to_DMS($lon, 'E', 'W');
  $alt = intval($alt);
  if ($geo)
    $ret = "<span class=\"geo\">
    <abbr class=\"latitude\" title=\"$lat\">$hlat</abbr>,
    <abbr class=\"longitude\" title=\"$lon\">$hlon</abbr>
</span>";
  else
    $ret = "$hlat, $hlon";
  return $ret . ($alt == NO_ALTITUDE ? '' : " ($alt m)");
}

?>