Skip to content

Instantly share code, notes, and snippets.

@stefanbc
Last active December 28, 2017 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanbc/23a832d7dba319ca7358 to your computer and use it in GitHub Desktop.
Save stefanbc/23a832d7dba319ca7358 to your computer and use it in GitHub Desktop.
Convert Google Maps Longitude / Latitude to degrees, minutes, seconds, direction
<?php
function format_latlong($decimal, &$degrees, &$minutes, &$seconds, &$direction, $type = true) {
//set default values for variables passed by reference
$degrees = 0;
$minutes = 0;
$seconds = 0;
$direction = 'X';
//decimal must be integer or float no larger than 180;
//type must be Boolean
if(!is_numeric($decimal) || abs($decimal) > 180 || !is_bool($type)) {
return false;
}
//inputs OK, proceed
//type is latitude when true, longitude when false
//set direction; north assumed
if($type && $decimal < 0) {
$direction = 'S';
}
elseif(!$type && $decimal < 0) {
$direction = 'W';
}
elseif(!$type) {
$direction = 'E';
}
else {
$direction = 'N';
}
//get absolute value of decimal
$d = abs($decimal);
//get degrees
$degrees = floor($d);
//get seconds
$seconds = ($d - $degrees) * 3600;
//get minutes
$minutes = floor($seconds / 60);
//reset seconds
$seconds = floor($seconds - ($minutes * 60));
}
?>
<?php
// Usage
format_latlong($location['lng'], $lng_deg, $lng_min, $lng_sec, $lng_dir, false);
format_latlong($location['lat'], $lat_deg, $lat_min, $lat_sec, $lat_dir, true);
echo $lng_deg . '&deg; ' . $lng_min . '\' ' . $lng_sec . '" ' . $lng_dir . '<br>';
echo $lat_deg . '&deg; ' . $lat_min . '\' ' . $lat_sec . '" ' . $lat_dir;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment