blib/lib/Geo/Coder/List.pm

filter: Statementstmt 98.4% 504 / 512 Branchbran 93.8% 289 / 308 Conditioncond 72.3% 97 / 134 MC/DCmcdc 44.0% 37 / 84 Subroutinesub 100% 28 / 28 Podpod 100% 7 / 7 totaltotal 89.6% 962 / 1073 CC 211 SCAR 38.7
CC
211
Cov
93%
geocode
93.6
reverse_geocode
36.2
_cache
30.1
CRAP 47.8
↑ Summary
1 package Geo::Coder::List;
2  
3 # Geo::Coder::List - Aggregate and chain multiple geocoding backends
4  
5 25 ▶use 5.10.1;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 25 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 25 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 25 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 25 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 # One definition of what counts as a location: Geo::Location::Predicate holds
13 # the rule the facade and its backends apply, so what is refused here is refused
14 # there for the same reason. It is called by name rather than imported - an
15 # import copies the code reference into this package, and then a test could not
16 # swap the rule for a spy to prove that it is the rule being consulted.
17 #
18 # The rule is an optional dependency, not a prerequisite: it is a distribution of
19 # its own (Geo-Location-Predicate), declared in Makefile.PL under META_MERGE's
20 # recommends, so an installer fetches it by default and a standalone install that
21 # leaves it out still gets the one answer this module can give alone - a
22 # reference is refused. It is looked for when it is first needed rather than
23 # when this module is loaded, so importing this module reads no file it may not
24 # need, and a rule installed after this module is loaded is still found.
25 25 my $HAVE_RULE; # undef until the rule is first looked for
26 25 ▶use HTML::Entities;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 25 ▶use Object::Configure 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 25 ▶use Params::Get 0.04;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 25 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 25 ▶use Scalar::Util qw(blessed reftype);
Subroutine BEGIN: called CC=1 SCAR=0.0
31 25 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 =head1 NAME
34  
35 Geo::Coder::List - Call many Geo-Coders
36  
37 =head1 VERSION
38  
39 Version 0.40
40  
41 =cut
42  
43 25 our $VERSION = '0.40';
44  
45 # ── Module-level constants (not user-configurable) ────────────────────────────
46  
47 # Default verbosity: 0 = silent, 1 = basic trace, 2 = full Data::Dumper dumps
48 25 ▶use constant DEBUG_DEFAULT => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
49  
50 # Internal sentinel class: a cached not-found result stored in L1.
51 # Using a blessed ref lets _cache() distinguish "never looked up" from
52 # "looked up and found nothing" without requiring a special undef convention.
53 25 ▶use constant _NOT_FOUND_CLASS => __PACKAGE__ . '::_NotFound';
Subroutine BEGIN: called CC=1 SCAR=0.0
54  
55 # The singleton value stored in L1 when a location is confirmed missing
56 25 my $NOT_FOUND_SENTINEL = bless {}, _NOT_FOUND_CLASS;
57  
58 # String placed in the 'geocoder' field of a result served from cache
59 25 Readonly::Scalar my $CACHE_SOURCE => 'cache';
60  
61 # A latlng argument to reverse_geocode(): two decimal numbers and a comma.
62 # The classes are spelt out rather than written \d and \s: those match
63 # Arabic-Indic and other Unicode digits, which no backend reads as numbers,
64 # and the /a flag that would restrict them needs Perl 5.14.
65 25 Readonly::Scalar my $LATLNG_RE => qr/^[ \t]*[-+]?(?:[0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)[ \t]*,[ \t]*[-+]?(?:[0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)[ \t]*$/;
66  
67 # String used as the 'result' value in log entries for a geocoder miss
68 25 Readonly::Scalar my $RESULT_NONE => 'not found';
69  
70 # ── Configurable defaults ─────────────────────────────────────────────────────
71 #
72 # Any key here can be overridden at run time via an environment variable named
73 # GEO__CODER__LIST__<key>, which Object::Configure reads automatically in new().
74 # Example:
75 # export GEO__CODER__LIST__cache_hit_duration='7 days'
76  
77 25 my %config = (
78 debug => DEBUG_DEFAULT,
79 # How long a confirmed location stays in the L2 cache
80 cache_hit_duration => '1 month',
81 # How long a transient/partial failure is cached (retry tomorrow)
82 cache_part_duration => '1 day',
83 # How long a definite not-found is cached (place probably does not exist)
84 cache_miss_duration => '1 week',
85 );
86  
87 # =============================================================================
88 # PUBLIC API
89 # =============================================================================
90  
91 =head1 SYNOPSIS
92  
93 use Geo::Coder::List;
94 use Geo::Coder::OSM;
95  
96 # 1. The simplest use: one list, one geocoder
97 my $list = Geo::Coder::List->new()->push(Geo::Coder::OSM->new());
98  
99 my $place = $list->geocode('10 Downing St, London, UK');
100 if($place) {
101 print "Latitude: $place->{geometry}{location}{lat}\n";
102 print "Longitude: $place->{geometry}{location}{lng}\n";
103 } else {
104 print "Not found\n";
105 }
106  
107 # 2. Several geocoders, tried in order. Geo::Coder::CA is asked only
108 # about places in Canada or the USA, and at most 1000 times.
109 use Geo::Coder::CA;
110  
111 my $chain = Geo::Coder::List->new()
112 ->push({ regex => qr/(Canada|USA)$/, geocoder => Geo::Coder::CA->new(), limit => 1000 })
113 ->push(Geo::Coder::OSM->new());
114  
115 my $ottawa = $chain->geocode('Ottawa, ON, Canada'); # asks CA first
116 my $paris = $chain->geocode('Paris, France'); # CA is skipped
117  
118 # 3. A cache that lives longer than the object (any CHI driver works)
119 use CHI;
120  
121 my $cached = Geo::Coder::List->new(
122 cache => CHI->new(driver => 'File', root_dir => '/var/cache/geocode'),
123 )->push(Geo::Coder::OSM->new());
124  
125 # 4. Every candidate, not only the best one: call geocode() in list context
126 my @candidates = $list->geocode('Springfield, USA');
127 print scalar(@candidates), " places are called Springfield\n";
128  
129 # 5. From a position to an address
130 my $address = $list->reverse_geocode(latlng => '51.5034,-0.1276');
131 print "$address\n" if defined($address);
132  
133 # 6. Bad input is fatal, so check it when the text comes from a user
134 my $text_from_a_form = $ARGV[0];
135 my $result = eval { $list->geocode($text_from_a_form) };
136 warn "Not a place: $@" if $@;
137  
138 # 7. See what happened, then clear the record
139 $list->geocode('Rome, Italy');
140 for my $entry (@{ $list->log() }) {
141 printf "%s: %s in %.3fs\n", $entry->{location}, $entry->{geocoder}, $entry->{timetaken};
142 }
143 $list->flush();
144  
145 =head1 DESCRIPTION
146  
147 L<Geo::Coder::All> and L<Geo::Coder::Many> are great modules but neither
148 quite does what I want.
149  
150 A I<geocoder> turns the name of a place, such as C<'Paris, France'>, into
151 a position on the Earth (a latitude and a longitude). There are many
152 geocoding services. Each one knows some places better than others, each
153 one has its own limits, and each one returns its answer in its own format.
154  
155 C<Geo::Coder::List> lets you use many geocoders as if they were one:
156  
157 =over 4
158  
159 =item * B<A chain.>
160 You add geocoders with C<push()>. When you ask for a place, the geocoders
161 are asked one at a time, in the order you added them. The first one that
162 gives a usable answer wins, and the others are not asked.
163  
164 =item * B<Routing.>
165 A geocoder can be given a regular expression. It is then asked only
166 about places whose names match it.
167  
168 =item * B<Limits.>
169 A geocoder can be given a limit: the number of questions it may answer.
170 When the limit is used up, the geocoder is skipped.
171  
172 =item * B<One answer format.>
173 Every answer is changed into the same structure, whichever service gave
174 it. The structure is the one used by L<HTML::GoogleMaps::V3> and
175 L<HTML::OSM>:
176  
177 $result->{geometry}{location}{lat} # latitude
178 $result->{geometry}{location}{lng} # longitude
179 $result->{lat} # the same latitude, for convenience
180 $result->{lng} # the same longitude, for convenience
181 $result->{lon} # the same longitude, another common name
182 $result->{geocoder} # the geocoder object that answered,
183 # or the string 'cache'
184  
185 =item * B<A cache in two levels.>
186 Level 1 (L1) is a hash inside the object. It is always used, and it lasts
187 as long as the object. Level 2 (L2) is optional. It can be a plain hash
188 or any object with C<get()> and C<set()> methods, such as a L<CHI> cache.
189 L2 can last longer than the object and can be shared between programs.
190 How long L2 keeps an answer depends on the answer:
191  
192 found 1 month (cache_hit_duration)
193 found, but no latitude 1 day (cache_part_duration)
194 not found 1 week (cache_miss_duration)
195  
196 A place that was not found is remembered in L1 only, never in L2.
197  
198 =back
199  
200 =head1 SUPPORTED ANSWER FORMATS
201  
202 Each geocoding service answers in its own format. C<geocode()> finds the
203 latitude and longitude in each of the formats below and copies them into
204 the common structure. Any geocoder whose answers use one of these formats
205 works without extra code. The provider's own fields are kept as well.
206  
207 Service (module) Where the position is found
208 ------------------------------ -----------------------------------------
209 OpenStreetMap, RandMcNally lat, lon
210 Bing Maps BestLocation.Coordinates.Latitude/Longitude
211 Bing Maps (other form) point.coordinates [lat, lng]
212 geocoder.ca (Geo::Coder::CA) latt, longt
213 postcodes.io, Geo::Coder::Free latitude, longitude
214 HERE / Ovi properties.geoLatitude/geoLongitude
215 DataScienceToolkit results[0].geometry.location.lat/lng
216 OpenCage results[0].geometry.lat/lng
217 GeocodeFarm RESULTS[0].COORDINATES.latitude/longitude
218 US Census Bureau result.addressMatches[0].coordinates.y/x
219 GeoNames lat, lng
220 Mapbox features[0].center [lng, lat]
221 GeoApify features[0].geometry.coordinates [lng, lat]
222 Google, and anything already geometry.location.lat/lng
223 in the common structure
224  
225 Notice that Mapbox and GeoApify give the longitude B<first>.
226  
227 Some services need special handling, which is done for you:
228  
229 =over 4
230  
231 =item * B<Geo::Location::Point.>
232 A geocoder may answer with a L<Geo::Location::Point> object. Its
233 C<geometry> is filled in from its own C<lat> and C<lng> (or C<lon>).
234  
235 =item * B<postcodes.io.>
236 Its C<local_type> field is copied to C<type>, with the first letter made
237 lower case.
238  
239 =item * B<geocoder.xyz.>
240 Its C<standard.countryname> field is copied to C<address.country>.
241  
242 =item * B<GeoNames.>
243 L<Geo::GeoNames> is called with the place name alone, not with
244 C<location =E<gt> ...>. If it has no C<username>, it fails with
245 C<lost username>, which is logged, and the next geocoder is asked.
246 GeoNames puts its answers in arrays; every answer in them is considered.
247  
248 =item * B<US Census Bureau.>
249 An answer with no C<addressMatches> means "not found", and the next
250 geocoder is asked.
251  
252 =item * B<GeoApify.>
253 An answer with an empty C<features> list means "not found", and the next
254 geocoder is asked.
255  
256 =item * B<Errors.>
257 An answer with a top-level C<error> key is treated as a refusal, not as a
258 place. The error is logged, and the next geocoder is asked.
259  
260 =back
261  
262 Every answer that went through this process also has a C<debug> key. It
263 holds the line number, in this module, of the code that read the answer.
264 It is there to help when a new format is not read correctly.
265  
266 =head1 SUBROUTINES/METHODS
267  
268 =head2 new
269  
270 Creates a new C<Geo::Coder::List> object with no geocoders in it.
271  
272 Settings can also come from the environment, through
273 L<Object::Configure>. The variable name is C<GEO__CODER__LIST__> followed
274 by the setting name. For example, C<GEO__CODER__LIST__carp_on_warn=1>
275 makes warnings go through L<Carp>, and
276 C<GEO__CODER__LIST__cache_hit_duration='7 days'> changes how long a found
277 place stays in L2.
278  
279 When you call C<new()> on an object that already exists, you get a
280 I<clone>: a new object with the same settings and the same geocoders,
281 merged with any arguments you give. The clone has its own list of
282 geocoders and its own limits, and it starts with an empty log. The clone
283 B<shares> the L1 and L2 caches with the original.
284  
285 use Geo::Coder::List;
286 use CHI;
287  
288 # With an L2 cache
289 my $geocoder = Geo::Coder::List->new(
290 cache => CHI->new(driver => 'Memory', global => 1),
291 );
292  
293 # A clone of it that prints what it is doing
294 my $verbose = $geocoder->new(debug => 1);
295  
296 Arguments can be given as a list of pairs or as one hash reference.
297  
298 =over 4
299  
300 =item * C<cache> - Optional. The L2 cache: a hash reference, or an object
301 with C<get($key)> and C<set($key, $value, $ttl)> methods.
302  
303 =item * C<debug> - Optional. C<0> (the default) prints nothing, C<1>
304 prints what is tried, C<2> also prints every answer in full.
305  
306 =item * C<cache_hit_duration>, C<cache_part_duration>,
307 C<cache_miss_duration> - Optional. How long L2 keeps each kind of
308 answer, in any form your L2 cache understands, such as C<'1 week'>.
309  
310 =item * C<geocoders> - Optional. An array reference of geocoders, as if
311 each had been given to C<push()>.
312  
313 =item * C<logger> - Optional. Where warnings and errors go. See
314 L<Object::Configure>.
315  
316 =item * C<carp_on_warn> - Optional. When true, warnings go through
317 L<Carp>.
318  
319 =back
320  
321 If C<new> is called as a function, C<Geo::Coder::List::new()>, with no
322 arguments, it still returns an object. Called as a function with
323 arguments, it warns and returns C<undef>.
324  
325 =head3 API SPECIFICATION
326  
327 =head4 INPUT
328  
329 {
330 cache => { type => 'hashref|object', optional => 1 },
331 debug => { type => 'integer', optional => 1, min => 0, max => 2 },
332 cache_hit_duration => { type => 'string', optional => 1 },
333 cache_part_duration => { type => 'string', optional => 1 },
334 cache_miss_duration => { type => 'string', optional => 1 },
335 geocoders => { type => 'arrayref', optional => 1 },
336 logger => { type => 'object|coderef|arrayref|string', optional => 1 },
337 carp_on_warn => { type => 'boolean', optional => 1 },
338 }
339  
340 =head4 OUTPUT
341  
342 {
343 type => 'object',
344 isa => 'Geo::Coder::List',
345 }
346  
347 # undef only when called as Geo::Coder::List::new() with arguments
348  
349 =cut
350  
351 sub new
352 406 ▶{
Subroutine new: called CC=9 SCAR=22.0
Pod documented
353 406 my $class = shift;
354 406 ▶ my $params = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
146260
MC/DC100%1/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
355  
356 # Handle the rare Geo::Coder::List::new() (function-style) invocation
357 406 ▶ if(!defined($class)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $class) { } 8 398 406
elsif (builtin::blessed($class)) { } 9 389 398
358 8 ▶ if(scalar keys %{$params} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$params;} > 0) 4 4 8
359 # Using ::new() with arguments is not supported
360 4 carp(__PACKAGE__, ' use ->new() not ::new() to instantiate');
361 4 return;
362 }
363 # With no arguments there is nothing to lose, so build a default
364 # object; with arguments the caller has mistaken the calling form and
365 # is told so above, rather than having the arguments silently ignored
366 4 $class = __PACKAGE__;
367 } elsif(blessed($class)) {
368 # Shallow clone merged with new params; log is always fresh so the
369 # clone starts with an empty event history independent of the original
370 # The chain is copied, hashref entries included, so pushing onto the
371 # clone or spending one of its limits leaves the original's alone
372 9 my $clone = bless { %{$class}, %{$params}, log => [] }, ref($class);
373 $clone->{'geocoders'} = [
374 9 ▶ map { ref($_) eq 'HASH' ? { %{$_} } : $_ } @{$clone->{'geocoders'} // []}
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 1 4 5
Condition50%1/2
$clone->{"geocoders"} // []
l!l
90
MC/DC0%0/1
$clone->{"geocoders"} // []
$clone->{"geocoders"}
Truth table50%1/2
A
A= $clone->{"geocoders"}
Aresult
11
00
375 ];
376 9 return $clone;
377 }
378  
379 # Let Object::Configure overlay defaults from environment / config files
380 393 $params = Object::Configure::configure($class, $params);
381  
382 # Fill in any %config defaults the caller did not explicitly supply
383 393 for my $key (keys %config) {
384 1572 ▶ $params->{$key} //= $config{$key};
Condition66%2/3
$params->{$key} //= $config{$key}
l!l&&r!l&&!r
1415580
MC/DC0%0/2
$params->{$key} //= $config{$key}
$params->{$key} $config{$key}
Truth table66%2/3
A //= B
A= $params->{$key}B= $config{$key}
ABresult
1X1
011
000
385 }
386  
387 # Bless and return; params override scalar defaults but locations/log
388 # are always initialised fresh so callers cannot inject stale state
389 return bless {
390 debug => DEBUG_DEFAULT,
391 geocoders => [],
392 393 %{$params},
393 locations => {},
394 log => [],
395 }, $class;
396 }
397  
398 # =============================================================================
399  
400 =head2 push
401  
402 Adds one geocoder to the end of the chain. Geocoders are asked in the
403 order in which they were added.
404  
405 C<push> returns the object itself, so you can add several geocoders in
406 one statement.
407  
408 There are two ways to add a geocoder:
409  
410 =over 4
411  
412 =item * B<A geocoder object.>
413 It is asked about every place.
414  
415 =item * B<A hash reference>, with these keys:
416  
417 =over 4
418  
419 =item * C<geocoder> - Required. The geocoder object.
420  
421 =item * C<regex> - Optional. A regular expression, made with C<qr//>.
422 The geocoder is asked only about places whose names match it.
423  
424 =item * C<limit> - Optional. A whole number. The geocoder answers at
425 most this many questions. Each question it is asked makes the number one
426 smaller. When the number reaches C<0>, the geocoder is skipped. A place
427 that does not match C<regex> does not use up the limit.
428  
429 =back
430  
431 =back
432  
433 my $list = Geo::Coder::List->new()
434 ->push({ regex => qr/USA$/, geocoder => Geo::Coder::US::Census->new(), limit => 100 })
435 ->push(Geo::Coder::OSM->new());
436  
437 C<push> croaks if C<$geocoder> is missing or C<undef>.
438  
439 =head3 API SPECIFICATION
440  
441 =head4 INPUT
442  
443 {
444 geocoder => { type => 'object|hashref', optional => 0 },
445 }
446  
447 # A hashref geocoder holds the keys geocoder (an object, required),
448 # regex (a Regexp, optional) and limit (an integer, optional)
449  
450 =head4 OUTPUT
451  
452 {
453 type => 'object',
454 isa => 'Geo::Coder::List',
455 }
456  
457 =cut
458  
459 sub push
460 308 ▶{
Subroutine push: called CC=2 SCAR=6.9
Pod documented
461 # Deliberately NOT using Params::Get here: passing the hashref through it
462 # would stringify the compiled qr// object, destroying the regex.
463 308 my ($self, $geocoder) = @_;
464  
465 # A geocoder argument is mandatory
466 308 ▶ croak(__PACKAGE__, '::push: Usage: ($geocoder)') unless defined($geocoder);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $geocoder 5 303 308
467  
468 # Append to the ordered chain and return $self for chaining
469 303 CORE::push @{$self->{geocoders}}, $geocoder;
470  
471 303 return $self;
472 }
473  
474 # The rule when it is installed, and the one thing that can be said without it.
475 # A reference is not a location however it would print: when the rule is there it
476 # says so, and when it is not this refuses it - the hole this module used to have
477 # was testing the string a reference turns into. Whether a string of digits is a
478 # place is the rule's question, so without the rule it is not asked: the string
479 # is looked up, as it was before the rule existed.
480 250 ▶sub _could_be_a_location {
Subroutine _could_be_a_location: called CC=9 SCAR=29.5
481 250 my $location = shift;
482  
483 250 ▶ if(!defined($HAVE_RULE)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $HAVE_RULE) 7 243 250
484 7 ▶ $HAVE_RULE = eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Geo::Location::Predicate; 'Geo::Location::Predicate'->can('_valid_location') ? 1 : 0 } } ? : 7 0 7
485 7 require Geo::Location::Predicate;
486 7 ▶ Geo::Location::Predicate->can('_valid_location') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'Geo::Location::Predicate'->can('_valid_location') ? : 7 0 7
487 } ? 1 : 0;
488 }
489  
490 # When the rule is installed it decides everything, references included, so
491 # that this module cannot be stricter or looser than the facade. Without it
492 # there are two answers this module can give on its own.
493 250 ▶ return Geo::Location::Predicate::_valid_location($location) ? 1 : 0 if $HAVE_RULE;
Branch: 2 branches
BranchTrueFalseTotal
if $HAVE_RULE 250 0 250
Geo::Location::Predicate::_valid_location($location) ? : 223 27 250
494  
495 0 ▶ return 0 if ref($location);
Branch: 1 branch
BranchTrueFalseTotal
if ref $location 0 0 0
496 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
497 0 return 1;
498 }
499  
500 # =============================================================================
501  
502 =head2 geocode
503  
504 Finds the position of a place from its name.
505  
506 my $result = $list->geocode(location => 'Paris, France');
507 my $result = $list->geocode('Paris, France'); # the same
508 my $result = $list->geocode({ location => 'Paris, France' }); # the same
509  
510 if($result) {
511 printf "lat=%.4f lng=%.4f from %s\n",
512 $result->{geometry}{location}{lat},
513 $result->{geometry}{location}{lng},
514 ref($result->{geocoder}) || $result->{geocoder};
515 }
516  
517 These are the steps, in order:
518  
519 =over 4
520  
521 =item 1. If C<location> is missing, C<geocode> croaks. If it is
522 C<undef> or an empty string, C<geocode> warns and returns nothing.
523  
524 =item 2. Runs of white space are made into one space, and HTML entities
525 are decoded: C<'Caf&eacute;'> becomes C<'Caf'> followed by the single
526 character e-acute. A reference to a string is treated as the string.
527  
528 =item 3. The text is checked. A reference is never a place. When
529 L<Geo::Location::Predicate> is installed, it decides what else is not a
530 place; for example, a string of only digits is not. If the text is not a
531 place, C<geocode> croaks. The check is done after step 2, so
532 C<'&#49;&#50;'> is refused as the digits C<'12'>.
533  
534 =item 4. The cache is checked: first L1, then L2. If the place is there,
535 the cached answer is returned, with C<geocoder> set to C<'cache'>. If L1
536 remembers that the place was not found, nothing is returned and no
537 geocoder is asked.
538  
539 =item 5. Each geocoder in the chain is asked in turn. A geocoder is
540 skipped if the place does not match its C<regex>, or if its C<limit> is
541 used up. If a geocoder dies, the error is logged, a warning is given, and
542 the next geocoder is asked.
543  
544 =item 6. The first answer that has both a latitude and a longitude wins.
545 It is changed into the common structure (see L</DESCRIPTION>), stored in
546 the cache, and returned.
547  
548 =item 7. If no geocoder gives a usable answer, the place is remembered as
549 "not found" in L1, and nothing is returned.
550  
551 =back
552  
553 B<Scalar context> returns one hash reference, or C<undef>.
554  
555 B<List context> returns every answer from the geocoder that won, or an
556 empty list. This is useful when a name, such as C<'Springfield'>, belongs
557 to many places. Answers that the geocoder returned inside an array are
558 taken out of it, so the list never contains array references. Answers
559 without a position may be in the list too; check C<geometry> before you
560 use each one.
561  
562 my @all = $list->geocode('Springfield, USA');
563  
564 The C<geocoder> key of an answer holds the geocoder object that gave it.
565 When the answer came from the cache, it holds the string C<'cache'>.
566  
567 =head3 API SPECIFICATION
568  
569 =head4 INPUT
570  
571 {
572 location => { type => 'string', optional => 0, min => 1 },
573 }
574  
575 =head4 OUTPUT
576  
577 {
578 type => 'hashref',
579 optional => 1,
580 }
581  
582 # Return::Set schema, scalar context: a hashref, or undef when not found
583 # {
584 # geometry => { location => { lat => Num, lng => Num } },
585 # lat => Num,
586 # lng => Num,
587 # lon => Num, # the same as lng
588 # geocoder => OBJECT | 'cache',
589 # debug => Int, # line that read the answer
590 # ... # fields from the provider
591 # }
592 #
593 # List context: a list of hashrefs as above, or an empty list
594  
595 =cut
596  
597 247 ▶sub geocode {
Subroutine geocode: called CC=90 SCAR=45.4
Pod documented
598 247 my $self = shift;
599  
600 # The geocoders are called inside eval; the caller's $@ is not ours to change
601 247 local $@;
602  
603 # Params::Get enforces 'location'; calling geocode() with no args causes
604 # get_params itself to croak with "Usage:" matching t/carp.t expectations
605 247 my $params = Params::Get::get_params('location', @_);
606 245 ▶ if(!defined($params)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $params) 0 245 245
607 0 $self->_error(__PACKAGE__, ' usage: geocode(location => $location)');
608 0 return;
609 }
610  
611 245 my $location = $params->{'location'};
612  
613 # A scalar reference is one way of passing the string it points at, and
614 # Params::Get dereferences it when it is the only argument. Do it here as
615 # well, in every calling form, so that it means the string however the
616 # method is called.
617 245 ▶ $location = ${$location} if ref($location) eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
if ref $location eq "SCALAR" 2 243 245
618  
619 # Reject empty or whitespace-only location strings
620 245 ▶ if((!defined($location)) || (length($location) == 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $location or length $location == 0) 6 239 245
Condition100%3/3
not defined $location or length $location == 0
l!l&&r!l&&!r
33239
MC/DC100%2/2
not defined $location or length $location == 0
not defined $location length $location == 0
Truth table100%3/3
not(A) or B
A= not defined $locationB= length $location == 0
ABresult
1X1
011
000
621 6 $self->_warn(__PACKAGE__, ' usage: geocode(location => $location)');
622 6 return;
623 }
624  
625 # Collapse runs of whitespace and expand any HTML entities before the rule
626 # is asked: '&#49;&#50;' is the string of digits '12' once decoded, and it
627 # is the decoded string that is looked up. A reference is left as it is
628 # for the rule to refuse.
629 239 ▶ if(!ref($location)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $location) 228 11 239
630 228 $location =~ s/\s\s+/ /g;
631 228 $location = decode_entities($location);
632 }
633  
634 # What counts as a location is Geo::Location::Predicate's answer, not a
635 # second copy of it here: a reference is not a location however it would print,
636 # and a string of digits is what a numeric column holds when the wrong one has
637 # been read.
638 239 ▶ if(!_could_be_a_location($location)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_could_be_a_location($location)) 18 221 239
639 18 ▶ $self->_error('Usage: ', __PACKAGE__, ': invalid input to geocode(), ',
Branch: 1 branch
BranchTrueFalseTotal
ref $location ? : 10 8 18
640 ref($location) ? 'a reference is not a location' : $location);
641 0 return;
642 }
643  
644 # Propagate the cleaned-up string so geocoders also receive the decoded form
645 221 $params->{'location'} = $location;
646  
647 221 $self->_debug("location: $location\n");
648  
649 # Capture the caller's line number once for all log entries in this call
650 221 my @call_details = caller(0);
651  
652 # ── L1 / L2 cache lookup ──────────────────────────────────────────────
653  
654 # _cache() returns undef for both "not in cache" and "cached not-found";
655 # the not-found sentinel is handled internally so callers see undef either way
656 221 my $cached = $self->_cache($location);
657  
658 # Only a reference is a geocode result. A plain string in the cache under
659 # this key - a reverse_geocode() address, or a corrupted store - is not,
660 # and is looked up again rather than returned as if it were one.
661 221 ▶ if(defined($cached) && !ref($cached)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cached and not ref $cached) 1 220 221
Condition100%3/3
defined $cached and not ref $cached
!ll&&!rl&&r
192281
MC/DC100%2/2
defined $cached and not ref $cached
defined $cached not ref $cached
Truth table100%3/3
A and not(B)
A= defined $cachedB= not ref $cached
ABresult
0X0
100
111
662 1 undef $cached;
663 }
664  
665 221 ▶ if(defined $cached) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cached) 28 193 221
666 # A defined value means we have a genuine cached positive result
667 28 ▶ my @rc = ref($cached) eq 'ARRAY' ? @{$cached} : ($cached);
Branch: 1 branch
BranchTrueFalseTotal
ref $cached eq 'ARRAY' ? : 5 23 28
668  
669 # Mark every element as coming from cache. Shallow-copy HASH results
670 # first so that neither the L1 cache entry nor any caller-held reference
671 # to the same hashref is mutated in place.
672 28 for my $r (@rc) {
673 28 ▶ next unless ref($r);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $r 0 28 28
674 28 ▶ $r = { %{$r} } if ref($r) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $r eq "HASH" 26 2 28
675 28 $r->{'geocoder'} = $CACHE_SOURCE;
676 }
677  
678 # Scalar context: return the first (and usually only) element
679 28 ▶ if(!wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (wantarray) 22 6 28
680 22 my $rc = $rc[0];
681 22 CORE::push @{$self->{'log'}}, {
682 line => $call_details[2],
683 location => $location,
684 timetaken => 0,
685 geocoder => $CACHE_SOURCE,
686 wantarray => 0,
687 result => $rc,
688 };
689 22 $self->_debug(__PACKAGE__, ': ', __LINE__, ": cached\n");
690 22 return $rc;
691 }
692  
693 # List context: return all cached candidates
694 6 CORE::push @{$self->{'log'}}, {
695 line => $call_details[2],
696 location => $location,
697 timetaken => 0,
698 geocoder => $CACHE_SOURCE,
699 wantarray => 1,
700 result => \@rc,
701 };
702 6 $self->_debug(__PACKAGE__, ': ', __LINE__, ": cached\n");
703  
704 # Determine if every element is empty; if so return nothing
705 6 my $allempty = 1;
706 6 for my $r (@rc) {
707 6 ▶ if(ref($r) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $r eq 'HASH') { } 5 1 6
elsif (ref $r eq 'Geo::Location::Point') { } 1 0 1
708 5 ▶ $allempty = 0 if defined $r->{geometry}{location}{lat};
Branch: 1 branch
BranchTrueFalseTotal
if defined $r->{"geometry"}{"location"}{"lat"} 3 2 5
709 } elsif(ref($r) eq 'Geo::Location::Point') {
710 1 $allempty = 0;
711 }
712 }
713 6 ▶ return if $allempty;
Branch: 1 branch
BranchTrueFalseTotal
if $allempty 2 4 6
714 4 return @rc;
715 }
716  
717 # Also check if this location is cached as a definite not-found in L1,
718 # without going through _cache() (which masks the sentinel as undef)
719 193 ▶ if(exists $self->{'locations'}{$location}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"locations"}{$location}) 6 187 193
720 6 my $stored = $self->{'locations'}{$location};
721 6 ▶ if(ref($stored) && ref($stored) eq _NOT_FOUND_CLASS) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $stored and ref $stored eq "Geo::Coder::List::_NotFound") 6 0 6
Condition33%1/3
ref $stored and ref $stored eq "Geo::Coder::List::_NotFound"
!ll&&!rl&&r
006
MC/DC0%0/2
ref $stored and ref $stored eq "Geo::Coder::List::_NotFound"
ref $stored ref $stored eq "Geo::Coder::List::_NotFound"
Truth table33%1/3
A and B
A= ref $storedB= ref $stored eq "Geo::Coder::List::_NotFound"
ABresult
0X0
100
111
722 6 $self->_debug("No matches (cached)\n");
723 6 ▶ return wantarray ? () : undef;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 5 6
724 }
725 }
726  
727 # ── Try each geocoder in turn ─────────────────────────────────────────
728  
729 187 ENCODER: foreach my $g (@{$self->{geocoders}}) {
730 193 my $geocoder = $g;
731  
732 # Unpack a hashref entry and apply regex / limit guards
733 193 ▶ if(ref($geocoder) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq "HASH") 19 174 193
734 # Skip this entry if the location does not match its regex. This
735 # comes before the limit so that a location the geocoder is never
736 # asked about does not spend one of its queries.
737 19 ▶ if(my $regex = $geocoder->{'regex'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $regex = $geocoder->{"regex"}) 6 13 19
738 6 $self->_debug('consider ', ref($geocoder->{geocoder}), ": $regex\n");
739 6 ▶ if($location !~ $regex) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($location =~ /$regex/) 4 2 6
740 4 next;
741 }
742 }
743  
744 # Decrement and check the per-geocoder query limit
745 15 ▶ if(exists($geocoder->{'limit'}) && defined(my $limit = $geocoder->{'limit'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})) 14 1 15
Condition66%2/3
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
!ll&&!rl&&r
1014
MC/DC50%1/2
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
exists $geocoder->{"limit"} defined(my $limit = $geocoder->{"limit"})
Truth table66%2/3
A and B
A= exists $geocoder->{"limit"}B= defined(my $limit = $geocoder->{"limit"})
ABresult
0X0
100
111
746 14 $self->_debug("limit: $limit\n");
747 14 ▶ if($limit <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit <= 0) 8 6 14
748 8 next;
749 }
750 6 $geocoder->{'limit'}--;
751 }
752  
753 # Unwrap the actual geocoder object from the hashref
754 7 $geocoder = $g->{'geocoder'};
755 }
756  
757 # Start timing before the network call
758 181 my @rc;
759 181 my $timetaken = Time::HiRes::time();
760  
761 181 eval {
762 # Geo::GeoNames uses a positional argument, not a hash
763 181 $self->_debug('trying ', ref($geocoder), "\n");
764 181 ▶ if(ref($geocoder) eq 'Geo::GeoNames') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq 'Geo::GeoNames') { } 2 179 181
765 2 $self->_debug('username => ', $geocoder->username(), "\n");
766 2 ▶ die 'lost username' if(!defined($geocoder->username()));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $geocoder->username 1 1 2
767 1 @rc = $geocoder->geocode($location);
768 } else {
769 179 @rc = $geocoder->geocode(%{$params});
770 }
771 };
772  
773 181 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 12 169 181
774 # Log the failure and move on; do not abort the whole chain
775 12 my $log = {
776 line => $call_details[2],
777 location => $location,
778 geocoder => ref($geocoder),
779 timetaken => Time::HiRes::time() - $timetaken,
780 wantarray => wantarray,
781 error => $@,
782 };
783 12 CORE::push @{$self->{'log'}}, $log;
784 12 $self->_warn(ref($geocoder), " '$location': $@");
785 12 next ENCODER;
786 }
787  
788 169 $timetaken = Time::HiRes::time() - $timetaken;
789  
790 # Geo::Coder::US::Census sometimes returns a truthy but empty result
791 169 ▶ if((ref($geocoder) eq 'Geo::Coder::US::Census') &&
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq "Geo::Coder::US::Census" and not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}) 2 167 169
Condition66%2/3
ref $geocoder eq "Geo::Coder::US::Census" and not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
!ll&&!rl&&r
16702
MC/DC50%1/2
ref $geocoder eq "Geo::Coder::US::Census" and not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
ref $geocoder eq "Geo::Coder::US::Census" not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
Truth table66%2/3
A and not(B)
A= ref $geocoder eq "Geo::Coder::US::Census"B= not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
ABresult
0X0
100
111
792 !(defined($rc[0]->{result}{addressMatches}[0]->{coordinates}{y}))) {
793 2 my $log = {
794 line => $call_details[2],
795 location => $location,
796 timetaken => $timetaken,
797 geocoder => ref($geocoder),
798 wantarray => wantarray,
799 result => $RESULT_NONE,
800 };
801 2 CORE::push @{$self->{'log'}}, $log;
802 2 next ENCODER;
803 }
804  
805 # Geo::GeoNames wraps its results in arrays. Every element of such an
806 # array is a candidate, so they are unwrapped into one list here, and a
807 # wrapped empty hash is then caught by the check below like any other
808 167 ▶ @rc = map { ref($_) eq 'ARRAY' ? @{$_} : $_ } @rc;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 5 20148 20153
809  
810 # Reject empty result sets and trivially empty hashes
811 167 ▶ if((scalar(@rc) == 0) ||
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @rc == 0 or ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0) 22 145 167
Condition100%6/6
scalar @rc == 0 or ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0
l!l&&r!l&&!r
202145
ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0
!ll&&!rl&&r
171282
MC/DC100%3/3
scalar @rc == 0 or ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0
scalar @rc == 0 ref $rc[0] eq "HASH" scalar keys %{$rc[0];} == 0
Truth table100%4/4
A or B and C
A= scalar @rc == 0B= ref $rc[0] eq "HASH"C= scalar keys %{$rc[0];} == 0
ABCresult
1XX1
0111
00X0
0100
812 130 ((ref($rc[0]) eq 'HASH') && (scalar(keys %{$rc[0]}) == 0))) {
813 22 my $log = {
814 line => $call_details[2],
815 location => $location,
816 timetaken => $timetaken,
817 geocoder => ref($geocoder),
818 wantarray => wantarray,
819 result => $RESULT_NONE,
820 };
821 22 CORE::push @{$self->{'log'}}, $log;
822 22 next ENCODER;
823 }
824  
825 # ── Normalise each candidate result ──────────────────────────────
826  
827 # Track which element was successfully normalised so we return it,
828 # not blindly return $rc[0] when a later element was the good one
829 145 my $good_result;
830  
831 145 POSSIBLE_LOCATION: foreach my $l (@rc) {
832 # Skip undefined or empty-string candidates
833 152 ▶ if((!defined($l)) || ($l eq '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $l or $l eq "") 5 147 152
Condition100%3/3
not defined $l or $l eq ""
l!l&&r!l&&!r
32147
MC/DC100%2/2
not defined $l or $l eq ""
not defined $l $l eq ""
Truth table100%3/3
not(A) or B
A= not defined $lB= $l eq ""
ABresult
1X1
011
000
834 5 my $log = {
835 line => $call_details[2],
836 location => $location,
837 timetaken => $timetaken,
838 geocoder => ref($geocoder),
839 wantarray => wantarray,
840 result => $RESULT_NONE,
841 };
842 5 CORE::push @{$self->{'log'}}, $log;
843 5 next ENCODER;
844 }
845  
846 # Skip bare scalars (e.g. integer 0, plain strings) that are
847 # not references; they cannot be hash-dereferenced below
848 147 ▶ next unless ref($l);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $l 8 139 147
849  
850 # Stamp the source geocoder on the result before normalisation
851 139 $l->{'geocoder'} = ref($geocoder);
852  
853 $self->_debug(ref($geocoder), ': ',
854 139 ▶ Data::Dumper->new([\$l])->Dump()) if($self->{'debug'} >= 2);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} >= 2 2 137 139
855  
856 # Geo::Location::Point objects carry their own accessors;
857 # upgrade the geocoder field and populate the canonical geometry
858 # structure so callers can rely on geometry.location.{lat,lng}
859 139 ▶ if(ref($l) eq 'Geo::Location::Point') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $l eq "Geo::Location::Point") 4 135 139
860 4 $l->{'geocoder'} = $geocoder;
861  
862 # Populate canonical geometry structure from the GLP's own fields
863 4 ▶ if(!defined($l->{geometry}{location}{lat}) && defined($l->{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"lat"}) 3 1 4
Condition66%2/3
not defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"lat"}
!ll&&!rl&&r
103
MC/DC50%1/2
not defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"lat"}
not defined $l->{"geometry"}{"location"}{"lat"} defined $l->{"lat"}
Truth table66%2/3
not(A) and B
A= not defined $l->{"geometry"}{"location"}{"lat"}B= defined $l->{"lat"}
ABresult
0X0
100
111
864 3 $l->{geometry}{location}{lat} = $l->{lat};
865 3 ▶ $l->{geometry}{location}{lng} = $l->{lng} // $l->{lon};
Condition33%1/3
$l->{"lng"} // $l->{"lon"}
l!l&&r!l&&!r
300
MC/DC0%0/2
$l->{"lng"} // $l->{"lon"}
$l->{"lng"} $l->{"lon"}
Truth table33%1/3
A // B
A= $l->{"lng"}B= $l->{"lon"}
ABresult
1X1
011
000
866 }
867  
868 # Convenience aliases (idempotent if already set by GLP)
869 4 ▶ $l->{'lat'} //= $l->{geometry}{location}{lat};
Condition66%2/3
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
l!l&&r!l&&!r
310
MC/DC0%0/2
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
$l->{"lat"} $l->{"geometry"}{"location"}{"lat"}
Truth table66%2/3
A //= B
A= $l->{"lat"}B= $l->{"geometry"}{"location"}{"lat"}
ABresult
1X1
011
000
870 4 ▶ $l->{'lng'} //= $l->{geometry}{location}{lng};
Condition66%2/3
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
310
MC/DC0%0/2
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lng"} $l->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $l->{"lng"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
871 4 ▶ $l->{'lon'} //= $l->{geometry}{location}{lng};
Condition33%1/3
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
040
MC/DC0%0/2
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lon"} $l->{"geometry"}{"location"}{"lng"}
Truth table33%1/3
A //= B
A= $l->{"lon"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
872  
873 4 CORE::push @{$self->{'log'}}, {
874 line => $call_details[2],
875 location => $location,
876 timetaken => $timetaken,
877 geocoder => ref($geocoder),
878 wantarray => wantarray,
879 result => $l,
880 };
881 4 $good_result = $l;
882 4 last POSSIBLE_LOCATION;
883 }
884  
885 # Only HASH results need normalisation
886 135 ▶ next if(ref($l) ne 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
if ref $l ne "HASH" 0 135 135
887  
888 135 ▶ if($l->{'error'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($l->{'error'}) { } 2 133 135
889 # A top-level 'error' key signals a provider-level failure
890 my $log = {
891 line => $call_details[2],
892 location => $location,
893 timetaken => $timetaken,
894 geocoder => ref($geocoder),
895 wantarray => wantarray,
896 2 error => $l->{'error'},
897 };
898 2 CORE::push @{$self->{'log'}}, $log;
899 2 next ENCODER;
900 } else {
901 # Map provider-specific fields to the canonical geometry structure
902 133 ▶ if(!defined($l->{geometry}{location}{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $l->{"geometry"}{"location"}{"lat"}) 127 6 133
903 127 my ($lat, $long);
904  
905 127 ▶ if(defined($l->{lat}) && defined($l->{lon})) {
Branch: 11 branches
BranchTrueFalseTotal
if (defined $l->{'lat'} and defined $l->{'lon'}) { } 99 28 127
elsif ($l->{'BestLocation'}) { } 2 26 28
elsif ($l->{'point'}) { } 3 23 26
elsif (defined $l->{'latt'}) { } 2 21 23
elsif (defined $l->{'latitude'}) { } 3 18 21
elsif (defined $l->{'properties'}{'geoLatitude'}) { } 1 17 18
elsif ($l->{'results'}[0]{'geometry'}) { } 3 14 17
elsif ($l->{'RESULTS'}) { } 2 12 14
elsif (defined $l->{'result'}{'addressMatches'}[0]{'coordinates'}{'y'}) { } 1 11 12
elsif (defined $l->{'lat'}) { } 3 8 11
elsif ($l->{'features'}) { } 4 4 8
Condition100%3/3
defined $l->{"lat"} and defined $l->{"lon"}
!ll&&!rl&&r
25399
MC/DC100%2/2
defined $l->{"lat"} and defined $l->{"lon"}
defined $l->{"lat"} defined $l->{"lon"}
Truth table100%3/3
A and B
A= defined $l->{"lat"}B= defined $l->{"lon"}
ABresult
0X0
100
111
906 # OSM / RandMcNally: top-level lat/lon fields
907 99 $lat = $l->{lat};
908 99 $long = $l->{lon};
909 99 $l->{'debug'} = __LINE__;
910 } elsif($l->{BestLocation}) {
911 # Bing Maps: BestLocation.Coordinates.{Latitude,Longitude}
912 2 $lat = $l->{BestLocation}->{Coordinates}->{Latitude};
913 2 $long = $l->{BestLocation}->{Coordinates}->{Longitude};
914 2 $l->{'debug'} = __LINE__;
915 } elsif($l->{point}) {
916 # Bing Maps alternative: point.coordinates[lat, lng]
917 3 $lat = $l->{point}->{coordinates}[0];
918 3 $long = $l->{point}->{coordinates}[1];
919 3 $l->{'debug'} = __LINE__;
920 } elsif(defined($l->{latt})) {
921 # geocoder.ca: latt / longt fields
922 2 $lat = $l->{latt};
923 2 $long = $l->{longt};
924 2 $l->{'debug'} = __LINE__;
925 } elsif(defined($l->{latitude})) {
926 # postcodes.io, Geo::Coder::Free: latitude / longitude
927 3 $lat = $l->{latitude};
928 3 $long = $l->{longitude};
929 3 ▶ if(my $type = $l->{'local_type'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $l->{"local_type"}) 1 2 3
930 # Carry the local_type hint forward as a normalised 'type'
931 1 $l->{'type'} = lcfirst($type);
932 }
933 3 $l->{'debug'} = __LINE__;
934 } elsif(defined($l->{'properties'}{'geoLatitude'})) {
935 # HERE / Ovi: properties.geoLatitude / geoLongitude
936 1 $lat = $l->{properties}{geoLatitude};
937 1 $long = $l->{properties}{geoLongitude};
938 1 $l->{'debug'} = __LINE__;
939 } elsif($l->{'results'}[0]->{'geometry'}) {
940 3 ▶ if($l->{'results'}[0]->{'geometry'}->{'location'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($l->{'results'}[0]{'geometry'}{'location'}) { } 1 2 3
941 # DataScienceToolkit mirrors the Google Maps shape
942 1 $lat = $l->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
943 1 $long = $l->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
944 1 $l->{'debug'} = __LINE__;
945 } else {
946 # OpenCage places lat/lng directly under geometry
947 2 $lat = $l->{'results'}[0]->{'geometry'}->{'lat'};
948 2 $long = $l->{'results'}[0]->{'geometry'}->{'lng'};
949 2 $l->{'debug'} = __LINE__;
950 }
951 } elsif($l->{'RESULTS'}) {
952 # GeoCodeFarm: RESULTS[0].COORDINATES.{latitude,longitude}
953 2 $lat = $l->{'RESULTS'}[0]{'COORDINATES'}{'latitude'};
954 2 $long = $l->{'RESULTS'}[0]{'COORDINATES'}{'longitude'};
955 2 $l->{'debug'} = __LINE__;
956 } elsif(defined($l->{result}{addressMatches}[0]->{coordinates}{y})) {
957 # US Census Bureau: result.addressMatches[0].coordinates.{y,x}
958 1 $lat = $l->{result}{addressMatches}[0]->{coordinates}{y};
959 1 $long = $l->{result}{addressMatches}[0]->{coordinates}{x};
960 1 $l->{'debug'} = __LINE__;
961 } elsif(defined($l->{lat})) {
962 # Geo::GeoNames: lat / lng (reached only after lat+lon check fails)
963 3 $lat = $l->{lat};
964 3 $long = $l->{lng};
965 3 $l->{'debug'} = __LINE__;
966 } elsif($l->{features}) {
967 4 ▶ if($l->{features}[0]->{center}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($l->{'features'}[0]{'center'}) { } 1 3 4
elsif ($l->{'features'}[0]{'geometry'}{'coordinates'}) { } 1 2 3
968 # Geo::Coder::Mapbox: center is [lng, lat]
969 1 $lat = $l->{features}[0]->{center}[1];
970 1 $long = $l->{features}[0]->{center}[0];
971 1 $l->{'debug'} = __LINE__;
972 } elsif($l->{'features'}[0]{'geometry'}{'coordinates'}) {
973 # Geo::Coder::GeoApify: coordinates is [lng, lat]
974 1 $lat = $l->{'features'}[0]{'geometry'}{'coordinates'}[1];
975 1 $long = $l->{'features'}[0]{'geometry'}{'coordinates'}[0];
976 1 $l->{'debug'} = __LINE__;
977 } else {
978 # GeoApify signals not-found via empty features, not an error
979 2 next ENCODER;
980 }
981 } else {
982 4 $l->{'debug'} = __LINE__;
983 }
984  
985 125 ▶ if(defined($lat) && defined($long)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lat and defined $long) { } 121 4 125
Condition66%2/3
defined $lat and defined $long
!ll&&!rl&&r
40121
MC/DC50%1/2
defined $lat and defined $long
defined $lat defined $long
Truth table66%2/3
A and B
A= defined $latB= defined $long
ABresult
0X0
100
111
986 # Populate the canonical geometry structure
987 121 $l->{geometry}{location}{lat} = $lat;
988 121 $l->{geometry}{location}{lng} = $long;
989 # Compatibility aliases expected by callers
990 121 $l->{'lat'} = $lat;
991 121 $l->{'lon'} = $long;
992 } else {
993 # No coordinates extracted; clean up any partial data
994 4 delete $l->{'geometry'};
995 4 delete $l->{'lat'};
996 4 delete $l->{'lon'};
997 }
998  
999 # geocoder.xyz provides a country name under 'standard'
1000 125 ▶ if($l->{'standard'}{'countryname'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($l->{"standard"}{"countryname"}) 1 124 125
1001 1 $l->{'address'}{'country'} = $l->{'standard'}{'countryname'};
1002 }
1003 }
1004  
1005 # A result whose geometry has lat but no lng may still carry the
1006 # longitude at the top level, some geocoders using the legacy
1007 # 'long' key for it
1008 131 ▶ if(defined($l->{geometry}{location}{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $l->{"geometry"}{"location"}{"lat"}) 127 4 131
1009 127 ▶ $l->{geometry}{location}{lng} //= $l->{'lng'} // $l->{'lon'} // $l->{'long'};
Condition66%6/9
$l->{"geometry"}{"location"}{"lng"} //= ($l->{"lng"} // $l->{"lon"}) // $l->{"long"}
l!l&&r!l&&!r
12412
($l->{"lng"} // $l->{"lon"}) // $l->{"long"}
l!l&&r!l&&!r
012
$l->{"lng"} // $l->{"lon"}
l!l&&r!l&&!r
003
MC/DC0%0/4
$l->{"geometry"}{"location"}{"lng"} //= ($l->{"lng"} // $l->{"lon"}) // $l->{"long"}
$l->{"geometry"}{"location"}{"lng"} $l->{"lng"} $l->{"lon"} $l->{"long"}
Truth table0%0/5
A //= B // C // D
A= $l->{"geometry"}{"location"}{"lng"}B= $l->{"lng"}C= $l->{"lon"}D= $l->{"long"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1010 }
1011  
1012 # Only a result with both coordinates is usable; anything less is
1013 # passed over so that a later element, or the next geocoder, can
1014 # answer instead
1015 131 ▶ if(defined($l->{geometry}{location}{lat}) && defined($l->{geometry}{location}{lng})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"geometry"}{"location"}{"lng"}) 125 6 131
Condition100%3/3
defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"geometry"}{"location"}{"lng"}
!ll&&!rl&&r
42125
MC/DC100%2/2
defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"geometry"}{"location"}{"lng"}
defined $l->{"geometry"}{"location"}{"lat"} defined $l->{"geometry"}{"location"}{"lng"}
Truth table100%3/3
A and B
A= defined $l->{"geometry"}{"location"}{"lat"}B= defined $l->{"geometry"}{"location"}{"lng"}
ABresult
0X0
100
111
1016 $self->_debug($l->{geometry}{location}{lat}, '/',
1017 125 $l->{geometry}{location}{lng}, "\n");
1018  
1019 # Store the geocoder object (not just its name) on the result
1020 125 $l->{geocoder} = $geocoder;
1021 125 ▶ $l->{'lat'} //= $l->{geometry}{location}{lat};
Condition66%2/3
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
l!l&&r!l&&!r
12230
MC/DC0%0/2
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
$l->{"lat"} $l->{"geometry"}{"location"}{"lat"}
Truth table66%2/3
A //= B
A= $l->{"lat"}B= $l->{"geometry"}{"location"}{"lat"}
ABresult
1X1
011
000
1022 125 ▶ $l->{'lng'} //= $l->{geometry}{location}{lng};
Condition66%2/3
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
41210
MC/DC0%0/2
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lng"} $l->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $l->{"lng"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
1023 125 ▶ $l->{'lon'} //= $l->{geometry}{location}{lng};
Condition66%2/3
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
12230
MC/DC0%0/2
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lon"} $l->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $l->{"lon"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
1024  
1025 125 my $log = {
1026 line => $call_details[2],
1027 location => $location,
1028 timetaken => $timetaken,
1029 geocoder => ref($geocoder),
1030 wantarray => wantarray,
1031 result => $l,
1032 };
1033 125 CORE::push @{$self->{'log'}}, $log;
1034  
1035 # Record which element succeeded, then exit the inner loop
1036 125 $good_result = $l;
1037 125 last POSSIBLE_LOCATION;
1038 }
1039 }
1040 }
1041  
1042 # Only attempt to return / cache if normalisation actually succeeded
1043 136 ▶ next ENCODER unless defined $good_result;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $good_result 7 129 136
1044  
1045 129 $self->_debug('Number of matches from ', ref($geocoder), ': ',
1046 scalar(@rc), "\n");
1047  
1048 129 ▶ if($self->{'debug'} >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"} >= 2) 2 127 129
1049 # Use 'local' to avoid permanently altering the global Maxdepth
1050 2 local $Data::Dumper::Maxdepth = 10;
1051 2 $self->_debug(Data::Dumper->new([\@rc])->Dump());
1052 }
1053  
1054 # Only a result with both coordinates is accepted above, so this can
1055 # fail only if the normalisation itself is wrong
1056 129 ▶ if((!defined($good_result->{lat})) || (!defined($good_result->{lng}))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $good_result->{"lat"} and defined $good_result->{"lng"}) 0 129 129
Condition33%1/3
defined $good_result->{"lat"} and defined $good_result->{"lng"}
!ll&&!rl&&r
00129
MC/DC0%0/2
defined $good_result->{"lat"} and defined $good_result->{"lng"}
defined $good_result->{"lat"} defined $good_result->{"lng"}
Truth table33%1/3
A and B
A= defined $good_result->{"lat"}B= defined $good_result->{"lng"}
ABresult
0X0
100
111
1057 0 $self->_warn(Data::Dumper->new([\@rc])->Dump());
1058 0 $self->_error("BUG: '$location': HASH exists but is not sensible");
1059 }
1060  
1061 129 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 9 120 129
1062 # A bare scalar the loop passed over is not a result
1063 9 @rc = grep { ref } @rc;
1064 9 $self->_cache($location, \@rc);
1065 9 return @rc;
1066 }
1067  
1068 120 $self->_cache($location, $good_result);
1069 120 return $good_result;
1070 }
1071  
1072 # ── No geocoder produced a usable result ──────────────────────────────
1073  
1074 58 $self->_debug("No matches\n");
1075  
1076 # Cache the not-found result so repeated calls do not hammer all backends
1077 58 $self->_cache($location, undef);
1078  
1079 58 ▶ return wantarray ? () : undef;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 56 58
1080 }
1081  
1082 # =============================================================================
1083  
1084 =head2 ua
1085  
1086 Gives a user agent (the object that makes the web requests) to every
1087 geocoder in the chain. Use it to set a proxy or a time-out for all of
1088 them at once.
1089  
1090 use LWP::UserAgent;
1091  
1092 my $ua = LWP::UserAgent->new(timeout => 10);
1093 $ua->env_proxy(1);
1094 $list->ua($ua);
1095  
1096 If C<$ua> has both C<clone()> and C<agent()> methods, as
1097 L<LWP::UserAgent> does, each geocoder is given its own copy. The
1098 C<agent> string of each copy is set to the geocoder's class name and
1099 version, such as C<'Geo::Coder::OSM/0.03'>, so each service can see which
1100 module is calling it. Otherwise every geocoder is given C<$ua> itself.
1101  
1102 Add the geocoders before you call C<ua>: geocoders added later do not get
1103 the user agent.
1104  
1105 There is no way to read the user agent back, because each geocoder may
1106 have a different one.
1107  
1108 If C<$ua> is missing or false, nothing changes and nothing is returned.
1109 C<ua> croaks with C<No geocoder found> if an entry in the chain has no
1110 geocoder.
1111  
1112 =head3 API SPECIFICATION
1113  
1114 =head4 INPUT
1115  
1116 {
1117 ua => { type => 'object', optional => 1 },
1118 }
1119  
1120 =head4 OUTPUT
1121  
1122 {
1123 type => 'object',
1124 optional => 1,
1125 }
1126  
1127 # The same $ua that was passed in, or nothing when $ua is false
1128  
1129 =cut
1130  
1131 sub ua
1132 35 ▶{
Subroutine ua: called CC=9 SCAR=22.0
Pod documented
1133 35 my ($self, $ua) = @_;
1134  
1135 # Nothing to propagate if no UA was supplied
1136 35 ▶ return unless $ua;
Branch: 1 branch
BranchTrueFalseTotal
unless $ua 7 28 35
1137  
1138 # Push the UA into every geocoder in the chain
1139 28 foreach my $g (@{$self->{geocoders}}) {
1140 31 ▶ my $geocoder = (ref($g) eq 'HASH') ? $g->{geocoder} : $g;
Branch: 1 branch
BranchTrueFalseTotal
ref $g eq 'HASH' ? : 6 25 31
1141 # Guard against a misconfigured entry that has no geocoder object
1142 31 ▶ Carp::croak('No geocoder found') unless defined $geocoder;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $geocoder 4 27 31
1143  
1144 # When the incoming UA supports clone(), create a per-geocoder copy
1145 # and set the geocoder's own agent string on that copy.
1146 # Some APIs (e.g. OSM Nominatim) require a specific User-Agent and
1147 # refuse requests that carry the generic libwww-perl default.
1148 # The agent string is derived from the geocoder class name and version
1149 # (e.g. 'Geo::Coder::OSM/0.03') without reading the geocoder's current
1150 # UA, which would trigger any spy or hook installed on its ua() method.
1151 27 ▶ if($ua->can('clone') && $ua->can('agent')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ua->can('clone') and $ua->can('agent')) { } 13 14 27
Condition100%3/3
$ua->can("clone") and $ua->can("agent")
!ll&&!rl&&r
13113
MC/DC100%2/2
$ua->can("clone") and $ua->can("agent")
$ua->can("clone") $ua->can("agent")
Truth table100%3/3
A and B
A= $ua->can("clone")B= $ua->can("agent")
ABresult
0X0
100
111
1152 13 my $per_ua = $ua->clone();
1153 13 my $class = ref($geocoder);
1154 13 ▶ my $version = eval { $geocoder->VERSION() } // '';
Condition100%2/2
eval { do { $geocoder->VERSION } } // ""
l!l
211
MC/DC100%1/1
eval { do { $geocoder->VERSION } } // ""
eval { do { $geocoder->VERSION } }
Truth table100%2/2
A
A= eval { do { $geocoder->VERSION } }
Aresult
11
00
1155 13 ▶ $per_ua->agent($version ? "$class/$version" : $class);
Branch: 1 branch
BranchTrueFalseTotal
$version ? : 2 11 13
1156 13 $geocoder->ua($per_ua);
1157 } else {
1158 14 $geocoder->ua($ua);
1159 }
1160 }
1161  
1162 # Return the UA so callers can verify what was set (API contract)
1163 24 return $ua;
1164 }
1165  
1166 # =============================================================================
1167  
1168 =head2 reverse_geocode
1169  
1170 Finds the address of a position: the opposite of C<geocode>.
1171  
1172 my $address = $list->reverse_geocode(latlng => '51.5034,-0.1276');
1173 my $address = $list->reverse_geocode('51.5034,-0.1276'); # the same
1174 print "Address: $address\n" if defined($address);
1175  
1176 my @addresses = $list->reverse_geocode(latlng => '51.5034,-0.1276');
1177  
1178 C<latlng> is the latitude, a comma, and the longitude, in that order. It
1179 must be two plain decimal numbers written with the digits C<0> to C<9>.
1180 Spaces, tabs and a C<+> or C<-> sign are allowed. Anything else, such as
1181 C<'51.5;-0.1'>, C<'1e5,2'> or C<'51.5'>, makes C<reverse_geocode> croak
1182 before any geocoder is asked.
1183  
1184 The geocoders are asked in turn, as for C<geocode>. C<limit> is honoured;
1185 C<regex> is not. If a geocoder complains that it does not know the
1186 C<latlng> parameter, it is asked again with only C<lat> and C<lon>. If a
1187 geocoder dies for any other reason, a warning is given and the next
1188 geocoder is asked.
1189  
1190 B<Scalar context> returns one address string, or C<undef>.
1191  
1192 B<List context> returns every address from the first geocoder that has
1193 any, or an empty list.
1194  
1195 An address is taken from the first of these that the answer has:
1196  
1197 =over 4
1198  
1199 =item * C<display_name> (OpenStreetMap, and others that copy it)
1200  
1201 =item * the fields of geocoder.ca: C<stnumber>, C<staddress>, C<city> and
1202 C<prov> for Canada, giving for example
1203 C<'1 Sussex Dr, Ottawa, ON'>; or the C<usa> fields for the United States,
1204 giving for example C<'1600 Pennsylvania Ave, Washington, DC, USA'>
1205  
1206 =item * C<features[0].properties.formatted> (GeoApify); only the first
1207 feature is used
1208  
1209 =back
1210  
1211 If a geocoder returns a plain string, the string is the address.
1212  
1213 Addresses are cached under the C<latlng> string, so asking again for the
1214 same position does not ask any geocoder.
1215  
1216 =head3 API SPECIFICATION
1217  
1218 =head4 INPUT
1219  
1220 {
1221 latlng => { type => 'string', optional => 0, matches => qr/^[ \t]*[-+]?(?:[0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)[ \t]*,[ \t]*[-+]?(?:[0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)[ \t]*$/ },
1222 }
1223  
1224 =head4 OUTPUT
1225  
1226 {
1227 type => 'string',
1228 optional => 1,
1229 }
1230  
1231 # Scalar context: an address string, or undef when not found
1232 # List context: a list of address strings, or an empty list
1233  
1234 =cut
1235  
1236 86 ▶sub reverse_geocode {
Subroutine reverse_geocode: called CC=36 SCAR=35.9
Pod documented
1237 86 my $self = shift;
1238  
1239 # The geocoders are called inside eval; the caller's $@ is not ours to change
1240 86 local $@;
1241  
1242 86 my $params = Params::Get::get_params('latlng', \@_);
1243  
1244 84 ▶ my $latlng = $params->{'latlng'} or Carp::croak('Usage: reverse_geocode(latlng => $location)');
Branch: 1 branch
BranchTrueFalseTotal
my $latlng = $params->{"latlng"} or Carp::croak("Usage: reverse_geocode(latlng => \$location)") 82 2 84
1245  
1246 # Only a numeric pair is a position; anything else would be split into
1247 # nonsense coordinates and sent to every backend
1248 82 ▶ Carp::croak('Usage: reverse_geocode(latlng => $location)')
Branch: 1 branch
BranchTrueFalseTotal
if ref $latlng or not $latlng =~ /$LATLNG_RE/ 13 69 82
Condition100%3/3
ref $latlng or not $latlng =~ /$LATLNG_RE/
l!l&&r!l&&!r
11269
MC/DC100%2/2
ref $latlng or not $latlng =~ /$LATLNG_RE/
ref $latlng not $latlng =~ /$LATLNG_RE/
Truth table100%3/3
A or not(B)
A= ref $latlngB= not $latlng =~ /$LATLNG_RE/
ABresult
1X1
011
000
1249 if(ref($latlng) || ($latlng !~ $LATLNG_RE));
1250  
1251 # Split into components; populate convenience keys for geocoders that want them
1252 69 my ($latitude, $longitude) = split(/,/, $latlng);
1253 69 ▶ $params->{'lat'} //= $latitude;
Condition33%1/3
$params->{"lat"} //= $latitude
l!l&&r!l&&!r
0690
MC/DC0%0/2
$params->{"lat"} //= $latitude
$params->{"lat"} $latitude
Truth table33%1/3
A //= B
A= $params->{"lat"}B= $latitude
ABresult
1X1
011
000
1254 69 ▶ $params->{'lon'} //= $longitude;
Condition33%1/3
$params->{"lon"} //= $longitude
l!l&&r!l&&!r
0690
MC/DC0%0/2
$params->{"lon"} //= $longitude
$params->{"lon"} $longitude
Truth table33%1/3
A //= B
A= $params->{"lon"}B= $longitude
ABresult
1X1
011
000
1255  
1256 # Check L1 / L2 cache before hitting any backend. A list-context call
1257 # caches every address as an arrayref and a scalar-context call caches
1258 # one string, so the entry is unpacked for the context asking for it.
1259 69 ▶ if(defined(my $rc = $self->_cache($latlng))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $rc = $self->_cache($latlng))) 7 62 69
1260 7 ▶ if(ref($rc) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rc eq "ARRAY") 4 3 7
1261 4 ▶ return wantarray ? @{$rc} : $rc->[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 3 1 4
1262 }
1263 3 return $rc;
1264 }
1265  
1266 62 my @call_details = caller(0);
1267  
1268 62 foreach my $g (@{$self->{geocoders}}) {
1269 65 my $geocoder = $g;
1270  
1271 # Apply the per-geocoder limit guard for hashref entries
1272 65 ▶ if(ref($geocoder) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq "HASH") 6 59 65
1273 6 ▶ if(exists($geocoder->{'limit'}) && defined(my $limit = $geocoder->{'limit'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})) 5 1 6
Condition66%2/3
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
!ll&&!rl&&r
105
MC/DC50%1/2
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
exists $geocoder->{"limit"} defined(my $limit = $geocoder->{"limit"})
Truth table66%2/3
A and B
A= exists $geocoder->{"limit"}B= defined(my $limit = $geocoder->{"limit"})
ABresult
0X0
100
111
1274 5 $self->_debug("limit: $limit\n");
1275 5 ▶ if($limit <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit <= 0) 4 1 5
1276 4 next;
1277 }
1278 1 $geocoder->{'limit'}--;
1279 }
1280 2 $geocoder = $g->{'geocoder'};
1281 }
1282  
1283 61 $self->_debug('trying ', ref($geocoder), "\n");
1284  
1285 61 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 22 39 61
1286 # ── List context: collect all address strings from this geocoder ───
1287 22 my @rc;
1288 my @locs;
1289 22 eval { @locs = $geocoder->reverse_geocode(%{$params}) };
1290  
1291 # Some geocoders (e.g. Geo::Coder::GeoApify) use strict parameter
1292 # validation and reject the 'latlng' key as unknown. Retry without
1293 # it -- lat and lon are already in %params from the split above.
1294 # Other geocoders (e.g. Geo::Coder::CA) require 'latlng', so the
1295 # first attempt must include it.
1296 22 ▶ if($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) 2 20 22
1297 2 my %no_latlng = %{$params};
1298 2 delete $no_latlng{'latlng'};
1299 2 $@ = '';
1300 2 eval { @locs = $geocoder->reverse_geocode(%no_latlng) };
1301 }
1302  
1303 22 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 3 19 22
1304 3 CORE::push @{$self->{'log'}}, {
1305 line => $call_details[2],
1306 location => $latlng,
1307 geocoder => ref($geocoder),
1308 timetaken => 0,
1309 wantarray => 1,
1310 error => $@,
1311 };
1312 3 $self->_warn(ref($geocoder), " '$latlng': $@");
1313 3 next;
1314 }
1315  
1316 19 ▶ $self->_debug(Data::Dumper->new([\@locs])->Dump()) if($self->{'debug'} >= 2);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} >= 2 0 19 19
1317  
1318 19 foreach my $loc (@locs) {
1319 27 ▶ next unless(defined($loc));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $loc 1 26 27
1320  
1321 # A plain string is the address itself, as it is in scalar
1322 # context; anything else that is not a HASH has none to give
1323 26 ▶ if(!ref($loc)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $loc) 2 24 26
1324 2 ▶ CORE::push @rc, $loc if(length($loc));
Branch: 1 branch
BranchTrueFalseTotal
if length $loc 1 1 2
1325 2 next;
1326 }
1327 24 ▶ next unless(reftype($loc) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::reftype($loc) eq "HASH" 1 23 24
1328  
1329 23 ▶ if(my $name = $loc->{'display_name'}) {
Branch: 3 branches
BranchTrueFalseTotal
if (my $name = $loc->{'display_name'}) { } 19 4 23
elsif ($loc->{'city'}) { } 2 2 4
elsif ($loc->{'features'}) { } 2 0 2
1330 # OSM returns the full address in display_name
1331 19 CORE::push @rc, $name;
1332 } elsif($loc->{'city'}) {
1333 # Geo::Coder::CA: build the address from individual fields
1334 2 CORE::push @rc, _build_ca_address($loc);
1335 } elsif($loc->{features}) {
1336 # GeoApify: formatted string inside a features array
1337 CORE::push @rc,
1338 2 $loc->{features}[0]->{properties}{formatted};
1339 2 last; # only one result from this provider
1340 }
1341 }
1342  
1343 19 CORE::push @{$self->{'log'}}, {
1344 line => $call_details[2],
1345 location => $latlng,
1346 geocoder => ref($geocoder),
1347 timetaken => 0,
1348 wantarray => 1,
1349 result => \@rc,
1350 };
1351  
1352 # A geocoder with no address for the position has not answered;
1353 # the next one may
1354 19 ▶ next unless(scalar(@rc));
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @rc 2 17 19
1355  
1356 17 $self->_cache($latlng, \@rc);
1357 17 return @rc;
1358  
1359 } else {
1360 # ── Scalar context: return the first address string ────────────────
1361 my $rc = $self->_cache($latlng)
1362 39 ▶ // eval { $geocoder->reverse_geocode(%{$params}) };
Condition66%2/3
$self->_cache($latlng) // eval { do { $geocoder->reverse_geocode(%{$params;}) } }
l!l&&r!l&&!r
02217
MC/DC50%1/2
$self->_cache($latlng) // eval { do { $geocoder->reverse_geocode(%{$params;}) } }
$self->_cache($latlng) eval { do { $geocoder->reverse_geocode(%{$params;}) } }
Truth table66%2/3
A // B
A= $self->_cache($latlng)B= eval { do { $geocoder->reverse_geocode(%{$params;}) } }
ABresult
1X1
011
000
1363  
1364 # Same strict-validation fallback as the list-context path above
1365 39 ▶ if($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) 7 32 39
1366 7 my %no_latlng = %{$params};
1367 7 delete $no_latlng{'latlng'};
1368 7 $@ = '';
1369 7 $rc = eval { $geocoder->reverse_geocode(%no_latlng) };
1370 }
1371  
1372 39 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 9 30 39
1373 9 CORE::push @{$self->{'log'}}, {
1374 line => $call_details[2],
1375 location => $latlng,
1376 geocoder => ref($geocoder),
1377 timetaken => 0,
1378 wantarray => 0,
1379 error => $@,
1380 };
1381 9 $self->_warn(ref($geocoder), " '$latlng': $@");
1382 9 next;
1383 }
1384  
1385 # A bare string needs no further processing
1386 30 ▶ next unless defined $rc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rc 2 28 30
1387 28 ▶ if(!ref($rc)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $rc) 3 25 28
1388 3 CORE::push @{$self->{'log'}}, {
1389 line => $call_details[2],
1390 location => $latlng,
1391 geocoder => ref($geocoder),
1392 timetaken => 0,
1393 wantarray => 0,
1394 result => $rc,
1395 };
1396 3 return $rc;
1397 }
1398  
1399 25 ▶ $self->_debug(Data::Dumper->new([$rc])->Dump()) if($self->{'debug'} >= 2);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} >= 2 1 24 25
1400  
1401 25 ▶ if(my $name = $rc->{'display_name'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $name = $rc->{"display_name"}) 20 5 25
1402 # OSM
1403 20 CORE::push @{$self->{'log'}}, {
1404 line => $call_details[2],
1405 location => $latlng,
1406 geocoder => ref($geocoder),
1407 timetaken => 0,
1408 wantarray => 0,
1409 result => $name,
1410 };
1411 20 return $self->_cache($latlng, $name);
1412 }
1413  
1414 5 ▶ if($rc->{'city'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc->{"city"}) 3 2 5
1415 # Geo::Coder::CA
1416 3 my $name = _build_ca_address($rc);
1417 3 CORE::push @{$self->{'log'}}, {
1418 line => $call_details[2],
1419 location => $latlng,
1420 geocoder => ref($geocoder),
1421 timetaken => 0,
1422 wantarray => 0,
1423 result => $name,
1424 };
1425 3 return $self->_cache($latlng, $name);
1426 }
1427  
1428 2 ▶ if($rc->{features}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc->{"features"}) 2 0 2
1429 # GeoApify
1430 2 my $name = $rc->{features}[0]->{properties}{formatted};
1431 2 CORE::push @{$self->{'log'}}, {
1432 line => $call_details[2],
1433 location => $latlng,
1434 geocoder => ref($geocoder),
1435 timetaken => 0,
1436 wantarray => 0,
1437 result => $name,
1438 };
1439 2 return $self->_cache($latlng, $name);
1440 }
1441 }
1442 }
1443  
1444 17 return;
1445 }
1446  
1447 # =============================================================================
1448  
1449 =head2 log
1450  
1451 Returns the record of what has happened since the object was made, or
1452 since the last C<flush()>. There is one entry for each question asked of
1453 a geocoder, and one for each answer that C<geocode()> serves from the
1454 cache. C<reverse_geocode()> adds no entry when it answers from the
1455 cache.
1456  
1457 for my $entry (@{ $list->log() }) {
1458 printf "%s: %.3fs via %s\n",
1459 $entry->{location},
1460 $entry->{timetaken},
1461 $entry->{geocoder};
1462 }
1463  
1464 Each entry is a hash reference with these keys:
1465  
1466 =over 4
1467  
1468 =item * C<location> - the place name or C<latlng> that was asked about
1469  
1470 =item * C<geocoder> - the class name of the geocoder, or C<'cache'>
1471  
1472 =item * C<timetaken> - how long the geocoder took, in seconds
1473  
1474 =item * C<line> - the line of your program that made the call
1475  
1476 =item * C<wantarray> - true if the call was made in list context
1477  
1478 =item * C<result> - the answer, when there was one; the string
1479 C<'not found'> when the geocoder had none
1480  
1481 =item * C<error> - the error, when the geocoder died or returned an
1482 error; this can be an exception object, not only a string
1483  
1484 =back
1485  
1486 The returned array reference is the object's own record, not a copy.
1487  
1488 =head3 API SPECIFICATION
1489  
1490 =head4 INPUT
1491  
1492 []
1493  
1494 =head4 OUTPUT
1495  
1496 {
1497 type => 'arrayref',
1498 }
1499  
1500 # Each element:
1501 # {
1502 # line => Int,
1503 # location => Str,
1504 # timetaken => Num,
1505 # geocoder => Str, # class name, or 'cache'
1506 # wantarray => Bool,
1507 # result => HASHREF | ARRAYREF | Str, # on success
1508 # error => Str | OBJECT | HASHREF, # on failure
1509 # }
1510  
1511 =cut
1512  
1513 44 ▶sub log {
Subroutine log: called CC=2 SCAR=6.9
Pod documented
1514 44 my $self = shift;
1515  
1516 # Guard against the state left by flush(); always return a valid arrayref
1517 44 ▶ return $self->{'log'} // [];
Condition100%2/2
$self->{"log"} // []
l!l
422
MC/DC100%1/1
$self->{"log"} // []
$self->{"log"}
Truth table100%2/2
A
A= $self->{"log"}
Aresult
11
00
1518 }
1519  
1520 # =============================================================================
1521  
1522 =head2 flush
1523  
1524 Empties the log and returns the object itself, so that it can be chained.
1525  
1526 $list->geocode('Paris, France');
1527 my $entries = $list->log();
1528 $list->flush()->geocode('London, UK');
1529  
1530 C<flush> does B<not> empty the cache.
1531  
1532 =head3 API SPECIFICATION
1533  
1534 =head4 INPUT
1535  
1536 []
1537  
1538 =head4 OUTPUT
1539  
1540 {
1541 type => 'object',
1542 isa => 'Geo::Coder::List',
1543 }
1544  
1545 =cut
1546  
1547 16 ▶sub flush {
Subroutine flush: called CC=1 SCAR=0.0
Pod documented
1548 16 my $self = shift;
1549  
1550 # Reset to an empty arrayref so log() always returns a valid reference
1551 16 $self->{'log'} = [];
1552  
1553 16 return $self;
1554 }
1555  
1556 # =============================================================================
1557 # PRIVATE HELPERS
1558 # =============================================================================
1559  
1560 # _build_ca_address
1561 #
1562 # Purpose: Assemble a printable address string from a Geo::Coder::CA
1563 # reverse-geocode response. The CA response uses different keys
1564 # for US addresses (nested under 'usa') vs Canadian ones.
1565 #
1566 # Entry: $loc - HASHREF from Geo::Coder::CA reverse_geocode()
1567 #
1568 # Exit: Returns a plain string, or empty string if nothing was found.
1569 #
1570 # Notes: Street number and name are joined with a space; other parts
1571 # (city, province/state, country) are joined with ', '.
1572  
1573 sub _build_ca_address
1574 16 ▶{
Subroutine _build_ca_address: called CC=17 SCAR=28.4
1575 16 my $loc = $_[0];
1576 16 my $name = '';
1577  
1578 16 ▶ if(my $usa = $loc->{'usa'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $usa = $loc->{'usa'}) { } 5 11 16
1579 # US address layout inside a CA result
1580 5 ▶ $name = $usa->{'usstnumber'} // '';
Condition100%2/2
$usa->{"usstnumber"} // ""
l!l
32
MC/DC100%1/1
$usa->{"usstnumber"} // ""
$usa->{"usstnumber"}
Truth table100%2/2
A
A= $usa->{"usstnumber"}
Aresult
11
00
1581 # Street name follows number with a space; if no number, no leading space
1582 5 ▶ $name .= ($name ? ' ' : '') . $usa->{'usstaddress'} if $usa->{'usstaddress'};
Branch: 2 branches
BranchTrueFalseTotal
if $usa->{"usstaddress"} 4 1 5
$name ? : 3 1 4
1583 # City, state, country each separated by ', '; skip separator if name empty
1584 5 ▶ $name .= ($name ? ', ' : '') . $usa->{'uscity'} if $usa->{'uscity'};
Branch: 2 branches
BranchTrueFalseTotal
if $usa->{"uscity"} 4 1 5
$name ? : 3 1 4
1585 5 ▶ $name .= ($name ? ', ' : '') . $usa->{'state'} if $usa->{'state'};
Branch: 2 branches
BranchTrueFalseTotal
if $usa->{"state"} 3 2 5
$name ? : 3 0 3
1586 # Country is always appended for the US branch
1587 5 ▶ $name .= ($name ? ', ' : '') . 'USA';
Branch: 1 branch
BranchTrueFalseTotal
$name ? : 5 0 5
1588 } else {
1589 # Canadian address layout
1590 11 ▶ $name = $loc->{'stnumber'} // '';
Condition100%2/2
$loc->{"stnumber"} // ""
l!l
83
MC/DC100%1/1
$loc->{"stnumber"} // ""
$loc->{"stnumber"}
Truth table100%2/2
A
A= $loc->{"stnumber"}
Aresult
11
00
1591 # Street name follows number with a space; if no number, no leading space
1592 11 ▶ $name .= ($name ? ' ' : '') . $loc->{'staddress'} if $loc->{'staddress'};
Branch: 2 branches
BranchTrueFalseTotal
if $loc->{"staddress"} 8 3 11
$name ? : 7 1 8
1593 11 ▶ $name .= ($name ? ', ' : '') . $loc->{'city'} if $loc->{'city'};
Branch: 2 branches
BranchTrueFalseTotal
if $loc->{"city"} 9 2 11
$name ? : 8 1 9
1594 11 ▶ $name .= ($name ? ', ' : '') . $loc->{'prov'} if $loc->{'prov'};
Branch: 2 branches
BranchTrueFalseTotal
if $loc->{"prov"} 8 3 11
$name ? : 8 0 8
1595 }
1596  
1597 16 return $name;
1598 }
1599  
1600 # -----------------------------------------------------------------------------
1601  
1602 # _cache
1603 #
1604 # Read from or write to the two-level cache.
1605 # L1 is an in-process HASH (always active).
1606 # L2 is an optional CHI-compatible object or a plain HASH ref.
1607 #
1608 # Entry (write): _cache($key, $value)
1609 # $value may be undef, which is stored as $NOT_FOUND_SENTINEL so
1610 # subsequent reads can distinguish "cached not-found" from "never
1611 # looked up". Detect the write path by testing scalar(@_) before
1612 # shifting, not by truthiness of the value.
1613 #
1614 # Entry (read): _cache($key)
1615 #
1616 # Exit (write): Returns $value (undef if the location was not found).
1617 # Exit (read): Returns the cached value, or undef if not in cache.
1618 # $NOT_FOUND_SENTINEL is never surfaced to callers; undef is
1619 # returned in its place so callers handle both cases identically.
1620 #
1621 # Side effects: May update $self->{locations} (L1) and $self->{'cache'} (L2).
1622 #
1623 # Notes: Cache TTLs are taken from $self->{cache_*_duration}, which are
1624 # initialised from %config and overridable via Object::Configure.
1625 # Not-found sentinels are stored only in L1 to avoid leaking
1626 # internal implementation details into an external L2 store.
1627  
1628 602 ▶sub _cache {
Subroutine _cache: called CC=30 SCAR=34.1
1629 602 my $self = shift;
1630 602 my $key = shift;
1631  
1632 # ── Write path ────────────────────────────────────────────────────────
1633 # Detect a write call by the presence of a third argument (even if undef).
1634 # Testing truthiness of the value would silently swallow not-found results.
1635  
1636 602 ▶ if(scalar(@_)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 261 341 602
1637 261 my $value = shift;
1638  
1639 # Store a sentinel for not-found so we can skip backends on repeat calls
1640 261 ▶ my $stored = defined($value) ? $value : $NOT_FOUND_SENTINEL;
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 197 64 261
1641 261 $self->{locations}->{$key} = $stored;
1642  
1643 261 my $rc = $value;
1644  
1645 261 ▶ if($self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 35 226 261
1646 # L2 is written from copies: the caller is returned $value and L1
1647 # holds it, so what is stripped for storage must not be stripped
1648 # from what they see
1649 35 my $l2value = $value;
1650 35 my $duration;
1651  
1652 35 ▶ if(ref($value) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 10 25 35
elsif (ref $value eq 'HASH') { } 21 4 25
1653 10 $l2value = [ map { _l2_copy($_, $self->{'debug'}) } @{$value} ];
1654  
1655 10 foreach my $item (@{$l2value}) {
1656 11 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 2 9 11
1657  
1658 9 ▶ unless(_has_lat($item)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_has_lat($item)) 5 4 9
1659 # Geometry without a lat may be a transient failure, so
1660 # retry soon; no geometry at all is a miss
1661 $duration //= defined($item->{geometry})
1662 ? $self->{'cache_part_duration'}
1663 5 ▶ : $self->{'cache_miss_duration'};
Branch: 1 branch
BranchTrueFalseTotal
defined $item->{'geometry'} ? : 3 2 5
Condition33%1/3
$duration //= defined $item->{"geometry"} ? $self->{"cache_part_duration"} : $self->{"cache_miss_duration"}
l!l&&r!l&&!r
050
MC/DC0%0/2
$duration //= defined $item->{"geometry"} ? $self->{"cache_part_duration"} : $self->{"cache_miss_duration"}
$duration defined $item->{"geometry"} ? $self->{"cache_part_duration"} : $self->{"cache_miss_duration"}
Truth table33%1/3
A //= B
A= $durationB= defined $item->{"geometry"} ? $self->{"cache_part_duration"} : $self->{"cache_miss_duration"}
ABresult
1X1
011
000
1664 5 $rc = undef;
1665 }
1666 }
1667  
1668 # All items were clean: use the full hit duration
1669 10 ▶ $duration //= $self->{'cache_hit_duration'};
Condition66%2/3
$duration //= $self->{"cache_hit_duration"}
l!l&&r!l&&!r
550
MC/DC0%0/2
$duration //= $self->{"cache_hit_duration"}
$duration $self->{"cache_hit_duration"}
Truth table66%2/3
A //= B
A= $durationB= $self->{"cache_hit_duration"}
ABresult
1X1
011
000
1670  
1671 } elsif(ref($value) eq 'HASH') {
1672 21 $l2value = _l2_copy($value, $self->{'debug'});
1673  
1674 21 ▶ if(_has_lat($l2value)) {
Branch: 2 branches
BranchTrueFalseTotal
if (_has_lat($l2value)) { } 14 7 21
elsif (defined $l2value->{'geometry'}) { } 4 3 7
1675 # Confirmed location: cache for a full month
1676 14 $duration = $self->{'cache_hit_duration'};
1677 } elsif(defined($l2value->{geometry})) {
1678 # Partial geometry: may be a transient failure, retry soon
1679 4 $duration = $self->{'cache_part_duration'};
1680 4 $rc = undef;
1681 } else {
1682 # No geometry at all: place probably does not exist
1683 3 $duration = $self->{'cache_miss_duration'};
1684 3 $rc = undef;
1685 }
1686 } else {
1687 # Scalar string or a blessed object (e.g. Geo::Location::Point)
1688 4 $l2value = _l2_copy($value, 1);
1689 4 $duration = $self->{'cache_hit_duration'};
1690 }
1691  
1692 35 ▶ $self->_debug(Data::Dumper->new([$l2value])->Dump()) if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 2 33 35
1693  
1694 # Do not push the not-found sentinel into L2
1695 35 ▶ if(!defined($value)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $value) { } 4 31 35
elsif (ref $self->{'cache'} eq 'HASH') { } 15 16 31
1696 # value is not-found; L1 sentinel is sufficient
1697 } elsif(ref($self->{'cache'}) eq 'HASH') {
1698 15 $self->{'cache'}->{$key} = $l2value;
1699 } else {
1700 # L2 is only an optimisation: a store that is down must not
1701 # lose the caller the result that has already been found
1702 16 local $@;
1703 16 ▶ eval { $self->{'cache'}->set($key, $l2value, $duration); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->{"cache"}->set($key, $l2value, $duration); 1 } } or $self->_warn(__PACKAGE__, ": cache set failed for '${key}': $@") 15 1 16
1704 or $self->_warn(__PACKAGE__, ": cache set failed for '$key': $@");
1705 }
1706 }
1707  
1708 261 return $rc;
1709 }
1710  
1711 # ── Read path ─────────────────────────────────────────────────────────
1712  
1713 # Check L1 first (in-process, no serialisation cost)
1714 341 my $rc = $self->{'locations'}->{$key};
1715  
1716 # Fall through to L2 only when L1 has no entry for this key
1717 341 ▶ if((!defined($rc)) && $self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $rc and $self->{"cache"}) 12 329 341
Condition100%3/3
not defined $rc and $self->{"cache"}
!ll&&!rl&&r
4728212
MC/DC100%2/2
not defined $rc and $self->{"cache"}
not defined $rc $self->{"cache"}
Truth table100%3/3
not(A) and B
A= not defined $rcB= $self->{"cache"}
ABresult
0X0
100
111
1718 12 ▶ if(ref($self->{'cache'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{'cache'} eq 'HASH') { } 8 4 12
1719 8 $rc = $self->{'cache'}->{$key};
1720 } else {
1721 # A store that cannot be read is treated as a miss, so the lookup
1722 # goes to the geocoders rather than failing
1723 4 local $@;
1724 4 $rc = eval { $self->{'cache'}->get($key) };
1725 4 ▶ $self->_warn(__PACKAGE__, ": cache get failed for '$key': $@") if($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 3 4
1726 }
1727 }
1728  
1729 341 ▶ return unless defined $rc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rc 289 52 341
1730  
1731 # Translate the not-found sentinel back to undef for the caller
1732 52 ▶ return if ref($rc) && (ref($rc) eq _NOT_FOUND_CLASS);
Branch: 1 branch
BranchTrueFalseTotal
if ref $rc and ref $rc eq "Geo::Coder::List::_NotFound" 9 43 52
Condition100%3/3
ref $rc and ref $rc eq "Geo::Coder::List::_NotFound"
!ll&&!rl&&r
4399
MC/DC100%2/2
ref $rc and ref $rc eq "Geo::Coder::List::_NotFound"
ref $rc ref $rc eq "Geo::Coder::List::_NotFound"
Truth table100%3/3
A and B
A= ref $rcB= ref $rc eq "Geo::Coder::List::_NotFound"
ABresult
0X0
100
111
1733  
1734 # Restore the convenience aliases that were stripped before L2 storage
1735 43 ▶ if(ref($rc) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rc eq "HASH") 29 14 43
1736 29 ▶ return unless defined($rc->{geometry}{location}{lat});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rc->{"geometry"}{"location"}{"lat"} 2 27 29
1737 27 ▶ $rc->{'lat'} //= $rc->{geometry}{location}{lat};
Condition66%2/3
$rc->{"lat"} //= $rc->{"geometry"}{"location"}{"lat"}
l!l&&r!l&&!r
2250
MC/DC0%0/2
$rc->{"lat"} //= $rc->{"geometry"}{"location"}{"lat"}
$rc->{"lat"} $rc->{"geometry"}{"location"}{"lat"}
Truth table66%2/3
A //= B
A= $rc->{"lat"}B= $rc->{"geometry"}{"location"}{"lat"}
ABresult
1X1
011
000
1738 27 ▶ $rc->{'lng'} //= $rc->{geometry}{location}{lng};
Condition66%2/3
$rc->{"lng"} //= $rc->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
2250
MC/DC0%0/2
$rc->{"lng"} //= $rc->{"geometry"}{"location"}{"lng"}
$rc->{"lng"} $rc->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $rc->{"lng"}B= $rc->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
1739 27 ▶ $rc->{'lon'} //= $rc->{geometry}{location}{lng};
Condition66%2/3
$rc->{"lon"} //= $rc->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
2250
MC/DC0%0/2
$rc->{"lon"} //= $rc->{"geometry"}{"location"}{"lng"}
$rc->{"lon"} $rc->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $rc->{"lon"}B= $rc->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
1740 }
1741  
1742 41 return $rc;
1743 }
1744  
1745 # A copy of one result fit for L2. The geocoder object becomes its class name,
1746 # since a handle it holds may not serialise, and unless $keep_all only geometry
1747 # is kept, to keep the entry small. Anything that is not a HASH-based
1748 # reference is returned as it is.
1749 42 ▶sub _l2_copy {
Subroutine _l2_copy: called CC=7 SCAR=19.5
1750 42 my ($item, $keep_all) = @_;
1751  
1752 42 ▶ return $item unless ref($item) && (reftype($item) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item and builtin::reftype($item) eq "HASH" 8 34 42
Condition100%3/3
ref $item and builtin::reftype($item) eq "HASH"
!ll&&!rl&&r
6234
MC/DC100%2/2
ref $item and builtin::reftype($item) eq "HASH"
ref $item builtin::reftype($item) eq "HASH"
Truth table100%3/3
A and B
A= ref $itemB= builtin::reftype($item) eq "HASH"
ABresult
0X0
100
111
1753  
1754 34 my $copy = { %{$item} };
1755 34 ▶ $copy = bless $copy, ref($item) if blessed($item);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($item) 3 31 34
1756  
1757 34 ▶ $copy->{'geocoder'} = ref($copy->{'geocoder'}) if ref($copy->{'geocoder'});
Branch: 1 branch
BranchTrueFalseTotal
if ref $copy->{"geocoder"} 13 21 34
1758  
1759 # A blessed object keeps its fields: its accessors may rely on them
1760 34 ▶ unless($keep_all || blessed($item)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($keep_all or builtin::blessed($item)) 28 6 34
Condition100%3/3
$keep_all or builtin::blessed($item)
l!l&&r!l&&!r
3328
MC/DC100%2/2
$keep_all or builtin::blessed($item)
$keep_all builtin::blessed($item)
Truth table100%3/3
A or B
A= $keep_allB= builtin::blessed($item)
ABresult
1X1
011
000
1761 28 delete @{$copy}{grep { $_ ne 'geometry' } keys %{$copy}};
1762 }
1763  
1764 34 return $copy;
1765 }
1766  
1767 # Whether a result carries a latitude, looked for without auto-vivifying the
1768 # path to it in a structure that may be shared with the caller
1769 36 ▶sub _has_lat {
Subroutine _has_lat: called CC=4 SCAR=13.9
1770 36 my $item = shift;
1771  
1772 36 ▶ return 0 unless ref($item->{geometry}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item->{"geometry"} eq "HASH" 8 28 36
1773 28 ▶ return 0 unless ref($item->{geometry}{location}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item->{"geometry"}{"location"} eq "HASH" 7 21 28
1774 21 ▶ return defined($item->{geometry}{location}{lat}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $item->{'geometry'}{'location'}{'lat'} ? : 19 2 21
1775 }
1776  
1777 # Emit a debug message somewhere
1778 845 ▶sub _debug {
Subroutine _debug: called CC=5 SCAR=16.1
1779 845 my $self = shift;
1780  
1781 # Callers may end the message with a newline or not; it is printed with
1782 # exactly one, and given to the logger with none
1783 845 ▶ my $message = join('', map { $_ // '' } @_);
Condition100%2/2
$_ // ""
l!l
23231
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
1784 845 ▶ $message .= "\n" unless($message =~ /\n\z/);
Branch: 1 branch
BranchTrueFalseTotal
unless $message =~ /\n\z/ 2 843 845
1785  
1786 845 ▶ if(my $logger = $self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 825 20 845
1787 825 (my $line = $message) =~ s/\n\z//;
1788 825 $logger->debug($line);
1789 }
1790 845 ▶ if($self->{debug}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 25 820 845
1791 25 print $message;
1792 }
1793 }
1794  
1795 # Emit a warning message somewhere
1796 34 ▶sub _warn {
Subroutine _warn: called CC=2 SCAR=6.9
1797 34 my $self = shift;
1798  
1799 34 ▶ if(my $logger = $self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{'logger'}) { } 28 6 34
1800 28 $logger->warn(@_);
1801 } else {
1802 6 Carp::carp(@_);
1803 }
1804 }
1805  
1806 # Emit an error message somewhere
1807 20 ▶sub _error {
Subroutine _error: called CC=2 SCAR=6.9
1808 20 my $self = shift;
1809  
1810 20 ▶ if(my $logger = $self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{'logger'}) { } 19 1 20
1811 19 $logger->error(@_);
1812 19 die @_;
1813 } else {
1814 1 Carp::croak(@_);
1815 }
1816 }
1817  
1818 # =============================================================================
1819 # DOCUMENTATION
1820 # =============================================================================
1821  
1822 =head1 COMMON PITFALLS
1823  
1824 =over 4
1825  
1826 =item * B<Scalar context and list context give different answers.>
1827  
1828 C<geocode()> and C<reverse_geocode()> return one answer in scalar
1829 context and all answers in list context. Perl decides the context from
1830 the code around the call, and some places give list context when you may
1831 not expect it:
1832  
1833 my %row = (name => $name, place => $list->geocode($name)); # list context!
1834 print 'Found: ', $list->geocode($name); # list context!
1835 return $list->geocode($name); # your caller decides
1836  
1837 When nothing is found, list context returns an I<empty list>, so in the
1838 first example the keys and values of C<%row> move out of step. Use
1839 C<scalar()> to be sure:
1840  
1841 my %row = (name => $name, place => scalar($list->geocode($name)));
1842  
1843 =item * B<C<undef> means "not found" and also "bad empty input".>
1844  
1845 C<geocode()> returns C<undef> both when no geocoder knows the place and
1846 when C<location> is C<undef> or empty (it also warns in that case). Other
1847 bad input, such as a reference or a string of digits, does not return
1848 C<undef>: it croaks. Wrap the call in C<eval> when the text comes from
1849 outside your program.
1850  
1851 =item * B<"Not found" is remembered for the life of the object.>
1852  
1853 When no geocoder finds a place, L1 remembers that, and later calls for
1854 the same place return C<undef> at once without asking any geocoder, even
1855 if a geocoder was only down for a moment. C<flush()> does not forget it,
1856 and nor does a clone, which shares L1. Make a new object with
1857 C<Geo::Coder::List-E<gt>new()> to ask again. L2 never stores "not
1858 found".
1859  
1860 =item * B<An answer from L2 has only its position.>
1861  
1862 To keep L2 small, only C<geometry> is stored there (unless C<debug> is
1863 set). An answer that comes from L2, for example in a new run of your
1864 program, has C<geometry>, C<lat>, C<lng>, C<lon> and C<geocoder> (set to
1865 C<'cache'>), but none of the provider's other fields, such as an address
1866 or a place type. Answers from L1 keep every field.
1867  
1868 =item * B<The C<geocoder> key is not always an object.>
1869  
1870 It is the geocoder object when a geocoder answered, and the string
1871 C<'cache'> when the cache answered. Do not call methods on it without
1872 checking. To get a printable name in both cases:
1873  
1874 my $source = ref($result->{geocoder}) || $result->{geocoder};
1875  
1876 =item * B<Changing an answer changes the cache.>
1877  
1878 The first answer for a place is the same hash that L1 stores. If you
1879 change it, later answers for that place, which are copies of the L1 entry,
1880 include your change. Copy the answer before you change it.
1881  
1882 =item * B<The hash you give to C<push()> is changed.>
1883  
1884 C<limit> counts down inside the hash reference that you pushed. If you
1885 push the same hash reference into two lists, they share one limit. A
1886 clone made with C<< $list->new() >> has its own copy.
1887  
1888 =item * B<The cache key is the exact text.>
1889  
1890 C<'Paris, France'>, C<'paris, france'> and C<'Paris,France'> are three
1891 different keys, and each one asks the geocoders again. Only runs of
1892 white space are made into one space before the text is used as a key.
1893  
1894 =item * B<HTML entities are always decoded.>
1895  
1896 C<'AT&amp;T Park'> is looked up as C<'AT&T Park'>. There is no way to
1897 look up text that really contains C<&amp;>.
1898  
1899 =item * B<Strings of digits depend on an optional module.>
1900  
1901 When L<Geo::Location::Predicate> is installed, C<geocode('12345')> croaks.
1902 When it is not installed, C<'12345'> is sent to the geocoders. If you
1903 handle postcodes or ZIP codes, add the country, such as
1904 C<'12345, USA'>.
1905  
1906 =item * B<C<reverse_geocode()> ignores C<regex>.>
1907  
1908 A geocoder added with C<regex> is still asked to reverse geocode every
1909 position. Only C<limit> is honoured.
1910  
1911 =item * B<The log grows until you empty it.>
1912  
1913 Every call adds to the log. In a long-running program, such as a web
1914 server, call C<flush()> from time to time.
1915  
1916 =item * B<Debug output goes to standard output.>
1917  
1918 With C<debug> set, messages are printed to C<STDOUT>, not C<STDERR>, so
1919 they mix with your program's own output. The same messages are always
1920 given to the configured C<logger> at debug level, whether C<debug> is set
1921 or not, so a logger is the way to collect them somewhere else.
1922  
1923 =back
1924  
1925 =head1 ENCODING
1926  
1927 =over 4
1928  
1929 =item * B<Place names> (C<location> in C<geocode()>) may contain any
1930 Unicode text, including accented letters, other alphabets and emoji.
1931 Give them to C<geocode()> as Perl I<character> strings: if your text is
1932 UTF-8 bytes from a file or a web form, decode it first, for example with
1933 C<Encode::decode('UTF-8', $bytes)>. HTML entities in the text are decoded
1934 into characters, so text that mixes UTF-8 bytes that are not yet decoded
1935 with entities becomes garbled. The text is passed to each geocoder unchanged apart from
1936 that; whether a geocoder understands emoji is up to the geocoder.
1937  
1938 =item * B<White space.> Runs of ASCII spaces, tabs and new lines are
1939 always made into one space. Unicode spaces, such as the no-break space,
1940 may or may not be, depending on how Perl stores the string; do not rely on
1941 it.
1942  
1943 =item * B<Positions> (C<latlng> in C<reverse_geocode()>) must be ASCII.
1944 Only the digits C<0> to C<9> are accepted. Other Unicode digits, such as
1945 Eastern Arabic or full-width digits, are refused.
1946  
1947 =item * B<Cache keys> are the cleaned text, so they can contain any
1948 character. L1 and a plain-hash L2 accept them all. An L2 object must
1949 accept character-string keys; L<CHI> does.
1950  
1951 =item * B<Answers> are returned as the geocoder gave them. Most
1952 geocoders return character strings.
1953  
1954 =item * B<Debug output> prints place names to C<STDOUT>. If they contain
1955 characters above 255, Perl warns C<Wide character in print> unless
1956 C<STDOUT> has an encoding layer, such as
1957 C<binmode(STDOUT, ':encoding(UTF-8)')>.
1958  
1959 =back
1960  
1961 =head1 AUTHOR
1962  
1963 Nigel Horne, C<< <njh at nigelhorne.com> >>
1964  
1965 =head1 BUGS
1966  
1967 Please report any bugs or feature requests to
1968 C<bug-geo-coder-list at rt.cpan.org>, or through the web interface at
1969 L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Geo-Coder-List>.
1970  
1971 Known limitations:
1972  
1973 =over 4
1974  
1975 =item * C<reverse_geocode()> does not yet support L<Geo::Location::Point> objects.
1976  
1977 =item * C<reverse_geocode()> does not honour C<regex>.
1978  
1979 =back
1980  
1981 =head1 SEE ALSO
1982  
1983 =over 4
1984  
1985 =item * L<Test Dashboard|https://nigelhorne.github.io/Geo-Coder-List/coverage/>
1986  
1987 =item * L<CHI>
1988  
1989 =item * L<Geo::Coder::All>
1990  
1991 =item * L<Geo::Coder::GooglePlaces>
1992  
1993 =item * L<Geo::Coder::Many>
1994  
1995 =item * L<Geo::Location::Predicate>
1996  
1997 =item * L<HTML::GoogleMaps::V3>
1998  
1999 =item * L<HTML::OSM>
2000  
2001 =item * L<Configure an Object at Runtime|Object::Configure>
2002  
2003 =item * L<Readonly>
2004  
2005 =back
2006  
2007 =head1 SUPPORT
2008  
2009 You can find documentation for this module with the perldoc command:
2010  
2011 perldoc Geo::Coder::List
2012  
2013 =over 4
2014  
2015 =item * RT: CPAN's request tracker
2016  
2017 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Geo-Coder-List>
2018  
2019 =item * MetaCPAN
2020  
2021 L<https://metacpan.org/release/Geo-Coder-List>
2022  
2023 =back
2024  
2025 =encoding utf-8
2026  
2027 =head1 FORMAL SPECIFICATION
2028  
2029 The specifications below use the Z notation. They describe what each
2030 method does to the state of the object; they do not describe how.
2031  
2032 =head2 State
2033  
2034 [Geocoder, Regex, Text, Result, LogEntry, Duration]
2035  
2036 Key == Text
2037 NotFound ::= notFound
2038 Entry ::= plain⟨⟨Geocoder⟩⟩
2039 | routed⟨⟨Geocoder × ℙ Text × (ℤ ∪ {∞})⟩⟩
2040 -- the geocoder, the texts its regex matches, its limit
2041  
2042 ┌─ GeoCoderList ─────────────────────────────────────────────────
2043 │ geocoders : seq Entry
2044 │ L1 : Key ⇸ (Result ∪ NotFound)
2045 │ L2 : Key ⇸ Result
2046 │ log : seq LogEntry
2047 │ debug : 0 ‥ 2
2048 │ hit, part, miss : Duration
2049 ├────────────────────────────────────────────────────────────────
2050 │ notFound ∉ ran L2
2051 │ ∀ r : ran L2 • dom r ⊆ {geometry, geocoder} ∨ debug > 0
2052 └────────────────────────────────────────────────────────────────
2053  
2054 usable : ℙ Result
2055 usable = { r : Result | r.geometry.location.lat ≠ ⊥
2056 ∧ r.geometry.location.lng ≠ ⊥ }
2057  
2058 clean : Text → Text
2059 -- runs of white space become one space; HTML entities are decoded
2060  
2061 isPlace : (Text ∪ Reference) → 𝔹
2062 -- Geo::Location::Predicate::_valid_location when installed;
2063 -- otherwise true for every non-empty Text and false for a Reference
2064  
2065 =head2 new
2066  
2067 ┌─ New ──────────────────────────────────────────────────────────
2068 │ GeoCoderList′
2069 │ args? : Key ⇸ Value
2070 ├────────────────────────────────────────────────────────────────
2071 │ geocoders′ = args?(geocoders) if geocoders ∈ dom args?, else ⟨⟩
2072 │ L1′ = ∅
2073 │ log′ = ⟨⟩
2074 │ L2′ = args?(cache) if cache ∈ dom args?, else ∅
2075 │ hit′ = 1 month ∧ part′ = 1 day ∧ miss′ = 1 week -- unless given
2076 └────────────────────────────────────────────────────────────────
2077  
2078 ┌─ Clone ────────────────────────────────────────────────────────
2079 │ GeoCoderList ; GeoCoderList′
2080 │ args? : Key ⇸ Value
2081 ├────────────────────────────────────────────────────────────────
2082 │ geocoders′ = geocoders -- equal values, distinct copies
2083 │ L1′ = L1 ∧ L2′ = L2 -- the same stores, shared
2084 │ log′ = ⟨⟩
2085 └────────────────────────────────────────────────────────────────
2086  
2087 =head2 push
2088  
2089 ┌─ Push ─────────────────────────────────────────────────────────
2090 │ ΔGeoCoderList
2091 │ g? : Entry
2092 ├────────────────────────────────────────────────────────────────
2093 │ g? ≠ ⊥
2094 │ geocoders′ = geocoders ⁀ ⟨g?⟩
2095 │ L1′ = L1 ∧ L2′ = L2 ∧ log′ = log
2096 └────────────────────────────────────────────────────────────────
2097  
2098 PushUndef ≙ [ ΞGeoCoderList ; g? : Entry | g? = ⊥ ] ⇒ croak
2099  
2100 =head2 geocode
2101  
2102 asks : Entry × Text ⇸ 𝔹
2103 asks(plain g, t) = true
2104 asks(routed(g, M, n), t) = t ∈ M ∧ n > 0
2105  
2106 spend : Entry × Text → Entry
2107 spend(routed(g, M, n), t) = routed(g, M, n − 1) if t ∈ M ∧ n > 0
2108 spend(e, t) = e otherwise
2109  
2110 ┌─ Geocode ──────────────────────────────────────────────────────
2111 │ ΔGeoCoderList
2112 │ loc? : Text ∪ Reference
2113 │ result! : Result ∪ {⊥}
2114 ├────────────────────────────────────────────────────────────────
2115 │ let t == clean(loc?) •
2116 │ ¬ isPlace(t) ⇒ croak
2117 │
2118 │ t ∈ dom L1 ∧ L1(t) ∈ Result
2119 │ ⇒ result! = L1(t) ⊕ {geocoder ↦ cache}
2120 │ ∧ geocoders′ = geocoders ∧ L1′ = L1
2121 │
2122 │ t ∈ dom L1 ∧ L1(t) = notFound
2123 │ ⇒ result! = ⊥ ∧ geocoders′ = geocoders ∧ L1′ = L1
2124 │
2125 │ t ∉ dom L1
2126 │ ⇒ (∃ i : dom geocoders •
2127 │ asks(geocoders i, t)
2128 │ ∧ (∀ j : 1 ‥ i − 1 • ¬ asks(geocoders j, t)
2129 │ ∨ answer(geocoders j, t) ∉ usable)
2130 │ ∧ answer(geocoders i, t) ∈ usable
2131 │ ∧ result! = answer(geocoders i, t)
2132 │ ∧ L1′ = L1 ⊕ {t ↦ result!}
2133 │ ∧ L2′ = L2 ⊕ {t ↦ result! ↾ {geometry, geocoder}})
2134 │ ∨ (result! = ⊥ ∧ L1′ = L1 ⊕ {t ↦ notFound} ∧ L2′ = L2)
2135 │
2136 │ geocoders′ = ⟨ e : geocoders • spend(e, t) ⟩ -- for those asked
2137 │ log′ = log ⁀ ⟨ one entry per geocoder asked, or one for the cache ⟩
2138 └────────────────────────────────────────────────────────────────
2139  
2140 =head2 ua
2141  
2142 ┌─ UA ───────────────────────────────────────────────────────────
2143 │ ΞGeoCoderList
2144 │ ua? : UserAgent ∪ {⊥}
2145 │ ua! : UserAgent ∪ {⊥}
2146 ├────────────────────────────────────────────────────────────────
2147 │ ua? = ⊥ ⇒ ua! = ⊥
2148 │ ua? ≠ ⊥ ⇒ ua! = ua?
2149 │ ∧ (∀ e : ran geocoders • geocoderOf(e) ≠ ⊥ ∨ croak)
2150 │ ∧ (∀ e : ran geocoders •
2151 │ geocoderOf(e).ua′ = clone(ua?) if ua? can clone and agent
2152 │ geocoderOf(e).ua′ = ua? otherwise)
2153 └────────────────────────────────────────────────────────────────
2154  
2155 =head2 reverse_geocode
2156  
2157 LatLng == { s : Text | s ∈ ⟦ ^W*[-+]?D W*,W*[-+]?D W*$ ⟧ }
2158 -- D is a decimal number written in the ASCII digits 0-9;
2159 -- W is a space or a tab
2160  
2161 ┌─ ReverseGeocode ───────────────────────────────────────────────
2162 │ ΔGeoCoderList
2163 │ latlng? : Text
2164 │ address! : Text ∪ {⊥}
2165 ├────────────────────────────────────────────────────────────────
2166 │ latlng? ∉ LatLng ⇒ croak
2167 │
2168 │ latlng? ∈ dom L1 ⇒ address! = first(L1(latlng?)) ∧ L1′ = L1
2169 │
2170 │ latlng? ∉ dom L1
2171 │ ⇒ (∃ i : dom geocoders •
2172 │ limitOf(geocoders i) > 0
2173 │ ∧ addresses(geocoders i, latlng?) ≠ ⟨⟩
2174 │ ∧ address! = head addresses(geocoders i, latlng?)
2175 │ ∧ L1′ = L1 ⊕ {latlng? ↦ address!})
2176 │ ∨ (address! = ⊥ ∧ L1′ = L1)
2177 └────────────────────────────────────────────────────────────────
2178  
2179 =head2 log
2180  
2181 ┌─ Log ──────────────────────────────────────────────────────────
2182 │ ΞGeoCoderList
2183 │ entries! : seq LogEntry
2184 ├────────────────────────────────────────────────────────────────
2185 │ entries! = log
2186 └────────────────────────────────────────────────────────────────
2187  
2188 =head2 flush
2189  
2190 ┌─ Flush ────────────────────────────────────────────────────────
2191 │ ΔGeoCoderList
2192 │ self! : GeoCoderList
2193 ├────────────────────────────────────────────────────────────────
2194 │ log′ = ⟨⟩
2195 │ geocoders′ = geocoders ∧ L1′ = L1 ∧ L2′ = L2
2196 │ self! = θGeoCoderList′
2197 └────────────────────────────────────────────────────────────────
2198  
2199 =head1 STATE DIAGRAM
2200  
2201 An object has three parts that change over time: its chain of geocoders,
2202 its cache (one state for each place name), and its log. Each part is
2203 shown on its own below.
2204  
2205 =head2 The object and its chain
2206  
2207 +-------------+ push($g) +--------------+ push($g)
2208 | EMPTY |----------------->| READY |<-----------+
2209 | no geocoder | adds $g to the | 1+ geocoders |------------+
2210 +-------------+ end of chain +--------------+ adds $g to the end
2211 | |
2212 | geocode($t) | new() on the object
2213 | reverse_geocode($p) | clone: copies the chain and
2214 v | limits, shares L1 and L2,
2215 returns undef / () | empties the log
2216 nothing is asked, but a v
2217 geocode() miss is still +--------------+
2218 remembered in L1 | READY (clone)|
2219 +--------------+
2220  
2221 =head2 The cache, for one place name $t
2222  
2223 +-----------+ geocode($t): a geocoder gives a usable answer
2224 | |----------------------------------------------+
2225 | UNKNOWN | - answer stored in L1 |
2226 | not in L1 | - copy with only geometry stored in L2, |
2227 | | kept for cache_hit_duration (1 month) |
2228 +-----------+ - log gets one entry per geocoder asked |
2229 | ^ v
2230 | | +-----------+
2231 | | L2 entry expires, and a new object | FOUND |<--+
2232 | | is used (L1 dies with its object) | L1 holds | | geocode($t):
2233 | +---------------------------------------------| an answer |---+ no geocoder
2234 | +-----------+ asked; a copy
2235 | geocode($t): no geocoder gives a usable answer returned with
2236 | - L1 stores "not found"; L2 is not written geocoder='cache';
2237 | - log gets one entry per geocoder asked log gets one
2238 v cache entry
2239 +-----------+
2240 | NOT FOUND |<--+ geocode($t): nothing asked, undef / () returned,
2241 | in L1 |---+ nothing logged
2242 +-----------+
2243 |
2244 +-- leaves this state only when the object is destroyed;
2245 flush() and clones do not leave it
2246  
2247 Any state: geocode($t) with a reference, digits (when
2248 Geo::Location::Predicate is installed) or entity-encoded digits
2249 --> croaks; the state does not change.
2250  
2251 =head2 The limit of one geocoder pushed with limit => N
2252  
2253 +--------------+ geocode($t), $t matches regex +--------------+
2254 | ACTIVE |-------------------------------->| ACTIVE |
2255 | limit = n | geocoder asked; limit = n - 1 | limit = n-1 |
2256 +--------------+ +--------------+
2257 | ^ |
2258 | | geocode($t), $t does not match regex: | ... when the
2259 | | geocoder not asked, limit unchanged | limit reaches 0
2260 +------+ v
2261 +--------------+
2262 | EXHAUSTED |<--+
2263 | limit <= 0 |---+
2264 +--------------+ geocode() and
2265 reverse_geocode():
2266 skipped, never asked
2267  
2268 =head2 The log
2269  
2270 +-----------+ geocode() or reverse_geocode() +-------------+
2271 | EMPTY |---------------------------------->| HAS |<--+
2272 | log = [] | appends one entry per geocoder | ENTRIES |---+ geocode() /
2273 +-----------+ asked, or one for a cache hit +-------------+ reverse_geocode():
2274 ^ | appends entries
2275 | flush(): log = [], returns $self |
2276 +-------------------------------------------------+
2277 ^
2278 | new() and clone: start EMPTY
2279  
2280 =head1 LICENSE AND COPYRIGHT
2281  
2282 Copyright 2016-2026 Nigel Horne.
2283  
2284 Usage is subject to the GPL2 licence terms.
2285 If you use it,
2286 please let me know.
2287  
2288 =cut
2289  
2290 25 1;
↑ Summary