Last active
August 19, 2016 01:58
-
-
Save ckhung/7f7337d718774dfe9c9b to your computer and use it in GitHub Desktop.
convert csv containing lon,lat,name files into geojson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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