Skip to content

Instantly share code, notes, and snippets.

@ckhung
Last active August 19, 2016 01:58
Show Gist options
  • Save ckhung/7f7337d718774dfe9c9b to your computer and use it in GitHub Desktop.
Save ckhung/7f7337d718774dfe9c9b to your computer and use it in GitHub Desktop.
convert csv containing lon,lat,name files into geojson
#!/usr/bin/perl -w
# see http://newtoypia.blogspot.tw/2015/07/csv-geojson.html
$prev = 0; # was there any previous output?
print "[\n";
while (<>) {
chomp;
next if (/^#/ or /^\s*$/);
@f = split /\s*,\s*/;
if (defined($F{lon}) and defined($F{lat})) {
print ",\n" if $prev;
@prop = ();
print qq({"type":"Feature", "geometry":{ "type":"Point","coordinates":[$f[$F{lon}],$f[$F{lat}]]}, "properties":{);
for ($i=0; $i<=$#f; ++$i) {
next if ($i==$F{lon} or $i==$F{lat});
push @prop, qq("$keys[$i]": "$f[$i]");
}
print join(',', @prop);
print qq(}});
$prev = 1;
} elsif (/\blon(gitude)?\b/i and /\blat(itude)?\b/i) {
# @f : index => key
for ($i=0; $i<=$#f; ++$i) {
$f[$i] = "lon" if $f[$i] =~ /\blon(gitude)?\b/i;
$f[$i] = "lat" if $f[$i] =~ /\blat(itude)?\b/i;
$F{$f[$i]} = $i;
}
# %F : key => index
die unless (defined($F{lon}) and defined($F{lat}));
@keys = @f;
}
}
print "\n]\n\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment