Address-PostCode-UK

 view release on metacpan or  search on metacpan

lib/Address/PostCode/UK.pm  view on Meta::CPAN

package Address::PostCode::UK;

$Address::PostCode::UK::VERSION   = '0.18';
$Address::PostCode::UK::AUTHORITY = 'cpan:MANWAR';

=head1 NAME

Address::PostCode::UK - Interface to the UK PostCode.

=head1 VERSION

Version 0.18

=cut

use 5.006;
use JSON;
use Data::Dumper;
use Address::PostCode::UserAgent;
use Address::PostCode::UK::Location;
use Address::PostCode::UK::Place;
use Address::PostCode::UK::Place::Geo;
use Address::PostCode::UK::Place::Ward;
use Address::PostCode::UK::Place::Council;
use Address::PostCode::UK::Place::Constituency;

use Moo;
use namespace::autoclean;
extends 'Address::PostCode::UserAgent';

our $BASE_URL = 'http://uk-postcodes.com';

=head1 DESCRIPTION

Interface to the API provided by L<UK Postcodes|http://uk-postcodes.com/>.

=head1 NOTE

Data  may  be  used  under the terms of the OS OpenData licence. Northern Ireland
postcode  data may be used under the terms of the ONSPD licence. Currently, there
are no limitations on usage, but they may introduce rate limiting in future.

=head1 METHODS

=head2 details()

It returns an object of type L<Address::PostCode::UK::Place> on success. The only
parameter requires is the post code.

    use strict; use warnings;
    use Address::PostCode::UK;

    my $address   = Address::PostCode::UK->new;
    my $post_code = 'Post Code';
    my $place     = $address->details($post_code);

    print "Latitude : ", $place->geo->lat, "\n";
    print "Longitude: ", $place->geo->lng, "\n";

=cut

sub details {
    my ($self, $post_code) = @_;

    die "ERROR: Missing required param 'post code'.\n" unless defined $post_code;
    die "ERROR: Invalid format for UK post code [$post_code].\n" unless ($post_code =~ /[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}/gi);

    $post_code =~ s/\s//g;
    my $url      = sprintf("%s/postcode/%s.json", $BASE_URL, $post_code);
    my $response = $self->get($url);
    my $contents = from_json($response->{'content'});

    my ($geo, $ward, $council, $constituency);
    $geo  = Address::PostCode::UK::Place::Geo->new($contents->{'geo'})
        if (exists $contents->{'geo'});
    $ward = Address::PostCode::UK::Place::Ward->new($contents->{'administrative'}->{'ward'})
        if (exists $contents->{'administrative'}->{'ward'});
    $council = Address::PostCode::UK::Place::Council->new($contents->{'administrative'}->{'council'})

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 1.075 second using v1.00-cache-2.02-grep-82fe00e-cpan-2c419f77a38b )