blib/lib/Geo/Coder/US/Census.pm

filter: Statementstmt 53.3% 48 / 90 Branchbran 20.5% 7 / 34 Conditioncond 20.0% 1 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 80.0% 12 / 15 Podpod 100% 5 / 5 totaltotal 48.0% 73 / 152 CC 19 SCAR 40.9
CC
19
Cov
43%
geocode
136.4
ua
6.0
run
6.0
CRAP 59.5
↑ Summary
1 package Geo::Coder::US::Census;
2  
3 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use LWP::Protocol::https;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 6 ▶use Geo::StreetAddress::US;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 =head1 NAME
16  
17 Geo::Coder::US::Census - Provides a Geo-Coding functionality for the US using L<https://geocoding.geo.census.gov>
18  
19 =head1 VERSION
20  
21 Version 0.07
22  
23 =cut
24  
25 6 our $VERSION = '0.07';
26  
27 =head1 SYNOPSIS
28  
29 use Geo::Coder::US::Census;
30  
31 my $geo_coder = Geo::Coder::US::Census->new();
32 # Get geocoding results (as a hash decoded from JSON)
33 my $location = $geo_coder->geocode(location => '4600 Silver Hill Rd., Suitland, MD');
34 # Sometimes the server gives a 500 error on this
35 $location = $geo_coder->geocode(location => '4600 Silver Hill Rd., Suitland, MD, USA');
36  
37 =head1 DESCRIPTION
38  
39 Geo::Coder::US::Census provides geocoding functionality specifically for U.S. addresses by interfacing with the U.S. Census Bureau's geocoding service.
40 It allows developers to convert street addresses into geographical coordinates (latitude and longitude) by querying the Census Bureau's API.
41 Using L<LWP::UserAgent> (or a user-supplied agent), the module constructs and sends an HTTP GET request to the API.
42  
43 The module uses L<Geo::StreetAddress::US> to break down a given address into its components (street, city, state, etc.),
44 ensuring that the necessary details for geocoding are present.
45  
46 =head1 METHODS
47  
48 =head2 new
49  
50 $geo_coder = Geo::Coder::US::Census->new();
51 my $ua = LWP::UserAgent->new();
52 $ua->env_proxy(1);
53 $geo_coder = Geo::Coder::US::Census->new(ua => $ua);
54  
55 =cut
56  
57 2 ▶sub new {
Subroutine new: called CC=4 SCAR=14.4
Pod documented
58 2 my $class = $_[0];
59  
60 2 shift;
61 0 ▶ my %args = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 2 2
62  
63 2 my $ua = $args{ua};
64 2 ▶ if(!defined($ua)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ua) 2 0 2
65 2 $ua = LWP::UserAgent->new(agent => __PACKAGE__ . "/$VERSION");
66 2 $ua->default_header(accept_encoding => 'gzip,deflate');
67 2 $ua->env_proxy(1);
68 }
69 2 ▶ my $host = $args{host} || 'geocoding.geo.census.gov/geocoder/locations/address';
Condition50%1/2
$args{'host'} || 'geocoding.geo.census.gov/geocoder/locations/address'
l!l
02
MC/DC0%0/1
$args{'host'} || 'geocoding.geo.census.gov/geocoder/locations/address'
$args{'host'}
Truth table50%1/2
A
A= $args{'host'}
Aresult
11
00
70  
71 2 return bless { ua => $ua, host => $host, %args }, $class;
72 }
73  
74 =head2 geocode
75  
76 Geocode an address.
77 It accepts addresses provided in various forms -
78 whether as a single argument, a key/value pair, or within a hash reference -
79 making it easy to integrate into different codebases.
80 It decodes the JSON response from the API using L<JSON::MaybeXS>,
81 providing the result as a hash.
82 This allows easy extraction of latitude, longitude, and other details returned by the service.
83  
84 $location = $geo_coder->geocode(location => $location);
85 # @location = $geo_coder->geocode(location => $location);
86  
87 print 'Latitude: ', $location->{'latt'}, "\n";
88 print 'Longitude: ', $location->{'longt'}, "\n";
89  
90 =cut
91  
92 1 ▶sub geocode {
Subroutine geocode: called CC=14 SCAR=49.2
Pod documented
93 1 my $self = shift;
94 1 my %param;
95  
96 1 ▶ if(ref($_[0]) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH') { } 0 1 1
elsif (ref $_[0]) { } 0 1 1
elsif (@_ % 2 == 0) { } 1 0 1
97 0 %param = %{$_[0]};
98 } elsif(ref($_[0])) {
99 0 Carp::croak('Usage: geocode(location => $location)');
100 } elsif(@_ % 2 == 0) {
101 1 %param = @_;
102 } else {
103 0 $param{location} = shift;
104 }
105  
106 my $location = $param{location}
107 1 ▶ or Carp::croak('Usage: geocode(location => $location)');
Branch: 1 branch
BranchTrueFalseTotal
my $location = $param{"location"} or Carp::croak("Usage: geocode(location => \$location)") 0 1 1
108  
109 0 ▶ if (Encode::is_utf8($location)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Encode::is_utf8($location)) 0 0 0
110 0 $location = Encode::encode_utf8($location);
111 }
112  
113 0 ▶ if($location =~ /,?(.+),\s*(United States|US|USA)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($location =~ /,?(.+),\s*(United States|US|USA)$/i) 0 0 0
114 0 $location = $1;
115 }
116  
117 # Remove county from the string, if that's included
118 # Assumes not more than one town in a state with the same name
119 # in different counties - but the census Geo-Coding doesn't support that
120 # anyway
121 # Some full state names include spaces, e.g South Carolina
122 # Some roads include full stops, e.g. S. West Street
123 0 ▶ if($location =~ /^(\d+\s+[\w\s\.]+),\s*([\w\s]+),\s*[\w\s]+,\s*([A-Za-z\s]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($location =~ /^(\d+\s+[\w\s\.]+),\s*([\w\s]+),\s*[\w\s]+,\s*([A-Za-z\s]+)$/) 0 0 0
124 0 $location = "$1, $2, $3";
125 }
126  
127 0 my $uri = URI->new("https://$self->{host}");
128 0 my $hr = Geo::StreetAddress::US->parse_address($location);
129  
130 0 ▶ if((!defined($hr->{'city'})) || (!defined($hr->{'state'}))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $hr->{"city"} and defined $hr->{"state"}) 0 0 0
Condition0%0/3
defined $hr->{"city"} and defined $hr->{"state"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $hr->{"city"} and defined $hr->{"state"}
defined $hr->{"city"} defined $hr->{"state"}
Truth table0%0/3
A and B
A= defined $hr->{"city"}B= defined $hr->{"state"}
ABresult
0X0
100
111
131 # use Data::Dumper;
132 # print Data::Dumper->new([$hr])->Dump(), "\n";
133 0 Carp::carp(__PACKAGE__ . ": city and state are mandatory ($location)");
134 0 return;
135 }
136  
137 my %query_parameters = (
138 'benchmark' => 'Public_AR_Current',
139 'city' => $hr->{'city'},
140 'format' => 'json',
141 0 'state' => $hr->{'state'},
142 );
143 0 ▶ if($hr->{'street'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hr->{"street"}) 0 0 0
144 0 ▶ if($hr->{'number'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hr->{'number'}) { } 0 0 0
145 0 $query_parameters{'street'} = $hr->{'number'} . ' ' . $hr->{'street'} . ' ' . $hr->{'type'};
146 } else {
147 0 $query_parameters{'street'} = $hr->{'street'} . ' ' . $hr->{'type'};
148 }
149 0 ▶ if($hr->{'suffix'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hr->{"suffix"}) 0 0 0
150 0 $query_parameters{'street'} .= ' ' . $hr->{'suffix'};
151 }
152 }
153  
154 0 $uri->query_form(%query_parameters);
155 0 my $url = $uri->as_string();
156  
157 0 my $res = $self->{ua}->get($url);
158  
159 0 ▶ if($res->is_error()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 0 0 0
160 0 Carp::carp("$url API returned error: " . $res->status_line());
161 0 return;
162 }
163  
164 0 my $json = JSON::MaybeXS->new->utf8();
165 0 return $json->decode($res->decoded_content());
166  
167 # my @results = @{ $data || [] };
168 # wantarray ? @results : $results[0];
169 }
170  
171 =head2 ua
172  
173 Accessor method to get and set UserAgent object used internally. You
174 can call I<env_proxy> for example, to get the proxy information from
175 environment variables:
176  
177 $geo_coder->ua()->env_proxy(1);
178  
179 You can also set your own User-Agent object:
180  
181 $geo_coder->ua(LWP::UserAgent::Throttled->new());
182  
183 =cut
184  
185 0 ▶sub ua {
Subroutine ua: not called CC=2 SCAR=17.9
Pod documented
186 0 my $self = shift;
187 0 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
188 0 $self->{ua} = shift;
189 }
190 0 $self->{ua};
191 }
192  
193 =head2 reverse_geocode
194  
195 # $location = $geo_coder->reverse_geocode(latlng => '37.778907,-122.39732');
196  
197 # Similar to geocode except it expects a latitude/longitude parameter.
198  
199 Not supported.
200 Croaks if this method is called.
201  
202 =cut
203  
204 0 ▶sub reverse_geocode {
Subroutine reverse_geocode: not called CC=1 SCAR=6.9
Pod documented
205 # my $self = shift;
206  
207 # my %param;
208 # if (@_ % 2 == 0) {
209 # %param = @_;
210 # } else {
211 # $param{latlng} = shift;
212 # }
213  
214 # my $latlng = $param{latlng}
215 # or Carp::croak("Usage: reverse_geocode(latlng => \$latlng)");
216  
217 # return $self->geocode(location => $latlng, reverse => 1);
218 0 Carp::croak(__PACKAGE__, ': Reverse geocode is not supported');
219 }
220  
221 =head2 run
222  
223 In addition to being used as a library within other Perl scripts,
224 L<Geo::Coder::US::Census> can be run directly from the command line.
225 When invoked this way,
226 it accepts an address as input,
227 performs geocoding,
228 and prints the resulting data structure via L<Data::Dumper>.
229  
230 perl Census.pm 1600 Pennsylvania Avenue NW, Washington DC
231  
232 =cut
233  
234 6 ▶__PACKAGE__->run(@ARGV) unless caller();
Branch: 1 branch
BranchTrueFalseTotal
unless &CORE::GLOBAL::caller() 0 6 6
235  
236 0 ▶sub run {
Subroutine run: not called CC=2 SCAR=17.9
Pod documented
237 0 require Data::Dumper;
238  
239 0 my $class = shift;
240  
241 0 my $location = join(' ', @_);
242  
243 0 my @rc = $class->new()->geocode($location);
244  
245 0 ▶ die "$0: geocoding failed" unless(scalar(@rc));
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @rc 0 0 0
246  
247 0 print Data::Dumper->new([\@rc])->Dump();
248 }
249  
250 =head1 AUTHOR
251  
252 Nigel Horne <njh@bandsman.co.uk>
253  
254 Based on L<Geo::Coder::GooglePlaces>.
255  
256 This library is free software; you can redistribute it and/or modify
257 it under the same terms as Perl itself.
258  
259 Lots of thanks to the folks at geocoding.geo.census.gov.
260  
261 =head1 BUGS
262  
263 =head1 SEE ALSO
264  
265 L<Geo::Coder::GooglePlaces>, L<HTML::GoogleMaps::V3>
266  
267 https://www.census.gov/data/developers/data-sets/Geocoding-services.html
268  
269 =head1 LICENSE AND COPYRIGHT
270  
271 Copyright 2017-2025 Nigel Horne.
272  
273 This program is released under the following licence: GPL2
274  
275 =cut
276  
277 6 1;
↑ Summary