User:Argrath/extract coastline.pl

From OpenStreetMap Wiki
Jump to: navigation, search

要XML::TreePP

ソースはutf8で保存すること。

先頭付近でファイル名を指定しているので適時変更すること。

末尾付近でタグを設定しているので調整すること。

#! /usr/bin/perl
use strict;
use warnings;
use XML::TreePP;
use Data::Dumper;
use utf8;

my %point;
my %curve;

my %pointid;

my $newid = -10000;

my $x = XML::TreePP->new();

my $h = $x->parsefile('N03-090320_27.xml');

my $base = $h->{"ksj:GI"}->{dataset}->{'ksj:object'}->{'ksj:AA01'}->{'ksj:OBJ'};

my $p = $base->{'jps:GM_Point'};

for (@$p){
    my $id = $_->{'-id'};
    $id =~ s/^p//;
    $id += 0;
    $id = -$id;
    my $val = $_->{'jps:GM_Point.position'}->{'jps:DirectPosition'}->{'DirectPosition.coordinate'};

    $point{$id} = $val;
    $pointid{$val} = $id;
}


my $c = $base->{'jps:GM_Curve'};

for (@$c){
    my $id = $_->{'-id'};
    my $vals = $_->{'jps:GM_Curve.segment'}->{'jps:GM_LineString'}->{'jps:GM_LineString.controlPoint'}->{'jps:GM_PointArray'}->{'GM_PointArray.column'};
    my @ex = ();
    foreach (@$vals){
	if(defined $_->{'jps:GM_Position.indirect'}){
	    my $id = $_->{'jps:GM_Position.indirect'}->{'GM_PointRef.point'}->{'-idref'};
	    $id =~ s/^p//;
	    $id += 0;
	    $id = -$id;
	    push @ex, $id;
	} elsif(defined $_->{'jps:GM_Position.direct'}){
	    my $cord = $_->{'jps:GM_Position.direct'}->{'DirectPosition.coordinate'};
	    my $id = $pointid{$cord};
	    if(!defined $id){
		$id = $newid--;
		$point{$id} = $cord;
		$pointid{$cord} = $id;
	    }
	    push @ex, $id;
	    
	} else {
	    print "Error!\n";
	}
    }
    $curve{$id} = \@ex;
}

#print Dumper(\%point);
#print Dumper(\%curve);


open my $fw, '>:encoding(utf-8)', 'out.osm';

print $fw <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="ksj-osm-road.pl">
EOF
;

for (sort keys %point){
    my ($lat, $lon) = split / /, $point{$_};
    printf $fw '<node id="%d" visible="true" lat="%3.8f" lon="%3.8f">' . "\n",
    $_, $lat, $lon;
#    my %tag = %cite;
#    foreach (sort keys %tag){
#	printf $fw '<tag k="%s" v="%s" />', $_, $tag{$_};
#    }
    print $fw "</node>\n";
}

for (sort keys %curve){
    my $id = $_;
    printf $fw '<way id="%d" action="modify" visible="true">', $newid--;
    foreach (@{$curve{$id}}){
	printf $fw '<nd ref="%d" />', $_;
    }

    my %tag = (
	source => "MLIT, Japan",
	'source:ja' => "国土数値情報(海岸線データ)平成21年 国土交通省",
	source_ref => 'http://nlftp.mlit.go.jp/ksj/',
    );
	foreach (sort keys %tag){
	    printf $fw '<tag k="%s" v="%s" />', $_, $tag{$_};
	}
	print $fw "</way>\n";
}
print $fw "</osm>\n";
close $fw;