| 1 | package Geo::Coder::Cloudmade; | ||
| 2 | |||
| 3 | our $VERSION = '0.7'; | ||
| 4 | |||
| 5 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | |||
| 7 | 1 | ▶ | use Carp qw(croak); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 1 | ▶ | use Encode; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 0 | ▶ | use JSON::Syck; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 10 | use HTTP::Request; | ||
| 11 | use LWP::UserAgent; | ||
| 12 | use URI; | ||
| 13 | |||
| 14 | |||
| 15 | sub new { | ||
| 16 | my $class = shift; | ||
| 17 | my $args = ref( $_[0] ) ? $_[0] : { @_ }; | ||
| 18 | |||
| 19 | my $ua = $args->{ua} || LWP::UserAgent->new( agent => __PACKAGE__ . "/$VERSION" ); | ||
| 20 | my $host = $args->{host} || 'geocoding.cloudmade.com'; | ||
| 21 | |||
| 22 | unless( exists($args->{apikey}) ) | ||
| 23 | { | ||
| 24 | croak "Required parameter 'apikey' not specified"; | ||
| 25 | }; | ||
| 26 | |||
| 27 | my $self = { | ||
| 28 | apikey => $args->{apikey}, | ||
| 29 | ua => $ua, | ||
| 30 | host => $host, | ||
| 31 | }; | ||
| 32 | bless $self, $class; | ||
| 33 | |||
| 34 | return( $self ); | ||
| 35 | }; | ||
| 36 | |||
| 37 | |||
| 38 | sub geocode { | ||
| 39 | my $self = shift; | ||
| 40 | my $args = ref( $_[0] ) ? $_[0] : { @_ }; | ||
| 41 | |||
| 42 | my $location = $args->{location}; | ||
| 43 | |||
| 44 | $location = Encode::encode_utf8($location); | ||
| 45 | |||
| 46 | my $url_string = 'http://'. $self->{host} .'/'. $self->{apikey} .'/geocoding/v2/find.js'; | ||
| 47 | |||
| 48 | my $uri = URI->new( $url_string ); | ||
| 49 | $uri->query_form( query => $location ); | ||
| 50 | |||
| 51 | my $res = $self->{ua}->get( $uri ); | ||
| 52 | |||
| 53 | if ($res->is_error) { | ||
| 54 | die "Cloudmade API returned error: " . $res->status_line; | ||
| 55 | } | ||
| 56 | |||
| 57 | local $JSON::Syck::ImplicitUnicode = 1; | ||
| 58 | my $data = JSON::Syck::Load( $res->content ); | ||
| 59 | |||
| 60 | my $results = []; | ||
| 61 | |||
| 62 | foreach my $point ( @{$data->{features}} ) { | ||
| 63 | my $tmp = { | ||
| 64 | lat => $point->{centroid}->{coordinates}->[0], | ||
| 65 | long => $point->{centroid}->{coordinates}->[1], | ||
| 66 | }; | ||
| 67 | push @{$results}, $tmp; | ||
| 68 | }; | ||
| 69 | |||
| 70 | wantarray ? @{$results} : $results->[0]; | ||
| 71 | } | ||
| 72 | |||
| 73 | 1; | ||
| 74 | |||
| 75 | __END__ | ||