blib/lib/Geo/Coder/GeoApify.pm

filter: Statementstmt 71.5% 88 / 123 Branchbran 52.3% 22 / 42 Conditioncond 42.8% 12 / 28 MC/DCmcdc 22.2% 4 / 18 Subroutinesub 93.7% 15 / 16 Podpod 100% 4 / 4 totaltotal 62.7% 145 / 231 CC 32 SCAR 36.1
CC
32
Cov
63%
reverse_geocode
132.0
geocode
12.8
new
12.0
CRAP 37.0
↑ Summary
1 package Geo::Coder::GeoApify;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 4 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 ▶use LWP::Protocol::https;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use Params::Get;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 4 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 =head1 NAME
18  
19 Geo::Coder::GeoApify - Provides a Geo-Coding functionality using L<https://www.geoapify.com/maps-api/>
20  
21 =head1 VERSION
22  
23 Version 0.02
24  
25 =cut
26  
27 4 our $VERSION = '0.02';
28  
29 =head1 SYNOPSIS
30  
31 use Geo::Coder::GeoApify;
32  
33 my $geo_coder = Geo::Coder::GeoApify->new(apiKey => $ENV{'GEOAPIFY_KEY'});
34 my $location = $geo_coder->geocode(location => '10 Downing St., London, UK');
35  
36 =head1 DESCRIPTION
37  
38 Geo::Coder::GeoApify provides an interface to https://www.geoapify.com/maps-api/,
39 a free Geo-Coding database covering many countries.
40  
41 =over 4
42  
43 =item * Caching
44  
45 Identical geocode requests are cached (using L<CHI> or a user-supplied caching object),
46 reducing the number of HTTP requests to the API and speeding up repeated queries.
47  
48 This module leverages L<CHI> for caching geocoding responses.
49 When a geocode request is made,
50 a cache key is constructed from the request.
51 If a cached response exists,
52 it is returned immediately,
53 avoiding unnecessary API calls.
54  
55 =item * Rate-Limiting
56  
57 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.
58  
59 Rate-limiting is implemented using L<Time::HiRes>.
60 A minimum interval between API
61 calls can be specified via the C<min_interval> parameter in the constructor.
62 Before making an API call,
63 the module checks how much time has elapsed since the
64 last request and,
65 if necessary,
66 sleeps for the remaining time.
67  
68 =back
69  
70 =head1 METHODS
71  
72 =head2 new
73  
74 $geo_coder = Geo::Coder::GeoApify->new(apiKey => $ENV{'GEOAPIFY_KEY'});
75  
76 Creates a new C<Geo::Coder::GeoApify> object with the provided apiKey.
77  
78 It takes several optional parameters:
79  
80 =over 4
81  
82 =item * C<cache>
83  
84 A caching object.
85 If not provided,
86 an in-memory cache is created with a default expiration of one hour.
87  
88 =item * C<host>
89  
90 The API host endpoint.
91 Defaults to L<https://api.geoapify.com/v1/geocode>.
92  
93 =item * C<min_interval>
94  
95 Minimum number of seconds to wait between API requests.
96 Defaults to C<0> (no delay).
97 Use this option to enforce rate-limiting.
98  
99 =item * C<ua>
100  
101 An object to use for HTTP requests.
102 If not provided, a default user agent is created.
103  
104 =back
105  
106 =cut
107  
108 sub new
109 10 ▶{
Subroutine new: called CC=12 SCAR=24.9
Pod documented
110 10 my $class = shift;
111  
112 # Handle hash or hashref arguments
113 10 ▶ my %args = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 6 4 10
114  
115 # Ensure the correct instantiation method is used
116 10 ▶ unless (defined $class) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $class) 1 9 10
117 1 carp(__PACKAGE__, ' Use ->new() not ::new() to instantiate');
118 1 return;
119 }
120  
121 # If $class is an object, clone it with new arguments
122 9 ▶ return bless { %{$class}, %args }, ref($class) if ref($class);
Branch: 1 branch
BranchTrueFalseTotal
if ref $class 1 8 9
123  
124 # Validate that the apiKey is provided and is a scalar
125 8 my $apiKey = $args{'apiKey'};
126 8 ▶ unless (defined $apiKey && !ref($apiKey)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $apiKey and not ref $apiKey) 2 6 8
Condition100%3/3
defined $apiKey and not ref $apiKey
!ll&&!rl&&r
116
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
127 2 ▶ carp(__PACKAGE__, defined $apiKey ? ' apiKey must be a scalar' : ' apiKey not given');
Branch: 1 branch
BranchTrueFalseTotal
defined $apiKey ? : 1 1 2
128 2 return;
129 }
130  
131 # Set up user agent (ua) if not provided
132 6 ▶ 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
420
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
133 6 $ua->default_header(accept_encoding => 'gzip,deflate');
134 6 $ua->env_proxy(1);
135  
136 # Disable SSL verification if the host is not defined (not recommended in production)
137 6 ▶ $ua->ssl_opts(verify_hostname => 0) unless defined $args{'host'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"host"} 5 1 6
138  
139 # Set host, defaulting to 'api.geoapify.com/v1/geocode'
140 6 ▶ my $host = $args{'host'} // 'api.geoapify.com/v1/geocode';
Condition100%2/2
$args{"host"} // "api.geoapify.com/v1/geocode"
l!l
15
MC/DC100%1/1
$args{"host"} // "api.geoapify.com/v1/geocode"
$args{"host"}
Truth table100%2/2
A
A= $args{"host"}
Aresult
11
00
141  
142 # Set up caching (default to an in-memory cache if none provided)
143 6 ▶ 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
150
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
144 driver => 'Memory',
145 global => 1,
146 expires_in => '1 day',
147 );
148  
149 # Set up rate-limiting: minimum interval between requests (in seconds)
150 6 ▶ my $min_interval = $args{min_interval} || 0; # default: no delay
Condition100%2/2
$args{'min_interval'} || 0
l!l
15
MC/DC100%1/1
$args{'min_interval'} || 0
$args{'min_interval'}
Truth table100%2/2
A
A= $args{'min_interval'}
Aresult
11
00
151  
152 # Return the blessed object
153 6 return bless {
154 apiKey => $apiKey,
155 cache => $cache,
156 host => $host,
157 min_interval => $min_interval,
158 last_request => 0, # Initialize last_request timestamp
159 ua => $ua,
160 %args
161 }, $class;
162 }
163  
164 =head2 geocode
165  
166 $location = $geo_coder->geocode(location => $location);
167  
168 print 'Latitude: ', $location->{'features'}[0]{'geometry'}{'coordinates'}[1], "\n";
169 print 'Longitude: ', $location->{'features'}[0]{'geometry'}{'coordinates'}[0], "\n";
170  
171 @locations = $geo_coder->geocode('Portland, USA');
172 print 'There are Portlands in ', join (', ', map { $_->{'state'} } @locations), "\n";
173  
174 =cut
175  
176 sub geocode
177 5 ▶{
Subroutine geocode: called CC=10 SCAR=25.5
Pod documented
178 5 my $self = shift;
179 5 my $params = Params::Get::get_params('location', @_);
180  
181 # Ensure location is provided
182 my $location = $params->{location}
183 5 ▶ or Carp::croak('Usage: geocode(location => $location)');
Branch: 1 branch
BranchTrueFalseTotal
my $location = $params->{"location"} or Carp::croak("Usage: geocode(location => \$location)") 5 0 5
184  
185 # Fail when the input is just a set of numbers
186 5 ▶ if($location !~ /\D/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($location =~ /\D/) 0 5 5
187 0 Carp::croak('Usage: ', __PACKAGE__, ": invalid input to geocode(), $location");
188 0 return;
189 }
190  
191 # Encode location if it's in UTF-8
192 5 ▶ $location = Encode::encode_utf8($location) if Encode::is_utf8($location);
Branch: 1 branch
BranchTrueFalseTotal
if &Encode::is_utf8($location) 0 5 5
193  
194 # Create URI for the API request
195 5 my $uri = URI->new("https://$self->{host}/search");
196  
197 # Handle potential confusion between England and New England
198 5 $location =~ s/(.+),\s*England$/$1, United Kingdom/i;
199  
200 # Replace spaces with plus signs for URL encoding
201 5 $location =~ s/\s/+/g;
202  
203 # Set query parameters
204 5 $uri->query_form('text' => $location, 'apiKey' => $self->{'apiKey'});
205 5 my $url = $uri->as_string();
206  
207 # Create a cache key based on the location (might want to use a stronger hash function if needed)
208 5 my $cache_key = "apify:$location";
209 5 ▶ if(my $cached = $self->{cache}->get($cache_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"cache"}->get($cache_key)) 2 3 5
210 2 return $cached;
211 }
212  
213 # Enforce rate-limiting: ensure at least min_interval seconds between requests.
214 3 my $now = time();
215 3 my $elapsed = $now - $self->{last_request};
216 3 ▶ if($elapsed < $self->{min_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 1 2 3
217 1 Time::HiRes::sleep($self->{min_interval} - $elapsed);
218 }
219  
220 # Send the request and handle response
221 3 my $res = $self->{ua}->get($url);
222  
223 # Update last_request timestamp
224 3 $self->{'last_request'} = time();
225  
226 3 ▶ if($res->is_error()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 0 3 3
227 0 Carp::carp("API returned error on $url: ", $res->status_line());
228 0 return {};
229 }
230  
231 # Decode the JSON response
232 3 my $json = JSON::MaybeXS->new->utf8();
233 3 my $rc;
234 3 eval {
235 3 $rc = $json->decode($res->decoded_content());
236 };
237 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
238 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
239 0 return {};
240 }
241  
242 # Cache the result before returning it
243 3 $self->{'cache'}->set($cache_key, $rc);
244  
245 3 return $rc;
246 }
247  
248 =head2 ua
249  
250 Accessor method to get and set UserAgent object used internally. You
251 can call I<env_proxy> for example, to get the proxy information from
252 environment variables:
253  
254 $geo_coder->ua()->env_proxy(1);
255  
256 You can also set your own User-Agent object:
257  
258 use LWP::UserAgent::Throttled;
259  
260 my $ua = LWP::UserAgent::Throttled->new();
261 $ua->throttle({ 'api.geoapify.com' => 5 });
262 $ua->env_proxy(1);
263 $geo_coder = Geo::Coder::GeoApify->new({ ua => $ua, apiKey => $ENV{'GEOAPIFY_KEY'} });
264  
265 =cut
266  
267 sub ua
268 1 ▶{
Subroutine ua: called CC=2 SCAR=7.1
Pod documented
269 1 my $self = shift;
270  
271 # Update 'ua' if an argument is provided
272 1 ▶ $self->{ua} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 1 1
273  
274 # Return the 'ua' value
275 1 return $self->{ua};
276 }
277  
278 =head2 reverse_geocode
279  
280 my $address = $geo_coder->reverse_geocode(lat => 37.778907, lon => -122.39732);
281 print 'City: ', $address->{features}[0]->{'properties'}{'city'}, "\n";
282  
283 Similar to geocode except it expects a latitude,longitude pair.
284  
285 =cut
286  
287 sub reverse_geocode
288 0 ▶{
Subroutine reverse_geocode: not called CC=11 SCAR=48.8
Pod documented
289 0 my $self = shift;
290 0 my $params = Params::Get::get_params(undef, @_);
291  
292 # Validate latitude and longitude
293 0 ▶ my $lat = $params->{lat} or Carp::carp('Missing latitude (lat)');
Branch: 1 branch
BranchTrueFalseTotal
my $lat = $params->{"lat"} or Carp::carp("Missing latitude (lat)") 0 0 0
294 0 ▶ my $lon = $params->{lon} or Carp::carp('Missing longitude (lon)');
Branch: 1 branch
BranchTrueFalseTotal
my $lon = $params->{"lon"} or Carp::carp("Missing longitude (lon)") 0 0 0
295  
296 0 ▶ return {} unless $lat && $lon; # Return early if lat or lon is missing
Branch: 1 branch
BranchTrueFalseTotal
unless $lat and $lon 0 0 0
Condition0%0/3
$lat and $lon
!ll&&!rl&&r
000
MC/DC0%0/2
$lat and $lon
$lat $lon
Truth table0%0/3
A and B
A= $latB= $lon
ABresult
0X0
100
111
297  
298 # Build URI for the API request
299 0 my $uri = URI->new("https://$self->{host}/reverse");
300 $uri->query_form(
301 'lat' => $lat,
302 'lon' => $lon,
303 0 'apiKey' => $self->{'apiKey'}
304 );
305 0 my $url = $uri->as_string();
306  
307 # Create a cache key based on the location (might want to use a stronger hash function if needed)
308 0 my $cache_key = "apify:reverse:$lat:$lon";
309 0 ▶ if(my $cached = $self->{cache}->get($cache_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"cache"}->get($cache_key)) 0 0 0
310 0 return $cached;
311 }
312  
313 # Enforce rate-limiting: ensure at least min_interval seconds between requests.
314 0 my $now = time();
315 0 my $elapsed = $now - $self->{last_request};
316 0 ▶ if($elapsed < $self->{min_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 0 0 0
317 0 Time::HiRes::sleep($self->{min_interval} - $elapsed);
318 }
319  
320 # Send request to the API
321 0 my $res = $self->{ua}->get($url);
322  
323 # Update last_request timestamp
324 0 $self->{'last_request'} = time();
325  
326 # Handle API errors
327 0 ▶ if($res->is_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 0 0 0
328 0 Carp::carp("API returned error on $url: ", $res->status_line());
329 0 return {};
330 }
331  
332 # Decode the JSON response
333 0 my $json = JSON::MaybeXS->new->utf8();
334 0 my $rc;
335 0 eval {
336 0 $rc = $json->decode($res->decoded_content());
337 };
338  
339 # Handle JSON decoding errors
340 0 ▶ if($@ || !defined $rc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not defined $rc) 0 0 0
Condition0%0/3
$@ or not defined $rc
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not defined $rc
$@ not defined $rc
Truth table0%0/3
A or not(B)
A= $@B= not defined $rc
ABresult
1X1
011
000
341 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
342 0 return {};
343 }
344  
345 # Cache the result before returning it
346 0 $self->{'cache'}->set($cache_key, $rc);
347  
348 0 return $rc;
349 }
350  
351 =head1 AUTHOR
352  
353 Nigel Horne, C<< <njh at bandsman.co.uk> >>
354  
355 This library is free software; you can redistribute it and/or modify
356 it under the same terms as Perl itself.
357  
358 Lots of thanks to the folks at geoapify.com
359  
360 =head1 SEE ALSO
361  
362 L<Geo::Coder::GooglePlaces>, L<HTML::GoogleMaps::V3>
363  
364 =head1 LICENSE AND COPYRIGHT
365  
366 Copyright 2024-2025 Nigel Horne.
367  
368 This program is released under the following licence: GPL2
369  
370 =cut
371  
372 4 1;
↑ Summary