#!/usr/bin/perl
# par2kml -- 台灣地籍 .par 格式中幾筆地中心點轉成 KML
# Taiwan cadastral .par format to KML for a range of center points
# 給地號，輸出每筆中心點
# Given parcel numbers, returns each's center point.
# Copyright       : http://www.fsf.org/copyleft/gpl.html
# Author          : 積丹尼 Dan Jacobson -- http://jidanni.org/
# Created On      : Thu Apr 14 10:43:42 2011
# Last Modified On: Sat Dec 22 10:15:12 2012
# Update Count    : 156
use strict;
use warnings FATAL => 'all';
use constant USAGE => "Usage 例:
\$ ls
le0714.bnp le0714.coa le0714.par
\$ $0 le0714 低地號 高地號 [低附號 高附號] [[Easting correction]] [[[Northing correction]]] 例如
\$ $0 le0714 3250 3260
\$ $0 le0714 3250 3260 0 0 -7 6
To get all parcels, use e.g.,
\$ $0 le0714 1 99999 0 99999 -7 6
";
use Geography::NationalGrid;
use Geography::NationalGrid::TW;
my (
    %parcels,   %correction,   $filebasename, $parcelmin,
    $parcelmax, $subparcelmin, $subparcelmax
);
$_ = shift || 0
  for $filebasename, $parcelmin, $parcelmax, $subparcelmin, $subparcelmax,
  $correction{Easting},
  $correction{Northing};
die USAGE unless $filebasename && $parcelmin && $parcelmax;
@ARGV = ("$filebasename.par");

while (<>) {
    next
      unless
/^(?<parcel>.{4})(?<subparcel>.{4}).{35}(?<Northing>.{9})(?<Easting>.{8}).../;
    next unless $+{parcel} >= $parcelmin;
    next unless $+{parcel} <= $parcelmax;
    next unless $+{subparcel} >= $subparcelmin;
    next unless $+{subparcel} <= $subparcelmax;
    for my $parcel (
        ( sprintf "%04d", $+{parcel} + 0 ) . "-" . ( $+{subparcel} + 0 ) )
    {
        map { $parcels{$parcel}{$_} = $+{$_} } qw/Easting Northing/;
    }
}
die "尋無符合地號" unless keys %parcels;
print <<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
EOF
for my $parcel ( sort keys %parcels ) {
    my $p = new Geography::NationalGrid::TW(
        Projection => q(TWD67),
        map { $_ => $parcels{"$parcel"}{$_} + $correction{$_} }
          qw/Easting Northing/
    );
    $p = $p->transform(q(TWD97));
    printf
"  <Placemark><name>%s</name><Point><coordinates>%f,%f</coordinates></Point></Placemark>\n",
      $parcel, $p->longitude, $p->latitude;
}
print <<EOF;
 </Document>
</kml>
EOF
