Created
August 7, 2014 03:16
-
-
Save dshorthouse/c2bc1896b12e1648e2bc to your computer and use it in GitHub Desktop.
Convert DDMMSS coordinates to array of DD latitude/longitude in PHP
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
/** | |
* Split DDMMSS or DD coordinate pair string into an array | |
* | |
* @param string $point A string purported to be a coordinate | |
* @return array(latitude, longitude) in DD | |
*/ | |
function make_coordinates($point) | |
{ | |
$loc = preg_replace(array('/[\p{Z}\s]/u', '/[^\d\s,;.\-NSEWO°ºdms\'"]/i'), array(' ', ''), $point); | |
if (preg_match('/[NSEWO]/', $loc) != 0) { | |
$coord = preg_split("/[,;]/", $loc); //split by comma or semicolon | |
if (count($coord) != 2 || empty($coord[1])) { | |
return array(null, null); | |
} | |
$coord = (preg_match('/[EWO]/', $coord[1]) != 0) ? $coord : array_reverse($coord); | |
return array(dms_to_deg(trim($coord[0])),dms_to_deg(trim($coord[1]))); | |
} else { | |
$coord = preg_split("/[\s,;]+/", trim(preg_replace("/[^0-9-\s,;.]/", "", $loc))); //split by space, comma, or semicolon | |
if (count($coord) != 2 || empty($coord[1])) { | |
return array(null, null); | |
} | |
return $coord; | |
} | |
} | |
/** | |
* Convert a coordinate in dms to deg | |
* | |
* @param string $dms coordinate | |
* @return float | |
*/ | |
function dms_to_deg($dms) | |
{ | |
$dms = stripslashes($dms); | |
$neg = (preg_match('/[SWO]/i', $dms) == 0) ? 1 : -1; | |
$dms = preg_replace('/(^\s?-)|(\s?[NSEWO]\s?)/i', '', $dms); | |
$pattern = "/(\\d*\\.?\\d+)(?:[°ºd: ]+)(\\d*\\.?\\d+)*(?:['m′: ])*(\\d*\\.?\\d+)*[\"s″ ]?/i"; | |
$parts = preg_split($pattern, $dms, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); | |
if (!$parts) { | |
return; | |
} | |
// parts: 0 = degree, 1 = minutes, 2 = seconds | |
$d = isset($parts[0]) ? (float)$parts[0] : 0; | |
$m = isset($parts[1]) ? (float)$parts[1] : 0; | |
if (strpos($dms, ".") > 1 && isset($parts[2])) { | |
$m = (float)($parts[1] . '.' . $parts[2]); | |
unset($parts[2]); | |
} | |
$s = isset($parts[2]) ? (float)$parts[2] : 0; | |
$dec = ($d + ($m/60) + ($s/3600))*$neg; | |
return $dec; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment