stefanbc
10/23/2014 - 7:02 PM

Convert Google Maps Longitude / Latitude to degrees, minutes, seconds, direction

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;
?>