| 1 | package Geo::Coder::Google::V2; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | our $VERSION = '0.19_01'; | ||
| 6 | |||
| 7 | use Carp; | ||
| 8 | use JSON; | ||
| 9 | use HTTP::Request; | ||
| 10 | use LWP::UserAgent; | ||
| 11 | use URI; | ||
| 12 | |||
| 13 | sub new { | ||
| 14 | my($class, %param) = @_; | ||
| 15 | |||
| 16 | my $ua = delete $param{ua} || LWP::UserAgent->new(agent => __PACKAGE__ . "/$VERSION"); | ||
| 17 | my $host = delete $param{host} || 'maps.google.com'; | ||
| 18 | my $language = delete $param{language}; | ||
| 19 | my $gl = delete $param{gl}; | ||
| 20 | my $oe = delete $param{oe} || 'utf8'; | ||
| 21 | |||
| 22 | bless { ua => $ua, host => $host, language => $language, gl => $gl, oe => $oe }, $class; | ||
| 23 | } | ||
| 24 | |||
| 25 | sub ua { | ||
| 26 | my $self = shift; | ||
| 27 | if (@_) { | ||
| 28 | $self->{ua} = shift; | ||
| 29 | } | ||
| 30 | $self->{ua}; | ||
| 31 | } | ||
| 32 | |||
| 33 | sub geocode { | ||
| 34 | my $self = shift; | ||
| 35 | |||
| 36 | my %param; | ||
| 37 | if (@_ % 2 == 0) { | ||
| 38 | %param = @_; | ||
| 39 | } else { | ||
| 40 | $param{location} = shift; | ||
| 41 | } | ||
| 42 | |||
| 43 | my $location = $param{location} | ||
| 44 | or Carp::croak("Usage: geocode(location => \$location)"); | ||
| 45 | |||
| 46 | my $uri = URI->new("http://$self->{host}/maps/geo"); | ||
| 47 | my %query_parameters = (q => $location, output => 'json'); | ||
| 48 | $query_parameters{hl} = $self->{language} if defined $self->{language}; | ||
| 49 | $query_parameters{gl} = $self->{gl} if defined $self->{gl}; | ||
| 50 | $query_parameters{oe} = $self->{oe}; | ||
| 51 | $uri->query_form(%query_parameters); | ||
| 52 | |||
| 53 | my $res = $self->{ua}->get($uri); | ||
| 54 | |||
| 55 | if ($res->is_error) { | ||
| 56 | Carp::croak("Google Maps API returned error: " . $res->status_line); | ||
| 57 | } | ||
| 58 | |||
| 59 | my $json = JSON->new->utf8; | ||
| 60 | my $data = $json->decode($res->content); | ||
| 61 | |||
| 62 | my @placemark = @{ $data->{Placemark} || [] }; | ||
| 63 | wantarray ? @placemark : $placemark[0]; | ||
| 64 | } | ||
| 65 | |||
| 66 | 1; | ||
| 67 | __END__ |