| 1 | package SVG::Shapefile; | ||
| 2 | |||
| 3 | use Geo::Shapelib; | ||
| 4 | use File::Basename; | ||
| 5 | use Compress::Zlib; | ||
| 6 | use DBI; | ||
| 7 | use CSS::Tiny; | ||
| 8 | use SVG; | ||
| 9 | use strict; | ||
| 10 | use warnings; | ||
| 11 | |||
| 12 | our $VERSION = '0.01'; | ||
| 13 | =pod | ||
| 14 | |||
| 15 | =head1 NAME SVG::Shapefile | ||
| 16 | |||
| 17 | =head1 SYNOPSIS | ||
| 18 | |||
| 19 | my $shp = SVG::Shapefile->new( %options ); | ||
| 20 | $shp->render('filename.svg'); | ||
| 21 | |||
| 22 | =head1 METHODS | ||
| 23 | |||
| 24 | =head2 new( %args ) | ||
| 25 | |||
| 26 | new() takes the following arguments: | ||
| 27 | |||
| 28 | =over 4 | ||
| 29 | |||
| 30 | =item ShapeFile | ||
| 31 | |||
| 32 | Path to the ESRI shapefile to parse. The .shx and .dbf components | ||
| 33 | should be in the same directory. | ||
| 34 | |||
| 35 | =item PolygonID | ||
| 36 | |||
| 37 | If defined, the name of the column from the .dbf component that should | ||
| 38 | be used as the identifier for each polygon. If undefined, the ID | ||
| 39 | is borrowed directly from the shapefile. | ||
| 40 | |||
| 41 | =item DataFile | ||
| 42 | |||
| 43 | The XBase (DBF), Excel, or CSV file to read data values from. | ||
| 44 | |||
| 45 | =item DataTable | ||
| 46 | |||
| 47 | If DataFile is an Excel spreadsheet, the name of the worksheet | ||
| 48 | to read data values from. | ||
| 49 | |||
| 50 | =item KeyColumn | ||
| 51 | |||
| 52 | The column from DataFile containing the polygon IDs. | ||
| 53 | |||
| 54 | =item ValueColumn | ||
| 55 | |||
| 56 | The column from DataFile containing the values to be mapped. | ||
| 57 | |||
| 58 | =item Scale | ||
| 59 | |||
| 60 | A constant multiplier applied to all vertices in the ShapeFile. | ||
| 61 | Used to scale up ShapeFile coordinates to something displayable | ||
| 62 | in SVG. Defaults to 1,000,000 if not specified. | ||
| 63 | |||
| 64 | =item Colors | ||
| 65 | |||
| 66 | A list of two lists, each containing an [R, G, B] triplet. The | ||
| 67 | first triplet is the RGB color assigned to the minimum data value, | ||
| 68 | the second triplet is the color assigned to the maximum. | ||
| 69 | |||
| 70 | =back | ||
| 71 | |||
| 72 | =cut | ||
| 73 | |||
| 74 | sub new { | ||
| 75 | my ($class, %args) = @_; | ||
| 76 | $args{Scale} ||= 1_000_000; | ||
| 77 | $args{Colors} ||= [[255,255,255], [0,0,255]]; | ||
| 78 | my $self = bless \%args, ref($class) || $class; | ||
| 79 | $self->shapefile if $self->{ShapeFile}; | ||
| 80 | $self->dataset if $self->{DataFile}; | ||
| 81 | return $self; | ||
| 82 | } | ||
| 83 | |||
| 84 | sub shapefile { | ||
| 85 | my $self = shift; | ||
| 86 | return $self->{ShapeObj} if $self->{ShapeObj}; | ||
| 87 | |||
| 88 | $self->{ShapeFile} = shift if @_; | ||
| 89 | |||
| 90 | my ($file, $path) = fileparse($self->{ShapeFile}, ".shp"); | ||
| 91 | $self->{ShapeObj} = Geo::Shapelib->new( "$path/$file" ) | ||
| 92 | or die "Can't load $path/$file: $!\n"; | ||
| 93 | |||
| 94 | $self->polygon_id( $self->{PolygonID} ) | ||
| 95 | if $self->{PolygonID}; | ||
| 96 | $self->group_by($self->{GroupBy}) if $self->{GroupBy}; | ||
| 97 | |||
| 98 | return $self->{ShapeObj}; | ||
| 99 | } | ||
| 100 | |||
| 101 | sub polygon_id { | ||
| 102 | my $self = shift; | ||
| 103 | |||
| 104 | return $self->{KeyIndex} if defined $self->{KeyIndex}; | ||
| 105 | $self->{PolygonID} = shift if @_; | ||
| 106 | |||
| 107 | my @names = $self->shape_columns; | ||
| 108 | for my $i (0 .. $#names) { | ||
| 109 | if (lc $names[$i] eq lc $self->{PolygonID}) { | ||
| 110 | $self->{KeyIndex} = $i; | ||
| 111 | last; | ||
| 112 | } | ||
| 113 | } | ||
| 114 | return $self->{KeyIndex}; | ||
| 115 | } | ||
| 116 | |||
| 117 | |||
| 118 | sub group_by { | ||
| 119 | my $self = shift; | ||
| 120 | $self->{GroupBy} = shift if @_; | ||
| 121 | my @names = $self->shape_columns; | ||
| 122 | for my $i (0 .. $#names) { | ||
| 123 | if (lc $names[$i] eq lc $self->{GroupBy}) { | ||
| 124 | $self->{GroupIndex} = $i; | ||
| 125 | last; | ||
| 126 | } | ||
| 127 | } | ||
| 128 | return $self->{GroupIndex}; | ||
| 129 | } | ||
| 130 | |||
| 131 | sub groups { | ||
| 132 | my $self = shift; | ||
| 133 | my $dbf = $self->dataset or return; | ||
| 134 | # cant select distninct against some drivers | ||
| 135 | my $s = "select ".$self->{GroupBy}." from ".$self->{DataTable}; | ||
| 136 | my $rows = $dbf->selectall_arrayref($s); | ||
| 137 | my %groups = map {$_->[0] => 1} @$rows; | ||
| 138 | return (keys %groups); | ||
| 139 | } | ||
| 140 | |||
| 141 | sub filter { | ||
| 142 | my $self = shift; | ||
| 143 | my $in = shift; | ||
| 144 | my $out; | ||
| 145 | my $filter = $self->{Filter} or return 1; | ||
| 146 | foreach (@$filter) { | ||
| 147 | $out = 1 if $_ eq $in; | ||
| 148 | } | ||
| 149 | return $out; | ||
| 150 | } | ||
| 151 | |||
| 152 | sub svg { | ||
| 153 | my ($self) = @_; | ||
| 154 | return $self->{SVG} if $self->{SVG}; | ||
| 155 | |||
| 156 | my ($min_x, $max_x, $min_y, $max_y, %shapes); | ||
| 157 | my $scale = $self->{Scale}; | ||
| 158 | my $shp = $self->shapefile; | ||
| 159 | my $poly_id = $self->polygon_id; | ||
| 160 | |||
| 161 | my $records = $shp->{ShapeRecords}; | ||
| 162 | my $shapes = $shp->{Shapes}; | ||
| 163 | my %groups; | ||
| 164 | my $group_by = $self->group_by; | ||
| 165 | for my $i (0 .. $#$shapes) { | ||
| 166 | my $poly = $shapes->[$i]; | ||
| 167 | my @points; | ||
| 168 | for my $vertex (@{$poly->{Vertices}}) { | ||
| 169 | my ($x, $y) = @$vertex; | ||
| 170 | $x = int( $x * $scale ); | ||
| 171 | $y = int( $y * $scale ); | ||
| 172 | $min_x = $x if not defined $min_x or $x < $min_x; | ||
| 173 | $max_x = $x if not defined $max_x or $x > $max_x; | ||
| 174 | $min_y = $y if not defined $min_y or $y < $min_y; | ||
| 175 | $max_y = $y if not defined $max_y or $y > $max_y; | ||
| 176 | next if @points and $points[-2] == $x and $points[-1] == $y; | ||
| 177 | push @points, $x, $y; | ||
| 178 | } | ||
| 179 | |||
| 180 | my $id = $poly->{ShapeId}; | ||
| 181 | my $poly_num = $records->[$i][$poly_id]; | ||
| 182 | $id = $poly_num if $poly_num; | ||
| 183 | $id =~ s/\W//gos; | ||
| 184 | my $filter = $self->filter($id); | ||
| 185 | next if not $filter; | ||
| 186 | |||
| 187 | if (defined($group_by) | ||
| 188 | and my $g_id = $records->[$i][$group_by]) { | ||
| 189 | $g_id =~ s/\W//gos; | ||
| 190 | $groups{$g_id}{$id} = join ",", @points; | ||
| 191 | } | ||
| 192 | else { | ||
| 193 | push @{$shapes{$id}}, join ",", @points; | ||
| 194 | } | ||
| 195 | } | ||
| 196 | my ($width,$height) = ($max_x-$min_x,$max_y-$min_y); | ||
| 197 | my $svg = SVG->new( viewBox => "$min_x -$max_y $width $height" ); | ||
| 198 | |||
| 199 | my $group = $svg->group( | ||
| 200 | id => 'shapefile', | ||
| 201 | transform => 'scale(1,-1)', | ||
| 202 | style => {stroke => 'black', 'stroke-width' => 10, fill => 'none'}, | ||
| 203 | ); | ||
| 204 | |||
| 205 | while (my ($id, $set) = each %shapes) { | ||
| 206 | for my $pts (@$set) { | ||
| 207 | $group->polygon( class => "id$id", points => $pts ); | ||
| 208 | } | ||
| 209 | } | ||
| 210 | |||
| 211 | my %subs; | ||
| 212 | foreach my $g (keys %groups) { | ||
| 213 | $subs{$g} ||= $group->group(id => $g); | ||
| 214 | my $subgroup = $subs{$g}; | ||
| 215 | while (my ($id,$pts) = each %{ $groups{$g} }) { | ||
| 216 | $subgroup->polygon( class => "id$id", points => $pts ); | ||
| 217 | } | ||
| 218 | } | ||
| 219 | |||
| 220 | $self->{SVG} = $svg; | ||
| 221 | return $svg; | ||
| 222 | } | ||
| 223 | |||
| 224 | sub render { | ||
| 225 | my ($self, $svgfile) = @_; | ||
| 226 | |||
| 227 | my ($base, $path, $ext) = fileparse( $svgfile, qr/\.svgz?/ ); | ||
| 228 | my $output = $self->svg->render; | ||
| 229 | $output =~ s/(<svg ) | ||
| 230 | /<?xml-stylesheet href="$base.css" type="text\/css"?>\n$1/osx; | ||
| 231 | |||
| 232 | open my($xml), ">", $svgfile | ||
| 233 | or die "Can't write to $svgfile: $!\n"; | ||
| 234 | |||
| 235 | if ($svgfile =~ /gz$/io) { | ||
| 236 | print $xml compress( $output, Z_BEST_COMPRESSION ); | ||
| 237 | } else { | ||
| 238 | print $xml $output; | ||
| 239 | } | ||
| 240 | |||
| 241 | $self->stylesheet->write("$path/$base.css") | ||
| 242 | if $self->stylesheet; | ||
| 243 | } | ||
| 244 | |||
| 245 | sub color_scale { | ||
| 246 | my ($self, $val, $min, $max) = @_; | ||
| 247 | my ($color1, $color2) = @{$self->{Colors}}; | ||
| 248 | my @target; | ||
| 249 | $val = ($max == $min ? .5 : ($val - $min) / ($max - $min)); | ||
| 250 | $target[$_] = int( $color1->[$_] + ($color2->[$_] - $color1->[$_]) * $val ) | ||
| 251 | for 0 .. $#$color1; | ||
| 252 | return \@target; | ||
| 253 | } | ||
| 254 | |||
| 255 | sub color { | ||
| 256 | my ($self, $val) = @_; | ||
| 257 | if (exists $self->{Colors}{$val}) { | ||
| 258 | return $self->{Colors}{$val}; | ||
| 259 | } else { | ||
| 260 | return; | ||
| 261 | } | ||
| 262 | } | ||
| 263 | |||
| 264 | sub dataset { | ||
| 265 | my $self = shift; | ||
| 266 | return $self->{DBF} if $self->{DBF}; | ||
| 267 | |||
| 268 | $self->{DataFile} = shift if @_; | ||
| 269 | $self->{DataTable} = shift if @_; | ||
| 270 | return unless $self->{DataFile}; | ||
| 271 | |||
| 272 | my ($table, $path, $type) = fileparse($self->{DataFile}, qr/\..*/); | ||
| 273 | my $connect = { | ||
| 274 | ".dbf" => "dbi:XBase:$path", | ||
| 275 | ".xls" => "dbi:Excel:file=$path/$table.xls", | ||
| 276 | ".csv" => "dbi:CSV:f_dir=$path" | ||
| 277 | } -> {$type}; | ||
| 278 | |||
| 279 | $self->{DataType} = $type; | ||
| 280 | $self->{DataTable} ||= $table; | ||
| 281 | $self->{DBF} = DBI->connect( $connect, undef, undef, {RaiseError => 1} ); | ||
| 282 | return $self->{DBF}; | ||
| 283 | } | ||
| 284 | |||
| 285 | sub stylesheet { | ||
| 286 | my $self = shift; | ||
| 287 | return $self->{CSS} if $self->{CSS}; | ||
| 288 | |||
| 289 | my $dbf = $self->dataset or return; | ||
| 290 | |||
| 291 | my $rows = $dbf->selectall_arrayref(qq{ | ||
| 292 | select $self->{KeyColumn}, $self->{ValueColumn} | ||
| 293 | from $self->{DataTable} }); | ||
| 294 | |||
| 295 | my ($min, $max, %data); | ||
| 296 | for my $row (@$rows) { | ||
| 297 | my ($key, $val) = @$row; | ||
| 298 | # $val =~ s/,//gos; # de-commify numeric values | ||
| 299 | # next unless $val =~ /^[-+]?[\d\.]+$/o; | ||
| 300 | # $data{$key} += $val; | ||
| 301 | # $min = $data{$key} if not defined $min or $min > $data{$key}; | ||
| 302 | # $max = $data{$key} if not defined $max or $max < $data{$key}; | ||
| 303 | $data{$key} = $val; | ||
| 304 | } | ||
| 305 | |||
| 306 | my $style = CSS::Tiny->new; | ||
| 307 | while (my ($key, $val) = each %data) { | ||
| 308 | # my $color = $self->color_scale( $val, $min, $max ); | ||
| 309 | my $color = $self->color($val) or next; | ||
| 310 | my $rgb = join(",", @$color); | ||
| 311 | |||
| 312 | $key =~ s/\W//gos; # clean up key names | ||
| 313 | $style->{".id$key"}{fill} = "rgb($rgb)"; | ||
| 314 | } | ||
| 315 | |||
| 316 | $self->{CSS} = $style; | ||
| 317 | return $style; | ||
| 318 | } | ||
| 319 | |||
| 320 | sub shape_columns { | ||
| 321 | my $self = shift; | ||
| 322 | my $shp = $self->shapefile or return; | ||
| 323 | my $names = $shp->{FieldNames}; | ||
| 324 | return @$names; | ||
| 325 | } | ||
| 326 | |||
| 327 | sub data_tables { | ||
| 328 | my $self = shift; | ||
| 329 | my $dbf = $self->dataset or return; | ||
| 330 | my $st = $dbf->table_info; | ||
| 331 | my $data = $st->fetchall_arrayref; | ||
| 332 | return map( $_->[2], @$data ); | ||
| 333 | } | ||
| 334 | |||
| 335 | sub data_columns { | ||
| 336 | my $self = shift; | ||
| 337 | my $dbf = $self->dataset or return; | ||
| 338 | if ($self->{DataType} eq ".xls") { | ||
| 339 | my $cols = $dbf->{xl_tbl}{$self->{DataTable}}{col_names}; # ugh! | ||
| 340 | return grep( !/^COL_\d+_$/o, @$cols ); | ||
| 341 | } elsif ($self->{DataType} eq ".csv") { | ||
| 342 | my $cols = $dbf->{csv_tables}{$self->{DataTable}}{col_names}; | ||
| 343 | return @$cols; | ||
| 344 | } elsif ($self->{DataType} eq ".dbf") { | ||
| 345 | return $dbf->{xbase_tables}{$self->{DataTable}}->field_names; | ||
| 346 | } else { | ||
| 347 | my $st = $dbf->column_info( undef, undef, $self->{DataTable}, '%' ); | ||
| 348 | my $data = $st->fetchall_arrayref({}); | ||
| 349 | return map( $_->[2], @$data ); | ||
| 350 | } | ||
| 351 | } | ||
| 352 | |||
| 353 | 1; |