Skip to content

Instantly share code, notes, and snippets.

@hrpunio
Created September 11, 2013 13:54
Show Gist options
  • Save hrpunio/6523931 to your computer and use it in GitHub Desktop.
Save hrpunio/6523931 to your computer and use it in GitHub Desktop.
GPX track to KML conversion
#!/usr/bin/perl
#
# GPX track to KML conversion
use Getopt::Long;
my $color="ff0000ff";
my $number_w_sign="[\+\-]?[0-9\.]+";
my $quote_sign="[ \t]*[\"'][ \t]*";
my $segment = '';
my $kml_name='??????';
my @Segments ;
GetOptions( "name=s" => \$kml_name,) ;
while (<>) {
chomp();
if (/<trkpt lat=$quote_sign($number_w_sign)$quote_sign lon=$quote_sign($number_w_sign)$quote_sign/ ) { $lat= $1 ; $lon=$2 }
elsif (/<ele>($number_w_sign)/) { $ele = $1 }
elsif (/<\/trkpt>/) { $ele_txt = sprintf ("%.1f", $ele);
$segment .= "$lon,$lat,$ele_txt "; $lat=$lon=$ele=0; }
elsif (/<\/trkseg>/) {##
$segment = substr($segment, 0, -1);
push (@Segments, $segment);
$segment="";
}
}
#### #### #### ####
print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
print "<!-- Converted with gpx2kml.pl by tp -->\n";
print "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">\n";
print "<Document><name>$kml_name</name> <open>1</open>\n";
print "<Style id=\"Photo\"><IconStyle><Icon><href>http://maps.google.com/mapfiles/ms/icons/red.png</href></Icon></IconStyle></Style>\n";
print "<Style id=\"Track\"><LineStyle><color>$color</color><width>4</width></LineStyle><PolyStyle><color>$color</color></PolyStyle></Style>\n";
my $track_no=0;
for $s (@Segments) {
$track_no++;
start_track ($track_no);
print "$s";
stop_track();
}
print "</Document></kml>";
## ## ## ### ### ###
sub start_track {
my $t = shift;
print "<Placemark><name>Track $t</name><visibility>1</visibility><styleUrl>#Track</styleUrl>";
print "<LineString><extrude>1</extrude><tessellate>1</tessellate><coordinates>";
}
sub stop_track {
print "</coordinates></LineString></Placemark>\n\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment