Geo::Coder::Cloudmade - Geocode addresses with the Cloudmade API


Geo-Coder-Cloudmade documentation Contained in the Geo-Coder-Cloudmade distribution.

Index


Code Index:

NAME

Top

Geo::Coder::Cloudmade - Geocode addresses with the Cloudmade API

VERSION

Top

Version 0.2

SYNOPSIS

Top

Provides a thin Perl interface to the Cloudmade Geocoding API.

    use Geo::Coder::Cloudmade;

    my $geocoder = Geo::Coder::Cloudmade->new( apikey => 'my_app' );
    my $location = $geocoder->geocode( { location => '1370 Willow Road, 2nd Floor, Menlo Park, CA 94025 USA' } );

OFFICIAL API DOCUMENTATION

Top

Read more about the API at http://developers.cloudmade.com/.

METHOD

Top

new

Constructs a new Geo::Coder::Cloudmade object and returns it. Requires a Cloudmade api key as an argument.

  KEY                   VALUE
  -----------           --------------------
  apikey                Cloudmade API key




geocode

Takes a location in a hashref as an argument and returns the list of matching coordinates for the specified location.

AUTHOR

Top

Alistair Francis, http://search.cpan.org/~friffin/

COPYRIGHT AND LICENSE

Top


Geo-Coder-Cloudmade documentation Contained in the Geo-Coder-Cloudmade distribution.

package Geo::Coder::Cloudmade;

our $VERSION = '0.2';

use strict;

use Carp;
use Encode;
use JSON::Syck;
use HTTP::Request;
use LWP::UserAgent;
use URI;

sub new {
    my $class = shift;
    my $args = shift;

    my $ua = $args->{ua} || LWP::UserAgent->new( agent => __PACKAGE__ . "/$VERSION" );
    my $host = $args->{host} || 'geocoding.cloudmade.com';

    my $self = {
        apikey  => $args->{apikey},
        ua      => $ua,
        host    => $host,
    };
    bless $self, $class;

    return( $self );
};


sub geocode {
    my $self = shift;
    my $args = shift;

    my $location = $args->{location};

    if( Encode::is_utf8($location) ) {
        $location = Encode::encode_utf8($location);
    };

    my $url_string = 'http://'. $self->{host} .'/'. $self->{apikey} .'/geocoding/v2/find.js';

    my $uri = URI->new( $url_string );
    $uri->query_form( query => $location );

    my $res = $self->{ua}->get( $uri );

    if ($res->is_error) {
        die "Cloudmade API returned error: " . $res->status_line;
    }

    local $JSON::Syck::ImplicitUnicode = 1;
    my $data = JSON::Syck::Load( $res->content );

    my $results = [];

    foreach my $point ( @{$data->{features}} ) {
        my $tmp = {
            lat     => $point->{centroid}->{coordinates}->[0],
            long    => $point->{centroid}->{coordinates}->[0],
        };
        push @{$results}, $tmp;
    };

    wantarray ? @{$results} : $results->[0];
}

1;

__END__