Perl で、Google Maps からルートを検索する方法

米国に限られるが、Perl には Geo::Google というモジュールがある。このモジュールを利用すると Google Maps からルートを検索できる。以下は、サンフランシスコダウンタウンのユニオンスクウェアにあるヒルトンからPIER 39までのルート検索の結果を XML で出力する例。

使用するモジュール


use Encode;
use Geo::Google;
#!/usr/bin/perl use Encode; use Geo::Google; # 変数の初期化 our $GEO = new Geo::Google; our $XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; our $output = ''; # xml 出力 our ($dist); $dist->{from} = qq|333 Ofarrell St, San Francisco, CA|; # From の住所 (米国のみ) $dist->{to } = qq|39 PIER 39, San Francisco, CA|; # To の住所 (米国のみ) $output = getPath($dist); $output = $XML_HEADER
    .    "<markers>\n"
    .    $output
    .    "</markers>\n";
print "Content-type: text/xml\n\n"; # XML を送るときは絶対にこれが必要!!! MUST!!! print $output; exit; sub getPath {
my ($dist) = shift;
my $output;

my $path = $GEO->path(getDegrees($dist->{from}), getDegrees($dist->{to}));
my @segments = $path->segments();

foreach my $s (@segments) {

    my $description = $s->text();
    $description =~ s/</&amp;lt;/g;
    $description =~ s/>/&amp;gt;/g;

    $output .= "\t<route\n"
            .  "\t\tdescription=\"" . $description . "\"\n"
            .  "\t/>\n";

    my @points = $s->points;
    foreach my $p (@points) {
        $output .= "\t<path lng=\"" . $p->longitude . "\" lat=\"" . $p->latitude . "\" />\n";
    }
}
return $output;
} sub getDegrees { # 住所から緯度経度を検索
return $GEO->location( address => Encode::encode_utf8(shift));
                                                    # shift = address / リファレンスを返す
} 1;
Content-type: text/xml <?xml version="1.0" encoding="UTF-8"?>
<route
    description="Head <b>east</b> from <b>Ofarrell St</b>"
/>
<route
    description="Turn <b>left</b> at <b>Grant Ave</b>"
    />
<path lng="-122.40966" lat="37.78621" />
<path lng="-122.40932" lat="37.78628" />
<path lng="-122.40894" lat="37.78632" />
<path lng="-122.40803" lat="37.78644" />
<path lng="-122.40639" lat="37.78663" />
<path lng="-122.40529" lat="37.78676" />
<path lng="-122.40485" lat="37.78683" />
<path lng="-122.40485" lat="37.78683" />
<route
    description="Turn <b>left</b> at <b>Sutter St</b>"
/>
<path lng="-122.40504" lat="37.78774" />
<path lng="-122.40513" lat="37.78819" />
<path lng="-122.40524" lat="37.78870" />
<path lng="-122.40530" lat="37.78913" />
<path lng="-122.40533" lat="37.78931" />
<path lng="-122.40539" lat="37.78964" />
<path lng="-122.40539" lat="37.78964" />

Comments