summaryrefslogtreecommitdiff
path: root/Geocoding.pm
blob: a7e5ba124a2ab9020285143b776dc96edd4b043f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package Geo::USCensus::Geocoding;

use strict;
use warnings;

use LWP::UserAgent;
use JSON;
use URI;
use Geo::USCensus::Geocoding::Match;

=head1 NAME

Geo::USCensus::Geocoding - The U.S. Census Bureau geocoding service

=head1 VERSION

Version 0.01

=cut

our $VERSION = '0.01';
our $DEBUG = 0;

=head1 SYNOPSIS

    use Geo::USCensus::Geocoding;

    my $request = {
      # required fields
      street  => '123 Main Street',
      city    => 'San Francisco',   # city
      state   => 'CA',              # state/province
      zip     => '93102',           # zip/postal code
      # optional fields
      benchmark => 'Public_AR_ACS2013', # default is "Public_AR_Current"
      vintage   => 'Census2010_ACS2013', # default is "Current_Current"

      debug => 1,                   # will print the URL and some other info
    };
    my $result = Geo::USCensus::Geocoding->query($request);

    if ($result->matches) {
      my $match = $result->match(0);
      print $match->matchedAddress,"\n",
            $match->coordinates->{x},',',$match->coordinates->{y},"\n",
            $match->censustract,"\n";
    }

=head1 CLASS METHODS

=head2 query HASHREF

Send a request to the web service.  See
L<http://geocoding.geo.census.gov/geocoder> for API documentation. This 
package will always use the JSON data format and the Geographies return type.

Returns an object of class Geo::USCensus::Geocoding.

=cut

my $ua = LWP::UserAgent->new;
my $api_uri = 'http://geocoding.geo.census.gov/geocoder/geographies/address';

sub query {
  my $class = shift;
  my %opt = (
    benchmark => 'Public_AR_Census2010',
    vintage   => 'Census2010_Census2010',
  );
  if (ref $_[0] eq 'HASH') {
    %opt = (%opt, %{ $_[0] });
  } else {
    %opt = (%opt, @_);
  }

  $DEBUG = $opt{debug} || 0;
  $opt{format} = 'json';

  foreach (qw(street city state zip)) {
    die "$_ required\n" unless length($opt{$_});
  }

  my $uri = URI->new($api_uri);
  $uri->query_form(\%opt);
  warn "$class->query\n$uri\n\n" if $DEBUG;
  my $http_req = HTTP::Request->new(GET => $uri->as_string);
  my $resp = $ua->request($http_req);
  my $self = { addr_response => $resp };
  bless $self, $class;
  if ( $resp->is_success ) {
    local $@;
    my $tree = eval { from_json($resp->content) };
    if ($@) {
      $self->message("Unable to parse response:\n$@");
      return $self;
    }
    if (!exists $tree->{result}) {
      $self->message("Response does not contain geocoding results.");
      warn $self->message. "\n".$resp->content."\n\n";
      return $self;
    }
    $tree = $tree->{result};

    my @matches;
    if (exists( $tree->{addressMatches} )) {
      foreach my $am (@{ $tree->{addressMatches} }) {
        push @matches, Geo::USCensus::Geocoding::Match->new($am);
      }
    } # else what? does this happen if there's no match? a proper REST 
      # interface should throw a 404
    $self->{matches} = \@matches;
  } else {
    $self->message( $resp->status_line );
  }
  $self;
}

=head1 METHODS

=head2 message

Sets/gets an explicit error status.

=cut

sub message {
  my $self = shift;
  if (@_) {
    $self->{_message} = shift;
  }
  $self->{_message} || '';
}

=head2 matches

Returns the number of matches found. 

=cut

sub matches {
  my $self = shift;
  $self->{matches} ? scalar @{ $self->{matches} } : 0;
}

=head2 match NUMBER

Returns a specific match (starting from zero). Matches are returned 
as L<Geo::USCensus::Geocoding::Match> objects, in the order they were 
returned by the service.

=cut

sub match {
  my $self = shift;
  my $i = shift;
  $self->{matches}->[$i];
}

=head1 AUTHOR

Mark Wells, C<< <mark at freeside.biz> >>

=head1 SUPPORT

Commercial support for this module is available from Freeside Internet 
Services:

    L<http://www.freeside.biz/>

=back


=head1 LICENSE AND COPYRIGHT

Copyright (C) 2014 Mark Wells.

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.

=cut

1;