blib/lib/Geo/Coder/GeoApify.pm

filter: Statementstmt 81.8% 104 / 127 Branchbran 64.8% 35 / 54 Conditioncond 52.0% 13 / 25 MC/DCmcdc 25.0% 4 / 16 Subroutinesub 94.7% 18 / 19 Podpod 100% 4 / 4 totaltotal 72.6% 178 / 245 CC 37 SCAR 22.9
CC
37
Cov
74%
reverse_geocode
20.0
_could_be_a_location
19.1
new
12.0
CRAP 9.9
↑ Summary
1 package Geo::Coder::GeoApify;
2  
3 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 # One definition of what counts as a location: Geo::Location::Predicate holds
10 # the rule the facade and its backends apply, so what is refused here is refused
11 # there for the same reason. It is called by name rather than imported - an
12 # import copies the code reference into this package, and then a test could not
13 # swap the rule for a spy to prove that it is the rule being consulted.
14 #
15 # The rule is an optional dependency, not a prerequisite: it is a distribution of
16 # its own (Geo-Location-Predicate), declared in Makefile.PL under META_MERGE's
17 # recommends, so an installer fetches it by default and a standalone install that
18 # leaves it out still gets the one answer this module can give alone - a
19 # reference is refused. It is looked for when it is first needed rather than
20 # when this module is loaded, so importing this module reads no file it may not
21 # need, and a rule installed after this module is loaded is still found.
22 5 my $HAVE_RULE; # undef until the rule is first looked for
23 5 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 5 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 5 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 5 ▶use LWP::Protocol::https;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 5 ▶use Params::Get 0.04;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 5 ▶use Params::Validate::Strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 5 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 5 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 =head1 NAME
33  
34 Geo::Coder::GeoApify - Provides a Geo-Coding functionality using L<https://www.geoapify.com/maps-api/>
35  
36 =head1 VERSION
37  
38 Version 0.03
39  
40 =cut
41  
42 5 our $VERSION = '0.03';
43  
44 =head1 SYNOPSIS
45  
46 use Geo::Coder::GeoApify;
47  
48 my $geo_coder = Geo::Coder::GeoApify->new(apiKey => $ENV{'GEOAPIFY_KEY'});
49 my $location = $geo_coder->geocode(location => '10 Downing St., London, UK');
50  
51 =head1 DESCRIPTION
52  
53 Geo::Coder::GeoApify provides an interface to L<https://www.geoapify.com/maps-api/>,
54 a free Geo-Coding database covering many countries.
55  
56 =over 4
57  
58 =item * Caching
59  
60 Identical geocode requests are cached (using L<CHI> or a user-supplied caching object),
61 reducing the number of HTTP requests to the API and speeding up repeated queries.
62  
63 This module leverages L<CHI> for caching geocoding responses.
64 When a geocode request is made,
65 a cache key is constructed from the request.
66 If a cached response exists,
67 it is returned immediately,
68 avoiding unnecessary API calls.
69  
70 =item * Rate-Limiting
71  
72 A minimum interval between successive API calls can be enforced to ensure that the API is not overwhelmed and to comply with any request throttling requirements.
73  
74 Rate-limiting is implemented using L<Time::HiRes>.
75 A minimum interval between API
76 calls can be specified via the C<min_interval> parameter in the constructor.
77 Before making an API call,
78 the module checks how much time has elapsed since the
79 last request and,
80 if necessary,
81 sleeps for the remaining time.
82  
83 =back
84  
85 =head1 METHODS
86  
87 =head2 new
88  
89 $geo_coder = Geo::Coder::GeoApify->new(apiKey => $ENV{'GEOAPIFY_KEY'});
90  
91 Creates a new C<Geo::Coder::GeoApify> object with the provided apiKey.
92  
93 It takes several optional parameters:
94  
95 =over 4
96  
97 =item * C<cache>
98  
99 A caching object.
100 If not provided,
101 an in-memory cache is created with a default expiration of one hour.
102  
103 =item * C<host>
104  
105 The API host endpoint.
106 Defaults to L<https://api.geoapify.com/v1/geocode>.
107  
108 =item * C<min_interval>
109  
110 Minimum number of seconds to wait between API requests.
111 Defaults to C<0> (no delay).
112 Use this option to enforce rate-limiting.
113  
114 =item * C<ua>
115  
116 An object to use for HTTP requests.
117 If not provided, a default user agent is created.
118  
119 =back
120  
121 =cut
122  
123 sub new
124 22 ▶{
Subroutine new: called CC=12 SCAR=24.9
Pod documented
125 22 my $class = shift;
126  
127 # Handle hash or hashref arguments
128 22 ▶ my %args = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 6 16 22
129  
130 # Ensure the correct instantiation method is used
131 22 ▶ unless (defined $class) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $class) 1 21 22
132 1 carp(__PACKAGE__, ' Use ->new() not ::new() to instantiate');
133 1 return;
134 }
135  
136 # If $class is an object, clone it with new arguments
137 21 ▶ return bless { %{$class}, %args }, ref($class) if ref($class);
Branch: 1 branch
BranchTrueFalseTotal
if ref $class 1 20 21
138  
139 # Validate that the apiKey is provided and is a scalar
140 20 my $apiKey = $args{'apiKey'};
141 20 ▶ unless (defined $apiKey && !ref($apiKey)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $apiKey and not ref $apiKey) 2 18 20
Condition100%3/3
defined $apiKey and not ref $apiKey
!ll&&!rl&&r
1118
MC/DC100%2/2
defined $apiKey and not ref $apiKey
defined $apiKey not ref $apiKey
Truth table100%3/3
A and not(B)
A= defined $apiKeyB= not ref $apiKey
ABresult
0X0
100
111
142 2 ▶ carp(__PACKAGE__, defined $apiKey ? ' apiKey must be a scalar' : ' apiKey not given');
Branch: 1 branch
BranchTrueFalseTotal
defined $apiKey ? : 1 1 2
143 2 return;
144 }
145  
146 # Set up user agent (ua) if not provided
147 18 ▶ my $ua = $args{'ua'} || LWP::UserAgent->new(agent => __PACKAGE__ . "/$VERSION");
Condition66%2/3
$args{'ua'} || 'LWP::UserAgent'->new('agent', 'Geo::Coder::GeoApify' . "/$Geo::Coder::GeoApify::VERSION")
l!l&&r!l&&!r
1620
MC/DC0%0/2
$args{'ua'} || 'LWP::UserAgent'->new('agent', 'Geo::Coder::GeoApify' . "/$Geo::Coder::GeoApify::VERSION")
$args{'ua'} 'LWP::UserAgent'->new('agent', 'Geo::Coder::GeoApify' . "/$Geo::Coder::GeoApify::VERSION")
Truth table66%2/3
A || B
A= $args{'ua'}B= 'LWP::UserAgent'->new('agent', 'Geo::Coder::GeoApify' . "/$Geo::Coder::GeoApify::VERSION")
ABresult
1X1
011
000
148 18 $ua->default_header(accept_encoding => 'gzip,deflate');
149 18 $ua->env_proxy(1);
150  
151 # Disable SSL verification if the host is not defined (not recommended in production)
152 18 ▶ $ua->ssl_opts(verify_hostname => 0) unless defined $args{'host'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"host"} 5 13 18
153  
154 # Set host, defaulting to 'api.geoapify.com/v1/geocode'
155 18 ▶ my $host = $args{'host'} // 'api.geoapify.com/v1/geocode';
Condition100%2/2
$args{"host"} // "api.geoapify.com/v1/geocode"
l!l
135
MC/DC100%1/1
$args{"host"} // "api.geoapify.com/v1/geocode"
$args{"host"}
Truth table100%2/2
A
A= $args{"host"}
Aresult
11
00
156  
157 # Set up caching (default to an in-memory cache if none provided)
158 18 ▶ my $cache = $args{cache} || CHI->new(
Condition66%2/3
$args{'cache'} || 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 day')
l!l&&r!l&&!r
1170
MC/DC0%0/2
$args{'cache'} || 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 day')
$args{'cache'} 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 day')
Truth table66%2/3
A || B
A= $args{'cache'}B= 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 day')
ABresult
1X1
011
000
159 driver => 'Memory',
160 global => 1,
161 expires_in => '1 day',
162 );
163  
164 # Set up rate-limiting: minimum interval between requests (in seconds)
165 18 ▶ my $min_interval = $args{min_interval} || 0; # default: no delay
Condition100%2/2
$args{'min_interval'} || 0
l!l
117
MC/DC100%1/1
$args{'min_interval'} || 0
$args{'min_interval'}
Truth table100%2/2
A
A= $args{'min_interval'}
Aresult
11
00
166  
167 # Return the blessed object
168 18 return bless {
169 apiKey => $apiKey,
170 cache => $cache,
171 host => $host,
172 min_interval => $min_interval,
173 last_request => 0, # Initialize last_request timestamp
174 ua => $ua,
175 %args
176 }, $class;
177 }
178  
179 =head2 geocode
180  
181 $location = $geo_coder->geocode(location => $location);
182  
183 print 'Latitude: ', $location->{'features'}[0]{'geometry'}{'coordinates'}[1], "\n";
184 print 'Longitude: ', $location->{'features'}[0]{'geometry'}{'coordinates'}[0], "\n";
185  
186 @locations = $geo_coder->geocode('Portland, USA');
187 print 'There are Portlands in ', join (', ', map { $_->{'state'} } @locations), "\n";
188  
189 =cut
190  
191 # The rule when it is installed, and the one thing that can be said without it.
192 # A reference is not a location however it would print: when the rule is there it
193 # says so, and when it is not this refuses it - the hole this module used to have
194 # was testing the string a reference turns into. Whether a string of digits is a
195 # place is the rule's question, so without the rule it is not asked: the string
196 # is looked up, as it was before the rule existed.
197 16 ▶sub _could_be_a_location {
Subroutine _could_be_a_location: called CC=9 SCAR=29.5
198 16 my $location = shift;
199  
200 16 ▶ if(!defined($HAVE_RULE)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $HAVE_RULE) 3 13 16
201 3 ▶ $HAVE_RULE = eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Geo::Location::Predicate; 'Geo::Location::Predicate'->can('_valid_location') ? 1 : 0 } } ? : 3 0 3
202 3 require Geo::Location::Predicate;
203 3 ▶ Geo::Location::Predicate->can('_valid_location') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'Geo::Location::Predicate'->can('_valid_location') ? : 3 0 3
204 } ? 1 : 0;
205 }
206  
207 # When the rule is installed it decides everything, references included, so
208 # that this module cannot be stricter or looser than the facade. Without it
209 # there are two answers this module can give on its own.
210 16 ▶ return Geo::Location::Predicate::_valid_location($location) ? 1 : 0 if $HAVE_RULE;
Branch: 2 branches
BranchTrueFalseTotal
if $HAVE_RULE 16 0 16
Geo::Location::Predicate::_valid_location($location) ? : 9 7 16
211  
212 0 ▶ return 0 if ref($location);
Branch: 1 branch
BranchTrueFalseTotal
if ref $location 0 0 0
213 0 ▶ return 0 unless defined($location) && length($location);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $location and length $location 0 0 0
Condition0%0/3
defined $location and length $location
!ll&&!rl&&r
000
MC/DC0%0/2
defined $location and length $location
defined $location length $location
Truth table0%0/3
A and B
A= defined $locationB= length $location
ABresult
0X0
100
111
214 0 return 1;
215 }
216  
217 sub geocode
218 16 ▶{
Subroutine geocode: called CC=9 SCAR=22.2
Pod documented
219 16 my $self = shift;
220 16 my $params = Params::Get::get_params('location', @_);
221  
222 16 my $location = $params->{location};
223  
224 # A scalar reference is one way of passing the string it points at, and
225 # Params::Get dereferences it when it is the only argument. Do it here as
226 # well, in every calling form, so that it means the string however the
227 # method is called.
228 16 ▶ $location = ${$location} if ref($location) eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
if ref $location eq "SCALAR" 1 15 16
229  
230 # What counts as a location is Geo::Location::Predicate's answer, not a
231 # second copy of it here: undef and the empty string are nothing to look up, a
232 # reference is not a location however it would print, and a string of digits is
233 # what a numeric column holds when the wrong one has been read.
234 16 ▶ if(!_could_be_a_location($location)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_could_be_a_location($location)) 7 9 16
235 7 ▶ Carp::croak('Usage: geocode(location => $location)')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $location and length $location 0 7 7
Condition33%1/3
defined $location and length $location
!ll&&!rl&&r
007
MC/DC0%0/2
defined $location and length $location
defined $location length $location
Truth table33%1/3
A and B
A= defined $locationB= length $location
ABresult
0X0
100
111
236 unless(defined($location) && length($location));
237 7 ▶ Carp::croak('Usage: ', __PACKAGE__, ': invalid input to geocode(), ',
Branch: 1 branch
BranchTrueFalseTotal
ref $location ? : 6 1 7
238 ref($location) ? 'a reference is not a location' : $location);
239 }
240  
241 # Encode location if it's in UTF-8
242 9 ▶ $location = Encode::encode_utf8($location) if Encode::is_utf8($location);
Branch: 1 branch
BranchTrueFalseTotal
if &Encode::is_utf8($location) 0 9 9
243  
244 # Create URI for the API request
245 9 my $uri = URI->new("https://$self->{host}/search");
246  
247 # Handle potential confusion between England and New England
248 9 $location =~ s/(.+),\s*England$/$1, United Kingdom/i;
249  
250 # Replace spaces with plus signs for URL encoding
251 9 $location =~ s/\s/+/g;
252  
253 # Set query parameters
254 9 $uri->query_form('text' => $location, 'apiKey' => $self->{'apiKey'});
255 9 my $url = $uri->as_string();
256  
257 # Create a cache key based on the location (might want to use a stronger hash function if needed)
258 9 my $cache_key = "apify:$location";
259 9 ▶ if(my $cached = $self->{cache}->get($cache_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"cache"}->get($cache_key)) 2 7 9
260 2 return $cached;
261 }
262  
263 7 ▶ if(my $rc = $self->_get_result($url)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $self->_get_result($url)) 3 0 3
264 # Cache the result before returning it
265 3 return $self->{'cache'}->set($cache_key, $rc);
266 }
267 }
268  
269 =head2 ua
270  
271 Accessor method to get and set UserAgent object used internally. You
272 can call I<env_proxy> for example, to get the proxy information from
273 environment variables:
274  
275 $geo_coder->ua()->env_proxy(1);
276  
277 You can also set your own User-Agent object:
278  
279 use LWP::UserAgent::Throttled;
280  
281 my $ua = LWP::UserAgent::Throttled->new();
282 $ua->throttle({ 'api.geoapify.com' => 5 });
283 $ua->env_proxy(1);
284 $geo_coder = Geo::Coder::GeoApify->new({ ua => $ua, apiKey => $ENV{'GEOAPIFY_KEY'} });
285  
286 =cut
287  
288 sub ua
289 1 ▶{
Subroutine ua: called CC=2 SCAR=7.1
Pod documented
290 1 my $self = shift;
291  
292 # Update 'ua' if an argument is provided
293 1 ▶ $self->{ua} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 1 1
294  
295 # Return the 'ua' value
296 1 return $self->{ua};
297 }
298  
299 =head2 reverse_geocode
300  
301 my $address = $geo_coder->reverse_geocode(lat => 37.778907, lon => -122.39732);
302 print 'City: ', $address->{features}[0]->{'properties'}{'city'}, "\n";
303  
304 Similar to geocode except it expects a latitude,longitude pair.
305  
306 =cut
307  
308 sub reverse_geocode
309 0 ▶{
Subroutine reverse_geocode: not called CC=4 SCAR=30.0
Pod documented
310 0 my $self = shift;
311  
312 0 my $params = Params::Validate::Strict::validate_strict({
313 args => Params::Get::get_params(undef, @_),
314 schema => {
315 'lat' => {
316 type => 'number',
317 min => -90,
318 max => 90
319 }, 'lon' => {
320 type => 'number',
321 min => -180,
322 max => 180
323 }
324 }
325 });
326  
327 0 my $lat = $params->{'lat'};
328 0 my $lon = $params->{'lon'};
329  
330 # Build URI for the API request
331 0 my $uri = URI->new("https://$self->{host}/reverse");
332 $uri->query_form(
333 'lat' => $lat,
334 'lon' => $lon,
335 0 'apiKey' => $self->{'apiKey'}
336 );
337 0 my $url = $uri->as_string();
338  
339 # Create a cache key based on the location (might want to use a stronger hash function if needed)
340 0 my $cache_key = "apify:reverse:$lat:$lon";
341 0 ▶ if(my $cached = $self->{cache}->get($cache_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"cache"}->get($cache_key)) 0 0 0
342 0 return $cached;
343 }
344  
345 # Enforce rate-limiting: ensure at least min_interval seconds between requests.
346 0 my $now = time();
347 0 my $elapsed = $now - $self->{last_request};
348 0 ▶ if($elapsed < $self->{min_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 0 0 0
349 0 Time::HiRes::sleep($self->{min_interval} - $elapsed);
350 }
351  
352 0 ▶ if(my $rc = $self->_get_result($url)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $self->_get_result($url)) 0 0 0
353 # Cache the result before returning it
354 0 return $self->{'cache'}->set($cache_key, $rc);
355 }
356 }
357  
358 # Connect to the API and get results
359 sub _get_result
360 7 ▶{
Subroutine _get_result: called CC=6 SCAR=20.5
361 7 my ($self, $url) = @_;
362  
363 # Enforce rate-limiting: ensure at least min_interval seconds between requests.
364 7 my $now = time();
365 7 my $elapsed = $now - $self->{last_request};
366 7 ▶ if($elapsed < $self->{min_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 1 6 7
367 1 Time::HiRes::sleep($self->{min_interval} - $elapsed);
368 }
369  
370 # Send the request and handle response
371 7 my $res = $self->{ua}->get($url);
372  
373 # Update last_request timestamp
374 3 $self->{'last_request'} = time();
375  
376 # Handle API errors
377 3 ▶ if($res->is_error()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 0 3 3
378 0 Carp::carp("API returned error on $url: ", $res->status_line());
379 0 return {};
380 }
381  
382 # Decode the JSON response
383 3 my $json = JSON::MaybeXS->new->utf8();
384 3 my $rc;
385 3 eval {
386 3 $rc = $json->decode($res->decoded_content());
387 };
388  
389 # Handle JSON decoding errors
390 3 ▶ if($@ || !defined $rc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not defined $rc) 0 3 3
Condition33%1/3
$@ or not defined $rc
l!l&&r!l&&!r
003
MC/DC0%0/2
$@ or not defined $rc
$@ not defined $rc
Truth table33%1/3
A or not(B)
A= $@B= not defined $rc
ABresult
1X1
011
000
391 0 ▶ Carp::carp("$url: Failed to decode JSON - ", $@ || $res->content());
Condition0%0/3
$@ || $res->content
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $res->content
$@ $res->content
Truth table0%0/3
A || B
A= $@B= $res->content
ABresult
1X1
011
000
392 0 return;
393 }
394  
395 3 return $rc;
396 }
397  
398 =head1 AUTHOR
399  
400 Nigel Horne, C<< <njh at nigelhorne.com> >>
401  
402 This library is free software; you can redistribute it and/or modify
403 it under the same terms as Perl itself.
404  
405 Lots of thanks to the folks at geoapify.com
406  
407 =head1 SEE ALSO
408  
409 L<Geo::Coder::GooglePlaces>, L<HTML::GoogleMaps::V3>
410  
411 =head1 LICENSE AND COPYRIGHT
412  
413 Copyright 2024-2026 Nigel Horne.
414  
415 This program is released under the following licence: GPL2
416  
417 =cut
418  
419 5 1;
↑ Summary