使用awk将GPS位置转换为Latitude&经度

时间:2015-10-01 04:53:29

标签: bash awk gps

我正在编写一个基于EXIF标头重命名文件的bash脚本。 exiftool返回以下GPS位置字符串,我需要将其格式化为纬度/经度坐标,以便与Google Maps API一起使用。

GPS Position : 40 deg 44' 49.36" N, 73 deg 56' 28.18" W

Google地图:

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.7470444,-073.9411611

这是我的代码

awk -v FS="[ \t]" '{print $0,substr($1,length($1),1)substr($2,length($2),1)}' $1 \
| sed 's/\xc2\xb0\([0-9]\{1,2\}\).\([NEWS]\)/ \1 0 \2/g;s/\xc2\xb0\([NEWS]\)/ 0 0 \1/g;s/[^0-9NEWS]/ /g' \
| awk '{if ($9=="NE") {printf ("%.4f\t%.4f\n",$1+$2/60+$3/3600,$5+$6/60+$7/3600)} \
else if ($9=="NW") {printf ("%.4f\t%.4f\n",$1+$2/60+$3/3600,-($5+$6/60+$7/3600))} \
else if ($9=="SE") {printf ("%.4f\t%.4f\n",-($1+$2/60+$3/3600),$5+$6/60+$7/3600)} \
else if ($9=="SW") {printf ("%.4f\t%.4f\n",-($1+$2/60+$3/3600),-($5+$6/60+$7/3600))}}' 

我收到了这个错误:

sed: RE error: illegal byte sequence

我需要的是一个有效的awk命令来删除“deg”和NSEW文本,并按照这个帖子除以3600和60:

how to convert gps north and gps west to lat/long in objective c

40度44'49.36“N,73度56'28.18”W> 40.7470444,-073.9411611

请帮忙!

2 个答案:

答案 0 :(得分:1)

对于这种特殊情况,如果特殊字符出现问题,我会按如下所示编写。当然,它的缺点是错误检查不会那么严格。

 # 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 }'

答案 1 :(得分:0)

这是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);