Last active
December 28, 2017 17:10
-
-
Save stefanbc/23a832d7dba319ca7358 to your computer and use it in GitHub Desktop.
Convert Google Maps Longitude / Latitude to degrees, minutes, seconds, direction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 . '° ' . $lng_min . '\' ' . $lng_sec . '" ' . $lng_dir . '<br>'; | |
echo $lat_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