-
Notifications
You must be signed in to change notification settings - Fork 26
/
csv2geojson
executable file
·92 lines (71 loc) · 1.33 KB
/
csv2geojson
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/perl
use strict;
sub csv {
my $line = $_[0];
chomp $line;
$line =~ s/\015//;
my @ret = ();
my $n = 0;
my $quoted = 0;
while ($line ne "") {
if ($line =~ s/^""//) {
$ret[$n] .= '"';
} elsif ($line =~ s/^"//) {
$quoted = !$quoted;
} elsif ($line =~ s/^,//) {
if ($quoted) {
$ret[$n] .= ',';
} else {
$n++;
}
} else {
$line =~ s/^([^",]*)//;
$ret[$n] .= $1;
}
}
return @ret;
}
sub quote {
my $s = @_[0];
$s =~ s/\\/\\\\/g;
$s =~ s/"/\\"/g;
return $s;
}
my $line = <>;
chomp;
my @fields = csv($line);
print "{\n";
print "\"type\": \"FeatureCollection\",\n";
print "\"features\": [\n";
my $first = 1;
while (<>) {
chomp;
my @cols = csv($_);
my %val = ();
for (my $i = 0; $i <= $#cols; $i++) {
$val{$fields[$i]} = $cols[$i];
}
{
if ($first != 1) {
print ",\n";
}
$first = 0;
print "{ \"type\": \"Feature\", \"properties\": { ";
for (my $i = 0; $i <= $#cols; $i++) {
if ($i != 0) {
print ", ";
}
print "\"" . quote($fields[$i]) . "\": ";
if ($cols[$i] =~ /^-?[0-9.]+$/ && !($cols[$i] =~ /\..*\./)) {
print "$cols[$i]";
} else {
print "\"" . quote($cols[$i]) . "\"";
}
}
print "}, \"geometry\": { ";
print "\"type\": \"Point\", \"coordinates\": ";
print "[ $val{'lng'},$val{'lat'} ]";
print "} }\n";
}
}
print "] }\n";