Skip to content

Instantly share code, notes, and snippets.

@will83
Last active November 1, 2022 10:21
Show Gist options
  • Save will83/0c3e07b172ed2f4572a1e672007aa273 to your computer and use it in GitHub Desktop.
Save will83/0c3e07b172ed2f4572a1e672007aa273 to your computer and use it in GitHub Desktop.
PHP function to translate WGS84 to GPS coordinates
<?php
$lat = -24.108764;
$lng = 16.500156;
function WGS84toGPS($lat, $lng){
$lat = number_format($lat, 6);
$lng = number_format($lng, 6);
// define latitude coordinate with minutes and seconds
$lat_card = ($lat > 0) ? 'N' : 'S';
$whole = ($lat > 0) ? abs(floor($lat)) : abs(ceil($lat)); // x digits before coma // 24
$decimals = (abs($lat) - $whole) * 100; // 6 digits after coma // 108764
$min = floor($decimals * .6); // floor(6.52584) // 6
$sec = ($decimals * .6) - $min; // (6.52584) - 6 // 0.52584
$sec = round($sec*60, 1); // round(31.5504, 1) // 31.6
$min = ($min >= 10) ? $min : '0'.$min;
$sec = ($sec >= 10) ? $sec : '0'.$sec;
$gps_lat = $whole.'°'.$min.'\''.$sec.'"'.$lat_card;
// define longitude coordinate with minutes and seconds
$lng_card = ($lng > 0) ? 'E' : 'W';
$whole = ($lng > 0) ? abs(floor($lng)) : abs(ceil($lng)); // x digits before coma // 16
$decimals = (abs($lng) - $whole) * 100; // 6 digits after coma // 500156
$min = floor($decimals * .6); // floor(6.52584) // 6
$sec = ($decimals * .6) - $min; // (6.52584) - 6 // 0.52584
$sec = round($sec*60, 1); // round(31.5504, 1) // 31.6
$min = ($min >= 10) ? $min : '0'.$min;
$sec = ($sec >= 10) ? $sec : '0'.$sec;
$gps_lng = $whole.'°'.$min.'\''.$sec.'"'.$lng_card;
return $gps_lat.' '.$gps_lng;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment