Use awk to convert GPS Position to Latitude & Longitude

大兔子大兔子 提交于 2019-12-07 00:16:49

For this particular case, I would write it as below if special characters were a problem. Ofcourse it has the disadvantage that error checks would not be as stringent.

 # remove the string till the colon and characters other than numbers, dots, spaces and NSEW
 sed 's!^.*:\|[^0-9\. NSEW]!!g' filename |
 # calculate the latitude and longitude with some error checks
 awk '/^\s*([0-9.]+\s+){3}[NS]\s+([0-9.]+\s+){3}[EW]\s*$/ {
        lat=($1+$2/60+$3/3600); if ($4 == "S") lat=-lat;
        lon=($5+$6/60+$7/3600); if ($8 == "W") lon=-lon;
        printf("%.4f,%.4f\n", lat, lon); next  }

      { print "Error on line " NR; exit 1 }'

Here it is in PHP:

$parts = explode(" ",str_replace(array("deg",",","'","\""),"",$argv[1]));

print_r($parts);

$lat_deg = $parts[0];
$lat_min = $parts[1];
$lat_sec = $parts[2];
$lat_dir = $parts[3];

$lon_deg = $parts[4];
$lon_min = $parts[5];
$lon_sec = $parts[6];
$lon_dir = $parts[7];

if ($lat_dir == "N") {
    $lat_sin = "+";
    } else {
    $lat_sin = "-";
    }

if ($lon_dir == "N") {
    $lon_sin = "+";
    } else {
    $lon_sin = "-";
    }

$latitiude = $lat_sin.($lat_deg+($lat_min/60)+($lat_sec/3600));
$longitude = $lon_sin.($lon_deg+($lon_min/60)+($lon_sec/3600));

echo substr($latitiude,0,-5).",".substr($longitude,0,-5);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!