blib/lib/Database/BI/Model/Boundary.pm untested

filter: Statementstmt 0.0% 0 / 291 Branchbran 0.0% 0 / 136 Conditioncond 0.0% 0 / 215 MC/DCmcdc 0.0% 0 / 113 Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 817 CC 69 SCAR 39.8
CC
69
Cov
0%
outlines
210.0
_ask
110.0
_known
56.0
CRAP 53.5
1 package Database::BI::Model::Boundary;
2  
3 # The outline of the area each map marker is in: its county, for now.
4 #
5 # A map can draw the boundary of the county around each of its markers. The
6 # outlines come from OpenStreetMap's Nominatim, through its reverse lookup:
7 # given a point and a zoom, it names the administrative area there and, with
8 # polygon_geojson, sends its shape. Asking by point rather than by name means
9 # the same code serves coordinate columns and geocoded places, in any country,
10 # and needs no state or country column to tell one Richmond from another.
11 #
12 # Nominatim allows one request a second, so this module asks as little as it
13 # can:
14 #
15 # 1. Each point is rounded to 3 decimal places (about 110 m), which is also
16 # all of it that leaves this machine, and remembered with the outline it
17 # fell in (or with none, for a point at sea).
18 # 2. A point not remembered is first tested against the outlines already
19 # known, through an index of their bounding boxes, so ten thousand shops
20 # in one county cost one request, not ten thousand.
21 # 3. Only then is Nominatim asked, at most online_max times a call, and a
22 # point it does not answer is left pending, not remembered as nowhere.
23 #
24 # The outlines are simplified by Nominatim (polygon_threshold), about 7 KB each,
25 # because they are written into the page.
26 #
27 # The level is a "county": the division of a country below its states. Which
28 # of Nominatim's place ranks that is depends on the country, so %LEVELS gives a
29 # rank for most (12: a US county, an English county, a German Landkreis, a
30 # French departement, a Pakistani district) and the countries that differ (10:
31 # an Indian or Bangladeshi district, a Chinese prefecture, a Spanish province;
32 # 8: a Kenyan county), and config map_bounds_ranks can add more. Each reply
33 # names its country, so a point is asked at the zoom of the last country seen,
34 # and again at its own country's zoom when that guess was wrong: one extra
35 # request at each border a map crosses. The rank an outline was accepted at is
36 # kept with it, so a changed table asks again rather than draw the old level.
37  
38 use strict;
39 use warnings;
40  
41 use Carp qw(croak);
42 use JSON::PP ();
43 use Params::Get ();
44 use Params::Validate::Strict qw(validate_strict);
45 use Readonly;
46 use Scalar::Util qw(blessed);
47 use URI ();
48  
49 our $VERSION = '0.023.0';
50  
51 # The place rank an answer must have at each level: rank for a country not
52 # listed, countries for those that differ, by ISO 3166-1 alpha-2 code. Checked
53 # against Nominatim's reverse lookup in November 2026: rank 12
54 # at zoom 8 is the county level in the US, UK, Ireland, Germany, France, Italy,
55 # Pakistan, Mexico, Nigeria, South Africa, Russia, Indonesia and Canada.
56 # Australia, Brazil and Japan have nothing between their states and their
57 # towns, so a point there is nowhere.
58 Readonly my %LEVELS => (
59 county => {
60 rank => 12,
61 countries => {
62 bd => 10, # district (zila); 12 is an upazila
63 cn => 10, # prefecture-level city; 12 is a district
64 es => 10, # province; Spain has no rank 12
65 in => 10, # district; 12 is a sub-district (tehsil, taluk)
66 ke => 8, # county; 12 is a sub-county
67 },
68 # What the division is called where it is not a county, as a word a
69 # caller can name it by to its readers (name_for).
70 name => 'county',
71 names => {
72 bd => 'district', cn => 'prefecture', de => 'district', es => 'province',
73 fr => 'department', in => 'district', it => 'province',
74 },
75 },
76 );
77  
78 # The reverse zoom that asks for each rank. A zoom names the most detailed
79 # rank it may return, so a point with no area at that rank comes back as
80 # something larger (a state), which the rank check turns away rather than
81 # drawing.
82 Readonly my %ZOOM_FOR_RANK => (8 => 5, 10 => 6, 12 => 8);
83  
84 Readonly my $REVERSE_URL => 'https://nominatim.openstreetmap.org/reverse';
85 # How far Nominatim may move an outline's edge to simplify it, in degrees:
86 # about 100 m. Each outline is simplified alone, so neighbours' shared borders
87 # differ by up to this, which shows as gaps and overlaps now that each is drawn
88 # on its own side of the border; 0.005 (500 m, 2 KB a county) was 7 pixels out
89 # at the zoom a county fills the map, this (7 KB) under 2. Kept as text: it is
90 # stored with each outline and compared, to ask again for one kept coarser.
91 Readonly my $THRESHOLD => '0.001';
92 Readonly my $DECIMALS => 3; # of a point, in its key and in what is sent
93 Readonly my $DEFAULT_MAX => 20; # Nominatim requests in one call, as map_geocode_online_max
94 Readonly my $CACHE_DIR => 'boundary-cache'; # under model_dir, for file_cache()
95 Readonly my $CACHE_NAMESPACE => __PACKAGE__;
96 Readonly my $CACHE_MAX_SIZE => 8 * 1024 * 1024; # bytes, for the process-wide default
97  
98 my $json = JSON::PP->new->canonical->utf8;
99  
100 =head1 NAME
101  
102 Database::BI::Model::Boundary - The county outline around each map marker
103  
104 =head1 VERSION
105  
106 0.023.0
107  
108 =head1 SYNOPSIS
109  
110 use Database::BI::Model::Boundary;
111  
112 my $boundary = Database::BI::Model::Boundary->new(
113 cache => Database::BI::Model::Boundary->file_cache('.bi'),
114 online => 1,
115 );
116  
117 my $result = $boundary->outlines([ [ 39.09, -77.64 ], [ 38.85, -77.31 ] ]);
118 $map->add_geojson(
119 { type => 'FeatureCollection', features => $result->{features} },
120 name => 'County boundaries',
121 );
122  
123 # A point the map page listed as pending, looked up on its own
124 my $answer = $boundary->lookup_point($result->{pending}[0]);
125  
126 =head1 DESCRIPTION
127  
128 Finds the county each point is in and returns its outline as a GeoJSON
129 Feature, for L<HTML::OSM>'s C<add_geojson>. The outlines come from
130 OpenStreetMap's Nominatim reverse lookup, through the same throttled user agent
131 as the geocoder (L<Database::BI::Model::Geocode/nominatim_ua>), so the two
132 together never ask more than once a second.
133  
134 Only the point is sent, rounded to three decimal places (about 110 metres).
135 Every answer is cached: a point with the outline it is in, and the outline
136 itself. A point inside an outline already known is matched here, without a
137 request, so many points in one county cost one lookup.
138  
139 A county here is the division of a country below its states, whose place rank
140 in Nominatim depends on the country: 12 (a US county or independent city, an
141 English county, a German Landkreis, a French departement) unless the country is
142 listed otherwise: 10 for India, Bangladesh, China and Spain (district,
143 prefecture, province), 8 for Kenya. C<ranks> adds or changes countries.
144 Anything else Nominatim answers is taken as "no county here" and remembered as
145 such. A country with nothing at its rank (Australia, Brazil, Japan) gets no
146 outlines.
147  
148 Each reply names the point's country, so a point is asked at the zoom of the
149 last country seen, and asked again when its own country wants another rank.
150 An outline is kept with the rank it was accepted at; when C<ranks> changes, the
151 points it covered are asked again.
152  
153 =head1 METHODS
154  
155 =head2 new
156  
157 my $boundary = Database::BI::Model::Boundary->new(%args);
158  
159 =head3 API SPECIFICATION
160  
161 =head4 INPUT
162  
163 cache : object with get() and set() (CHI) optional; default one
164 CHI Memory cache for the process
165 online : boolean optional, default 0: may Nominatim be asked
166 online_max : integer optional, default 20: requests in one outlines() call
167 level : string optional, default 'county'; the only level so far
168 ranks : hashref optional: { country code => place rank }, over the
169 level's own list; codes are two letters (any case), ranks
170 8, 10 or 12
171 ua : object with get() optional: the user agent to ask with
172 (tests); default Geocode::nominatim_ua()
173  
174 =head4 OUTPUT
175  
176 A Database::BI::Model::Boundary object. Croaks on an unknown level, a cache
177 without get and set, or ranks that are not a hash of two-letter codes to 8, 10
178 or 12.
179  
180 =cut
181  
182 sub new {
183 my $class = shift;
184 my $raw = Params::Get::get_params(undef, \@_) // {};
185  
186 my $args = validate_strict(
187 schema => {
188 cache => { type => 'object', optional => 1, default => undef },
189 online => { type => 'boolean', optional => 1, default => 0 },
190 online_max => { type => 'integer', optional => 1, default => $DEFAULT_MAX, min => 0 },
191 level => { type => 'string', optional => 1, default => 'county' },
192 ua => { type => 'object', optional => 1, default => undef, can => 'get' },
193 ranks => { type => 'hashref', optional => 1, default => undef },
194 },
195 input => $raw,
196 );
197  
198 my $level = $LEVELS{ $args->{level} }
199 or croak "Unknown boundary level '$args->{level}'";
200 croak 'The boundary cache needs get() and set()'
201 if defined($args->{cache}) && !($args->{cache}->can('get') && $args->{cache}->can('set'));
202  
203 return bless {
204 %{$args},
205 ranks => { %{ $level->{countries} }, %{ $class->check_ranks($args->{ranks} // {}) } },
206 cache => $args->{cache} // _default_cache(),
207 }, $class;
208 }
209  
210 =head2 check_ranks
211  
212 my $ranks = Database::BI::Model::Boundary->check_ranks({ LK => 10 }); # { lk => 10 }
213  
214 =head3 API SPECIFICATION
215  
216 =head4 INPUT
217  
218 ranks : hashref of { country code => place rank }
219  
220 =head4 OUTPUT
221  
222 A new hashref with the codes in lower case and the ranks as numbers. Croaks
223 on a value that is not a hashref, a key that is not a two-letter code, or a
224 rank that is not 8, 10 or 12, naming the entry. Used by C<new> and by the
225 application's startup check of C<map_bounds_ranks>.
226  
227 =cut
228  
229 sub check_ranks {
230 my (undef, $ranks) = @_;
231 croak 'Boundary ranks must be a hash of country codes to place ranks'
232 unless ref($ranks) eq 'HASH';
233 my %checked;
234 for my $code (sort keys %{$ranks}) {
235 my $rank = $ranks->{$code};
236 croak "'$code' is not a two-letter country code" unless $code =~ /\A[A-Za-z]{2}\z/;
237 croak "the rank for '$code' must be one of " . join(', ', sort { $a <=> $b } keys %ZOOM_FOR_RANK)
238 unless defined($rank) && !ref($rank) && $rank =~ /\A\d+\z/ && $ZOOM_FOR_RANK{$rank};
239 croak "'$code' is given twice" if exists $checked{ lc $code };
240 $checked{ lc $code } = $rank + 0;
241 }
242 return \%checked;
243 }
244  
245 =head2 rank_for
246  
247 my $rank = $boundary->rank_for('in'); # 10
248  
249 =head3 API SPECIFICATION
250  
251 =head4 INPUT
252  
253 country : string, an ISO 3166-1 alpha-2 code in any case; undef or ''
254 for a point in no country (the sea)
255  
256 =head4 OUTPUT
257  
258 The place rank an outline in that country must have at this object's level:
259 the country's own, from C<ranks> or the built-in list, else the level's.
260  
261 =cut
262  
263 sub rank_for {
264 my ($self, $country) = @_;
265 my $rank = (defined($country) && !ref($country) && length($country))
266 ? $self->{ranks}{ lc $country } : undef;
267 return $rank // $LEVELS{ $self->{level} }{rank};
268 }
269  
270 =head2 name_for
271  
272 my $word = $boundary->name_for('in'); # 'district'
273  
274 What this object's level is called in a country, so a caller can say
275 "district" on a map of India rather than "county".
276  
277 =head3 API SPECIFICATION
278  
279 =head4 INPUT
280  
281 country : string, an ISO 3166-1 alpha-2 code in any case; undef or ''
282 for a point in no country
283  
284 =head4 OUTPUT
285  
286 One lower-case English word: C<county>, C<district>, C<province>,
287 C<prefecture> or C<department>. A country not listed gets the level's own
288 name, C<county>. It is a word to look a translation up by, not text to show.
289  
290 =cut
291  
292 sub name_for {
293 my ($self, $country) = @_;
294 my $level = $LEVELS{ ref($self) ? $self->{level} : 'county' };
295 my $name = (defined($country) && !ref($country) && length($country))
296 ? $level->{names}{ lc $country } : undef;
297 return $name // $level->{name};
298 }
299  
300 =head2 levels
301  
302 my @levels = Database::BI::Model::Boundary->levels; # ('county')
303  
304 =head3 API SPECIFICATION
305  
306 =head4 INPUT
307  
308 None.
309  
310 =head4 OUTPUT
311  
312 The names of the levels new() takes, sorted.
313  
314 =cut
315  
316 sub levels {
317 return sort keys %LEVELS;
318 }
319  
320 =head2 point_key
321  
322 my $key = Database::BI::Model::Boundary->point_key(39.0901, -77.6402); # '39.090,-77.640'
323  
324 =head3 API SPECIFICATION
325  
326 =head4 INPUT
327  
328 lat : number -90 .. 90
329 lon : number -180 .. 180
330  
331 =head4 OUTPUT
332  
333 The point rounded to three decimal places, as C<"lat,lon">: what the cache is
334 keyed by and all of the point that is sent. Undef for a point out of range.
335  
336 =cut
337  
338 sub point_key {
339 my (undef, $lat, $lon) = @_;
340  
341 return unless defined($lat) && defined($lon)
342 && $lat =~ /\A-?\d+(?:\.\d+)?\z/ && $lon =~ /\A-?\d+(?:\.\d+)?\z/
343 && abs($lat) <= 90 && abs($lon) <= 180;
344  
345 my @parts = map {
346 my $text = sprintf("%.${DECIMALS}f", $_);
347 $text =~ s/\A-(?=0\.0+\z)//; # no "-0.000", so a point has one key
348 $text;
349 } ($lat, $lon);
350 return join(',', @parts);
351 }
352  
353 =head2 outlines
354  
355 my $result = $boundary->outlines(\@points, lookup => 1);
356  
357 =head3 API SPECIFICATION
358  
359 =head4 INPUT
360  
361 points : arrayref of [lat, lon]
362 lookup : boolean, default 1. 0 asks Nominatim nothing: the points not
363 known yet come back in pending, for the caller to look up one at
364 a time (lookup_point)
365  
366 =head4 OUTPUT
367  
368 {
369 features => [ GeoJSON Feature, ... ] one per outline, in the order
370 their first point came; properties { name, osm, called }
371 (called: what the division is called there, as name_for)
372 pending => [ point_key, ... ] points not known, not asked
373 inside => { point_key => osm, ... } the outline each point drawn is in,
374 by the osm of its Feature (to total what is in each)
375 counts => { points, drawn, attempted, nowhere }
376 offline => 0|1 points were left because Nominatim may not be asked
377 failed => 0|1 Nominatim did not answer; the rest were left
378 }
379  
380 A point out of range is ignored. A Feature's name is the place's name as
381 OpenStreetMap has it: text, not HTML.
382  
383 =cut
384  
385 sub outlines {
386 my ($self, $points, @rest) = @_;
387 croak 'outlines() needs an arrayref of [lat, lon]' unless ref($points) eq 'ARRAY';
388 my %opt = @rest;
389 my $lookup = exists($opt{lookup}) ? $opt{lookup} : 1;
390  
391 local ($@, $!);
392  
393 my (@keys, %seen);
394 for my $point (@{$points}) {
395 next unless ref($point) eq 'ARRAY';
396 my $key = $self->point_key(@{$point}[0, 1]);
397 push @keys, $key if defined($key) && !$seen{$key}++;
398 }
399  
400 my %counts = (points => scalar(@keys), drawn => 0, attempted => 0, nowhere => 0);
401 my (@order, %used, %inside, @pending, $failed, $offline);
402 my $index = $self->_index;
403  
404 for my $key (@keys) {
405 my ($osm, $status) = $self->_known($key, $index);
406 if (!defined($status) && $lookup) {
407 if (!$self->_can_ask) {
408 $offline = 1;
409 } elsif (!$failed && $counts{attempted} < $self->{online_max}) {
410 $counts{attempted}++;
411 ($osm, $status) = $self->_ask($key, $index);
412 $failed = 1 if $status eq 'failed';
413 }
414 }
415 if (!defined($status) || $status eq 'failed') {
416 push @pending, $key;
417 next;
418 }
419 if ($status eq 'nowhere') {
420 $counts{nowhere}++;
421 next;
422 }
423 push @order, $osm unless $used{$osm}++;
424 $inside{$key} = $osm;
425 }
426  
427 my @features;
428 for my $osm (@order) {
429 my $outline = $self->_get("outline:$osm") or next;
430 push @features, {
431 type => 'Feature',
432 properties => { name => $outline->{name}, osm => $osm,
433 called => $self->name_for($outline->{country}) },
434 geometry => $outline->{geometry},
435 };
436 }
437 $counts{drawn} = scalar @features;
438 my %drawn = map { $_->{properties}{osm} => 1 } @features;
439 delete @inside{ grep { !$drawn{ $inside{$_} } } keys %inside };
440  
441 return {
442 features => \@features,
443 pending => \@pending,
444 inside => \%inside,
445 counts => \%counts,
446 offline => $offline ? 1 : 0,
447 failed => $failed ? 1 : 0,
448 };
449 }
450  
451 =head2 lookup_point
452  
453 my $answer = $boundary->lookup_point('39.090,-77.640');
454  
455 =head3 API SPECIFICATION
456  
457 =head4 INPUT
458  
459 key : string, a point_key
460  
461 =head4 OUTPUT
462  
463 { status => 'found' | 'nowhere' | 'held', name => string|undef, asked => 0|1 }
464  
465 'found' and 'nowhere' are remembered. 'held' is a point that could not be
466 settled now - Nominatim did not answer, or may not be asked - and is asked
467 again next time. asked says whether Nominatim was asked. Croaks on a key
468 that is not a point_key.
469  
470 =cut
471  
472 sub lookup_point {
473 my ($self, $key) = @_;
474  
475 croak 'lookup_point() needs a point key such as 39.090,-77.640'
476 unless defined($key) && !ref($key)
477 && $key =~ /\A(-?\d{1,2}\.\d{$DECIMALS}),(-?\d{1,3}\.\d{$DECIMALS})\z/
478 && defined($self->point_key($1, $2)) && $self->point_key($1, $2) eq $key;
479  
480 local ($@, $!);
481  
482 my $index = $self->_index;
483 my ($osm, $status) = $self->_known($key, $index);
484 my $asked = 0;
485 if (!defined($status) && $self->_can_ask) {
486 $asked = 1;
487 ($osm, $status) = $self->_ask($key, $index);
488 }
489  
490 return { status => 'held', name => undef, asked => $asked }
491 if !defined($status) || $status eq 'failed';
492 return { status => 'nowhere', name => undef, asked => $asked } if $status eq 'nowhere';
493  
494 my $outline = $self->_get("outline:$osm");
495 return { status => 'found', name => ($outline ? $outline->{name} : undef), asked => $asked };
496 }
497  
498 =head2 file_cache
499  
500 my $cache = Database::BI::Model::Boundary->file_cache($model_dir);
501  
502 =head3 API SPECIFICATION
503  
504 =head4 INPUT
505  
506 dir : string, an existing directory (model_dir)
507  
508 =head4 OUTPUT
509  
510 A CHI File cache under C<< <dir>/boundary-cache >>, with a copy of what it
511 reads in memory for as long as the cache object lives. Croaks when dir is not a directory.
512  
513 =cut
514  
515 sub file_cache {
516 my (undef, $dir) = @_;
517  
518 croak 'The boundary cache needs a directory, not ' . (defined($dir) ? $dir : 'undef')
519 unless defined($dir) && !ref($dir) && -d $dir;
520  
521 require CHI;
522 require File::Spec;
523 return CHI->new(
524 driver => 'File',
525 root_dir => File::Spec->catdir($dir, $CACHE_DIR),
526 namespace => $CACHE_NAMESPACE,
527 # A copy in memory for this object, which a request makes afresh: it
528 # saves reading the index and outlines again within the request. Not
529 # global, which would share it with every cache of this namespace in
530 # the process, whatever its folder, and keep a worker from seeing
531 # what another has added since.
532 l1_cache => { driver => 'RawMemory', global => 0, max_size => $CACHE_MAX_SIZE },
533 );
534 }
535  
536 # ---------------------------------------------------------------------------
537 # Private
538 # ---------------------------------------------------------------------------
539  
540 my $default_cache;
541  
542 sub _default_cache {
543 require CHI;
544 $default_cache //= CHI->new(
545 driver => 'Memory',
546 global => 1,
547 namespace => $CACHE_NAMESPACE,
548 max_size => $CACHE_MAX_SIZE,
549 );
550 return $default_cache;
551 }
552  
553 # _get($key) / _set($key, $value): the cache, under this level's prefix for a
554 # point and the plain key for an outline (an OSM relation is one outline at any
555 # level). A cache that fails reads as empty and writes as nothing: the page
556 # still draws, and asks again next time.
557 sub _get {
558 my ($self, $key) = @_;
559 my $value = eval { $self->{cache}->get($key) };
560 return $value;
561 }
562  
563 sub _set {
564 my ($self, $key, $value) = @_;
565 return eval { $self->{cache}->set($key, $value, 'never'); 1 };
566 }
567  
568 sub _point_cache_key {
569 my ($self, $key) = @_;
570 return "point:$self->{level}:$key";
571 }
572  
573 # _index() -> arrayref of [osm, south, west, north, east]
574 #
575 # The bounding box of every outline this level has found, so a point can be
576 # tested against the few that could hold it. Two processes adding at once can
577 # lose one's entry; that costs a request later, not a wrong answer.
578 sub _index {
579 my $self = shift;
580 my $index = $self->_get("index:$self->{level}");
581 return ref($index) eq 'ARRAY' ? [ @{$index} ] : [];
582 }
583  
584 # _known($key, \@index) -> ($osm, $status) or ()
585 #
586 # What is known of a point without asking: remembered with an outline or with
587 # none, or inside an outline the index holds (which is then remembered).
588 sub _known {
589 my ($self, $key, $index) = @_;
590  
591 my $remembered = $self->_get($self->_point_cache_key($key));
592 if (ref($remembered) eq 'HASH') {
593 # Nowhere, at the rank its country wanted then.
594 return (undef, 'nowhere')
595 if ($remembered->{rank} // -1) == $self->rank_for($remembered->{country});
596 } elsif (defined($remembered) && length($remembered)) {
597 return ($remembered, 'found') if $self->_current($self->_get("outline:$remembered"));
598 # The outline has gone from the cache, or its country's rank changed.
599 }
600 # '' is nowhere from before ranks were kept: ask again.
601  
602 my ($lat, $lon) = split /,/, $key;
603 for my $entry (@{$index}) {
604 my ($osm, $south, $west, $north, $east) = @{$entry};
605 next if $lat < $south || $lat > $north || $lon < $west || $lon > $east;
606 my $outline = $self->_get("outline:$osm");
607 next unless $self->_current($outline) && _contains($outline->{geometry}, $lat, $lon);
608 $self->_set($self->_point_cache_key($key), $osm);
609 return ($osm, 'found');
610 }
611  
612 return;
613 }
614  
615 # _current($outline) -> 1 when an outline was accepted at the rank its country
616 # wants now, and simplified as outlines are now. One kept before ranks were
617 # (no rank), or at another level of detail, is not.
618 sub _current {
619 my ($self, $outline) = @_;
620 return 0 unless ref($outline) eq 'HASH' && defined($outline->{rank});
621 return 0 unless ($outline->{detail} // '') eq $THRESHOLD;
622 return $outline->{rank} == $self->rank_for($outline->{country}) ? 1 : 0;
623 }
624  
625 # _last_country() / _last_country($code): the country of the last reply at
626 # this level, whose rank the next point is asked at first. Kept in the cache,
627 # so the first point of a later map is not asked twice.
628 sub _last_country {
629 my ($self, @set) = @_;
630 my $key = "country:$self->{level}";
631 if (@set) {
632 $self->{last_country} = $set[0];
633 $self->_set($key, $set[0]) unless ($self->_get($key) // '') eq $set[0];
634 return $set[0];
635 }
636 return $self->{last_country} //= $self->_get($key) // '';
637 }
638  
639 sub _can_ask {
640 my $self = shift;
641 return 0 unless $self->{online};
642 return 1 if $self->{ua};
643 require Database::BI::Model::Geocode;
644 return Database::BI::Model::Geocode::nominatim_ua() ? 1 : 0;
645 }
646  
647 # _ask($key, \@index) -> ($osm, 'found') | (undef, 'nowhere') | (undef, 'failed')
648 #
649 # A reverse lookup, at the zoom of the rank the last country seen wants; when
650 # the reply's country wants another, a second at that rank's zoom. A found
651 # outline is remembered with its country and rank, added to the index (and to
652 # @$index, so the caller's later points are tested against it), and the point
653 # remembered with it. An answer that is not an outline at the country's rank
654 # is remembered as nowhere, with that country and rank. A failure is
655 # remembered as nothing.
656 sub _ask {
657 my ($self, $key, $index) = @_;
658 my ($lat, $lon) = split /,/, $key;
659  
660 my $rank = $self->rank_for($self->_last_country);
661 my $reply = $self->_reverse($lat, $lon, $rank) or return (undef, 'failed');
662  
663 my $country = ref($reply->{address}) eq 'HASH' ? $reply->{address}{country_code} : undef;
664 $country = (defined($country) && !ref($country) && $country =~ /\A[A-Za-z]{2}\z/) ? lc($country) : '';
665 if (length $country) {
666 $self->_last_country($country);
667 my $wanted = $self->rank_for($country);
668 if ($wanted != $rank) {
669 $rank = $wanted;
670 $reply = $self->_reverse($lat, $lon, $rank) or return (undef, 'failed');
671 }
672 }
673  
674 my $geometry = $reply->{geojson};
675 my $is_outline = ($reply->{category} // '') eq 'boundary'
676 && ($reply->{type} // '') eq 'administrative'
677 && ($reply->{osm_type} // '') eq 'relation'
678 && defined($reply->{osm_id}) && $reply->{osm_id} =~ /\A\d+\z/
679 && ($reply->{place_rank} // -1) == $rank
680 && ref($geometry) eq 'HASH'
681 && ($geometry->{type} // '') =~ /\A(?:Multi)?Polygon\z/
682 && ref($geometry->{coordinates}) eq 'ARRAY';
683  
684 unless ($is_outline) {
685 # "Unable to geocode" (the sea) and an answer at another rank alike.
686 $self->_set($self->_point_cache_key($key), { country => $country, rank => $rank });
687 return (undef, 'nowhere');
688 }
689  
690 my $osm = "R$reply->{osm_id}";
691 my $name = $reply->{name};
692 $name = $reply->{display_name} unless defined($name) && length($name);
693 $self->_set("outline:$osm", {
694 name => $name // $osm,
695 geometry => $geometry,
696 country => $country,
697 rank => $rank,
698 detail => $THRESHOLD,
699 });
700  
701 unless (grep { $_->[0] eq $osm } @{$index}) {
702 my $box = _bounds($geometry);
703 if ($box) {
704 push @{$index}, [ $osm, @{$box} ];
705 my $stored = $self->_index;
706 push @{$stored}, [ $osm, @{$box} ] unless grep { $_->[0] eq $osm } @{$stored};
707 $self->_set("index:$self->{level}", $stored);
708 }
709 }
710 $self->_set($self->_point_cache_key($key), $osm);
711  
712 return ($osm, 'found');
713 }
714  
715 # _reverse($lat, $lon, $rank) -> the decoded reply, or undef when Nominatim
716 # did not answer with JSON.
717 sub _reverse {
718 my ($self, $lat, $lon, $rank) = @_;
719  
720 my $uri = URI->new($REVERSE_URL);
721 $uri->query_form(
722 lat => $lat,
723 lon => $lon,
724 zoom => $ZOOM_FOR_RANK{$rank},
725 format => 'jsonv2',
726 polygon_geojson => 1,
727 polygon_threshold => $THRESHOLD,
728 'accept-language' => 'en',
729 );
730  
731 require Database::BI::Model::Geocode;
732 my $ua = $self->{ua} // Database::BI::Model::Geocode::nominatim_ua();
733 my $res = eval { $ua->get($uri) };
734 return unless blessed($res) && $res->can('is_success') && $res->is_success;
735  
736 my $reply = eval { $json->decode($res->decoded_content // '') };
737 return ref($reply) eq 'HASH' ? $reply : undef;
738 }
739  
740 # _polygons($geometry) -> list of polygons, each an arrayref of rings, each
741 # ring an arrayref of [lon, lat].
742 sub _polygons {
743 my $geometry = shift;
744 return () unless ref($geometry) eq 'HASH' && ref($geometry->{coordinates}) eq 'ARRAY';
745 return ($geometry->{coordinates}) if ($geometry->{type} // '') eq 'Polygon';
746 return @{ $geometry->{coordinates} } if ($geometry->{type} // '') eq 'MultiPolygon';
747 return ();
748 }
749  
750 # _bounds($geometry) -> [south, west, north, east], or undef with no points
751 sub _bounds {
752 my $geometry = shift;
753 my ($south, $west, $north, $east);
754 for my $polygon (_polygons($geometry)) {
755 for my $position (@{ $polygon->[0] // [] }) {
756 my ($lon, $lat) = @{$position};
757 $south = $lat if !defined($south) || $lat < $south;
758 $north = $lat if !defined($north) || $lat > $north;
759 $west = $lon if !defined($west) || $lon < $west;
760 $east = $lon if !defined($east) || $lon > $east;
761 }
762 }
763 return defined($south) ? [ $south, $west, $north, $east ] : undef;
764 }
765  
766 # _contains($geometry, $lat, $lon) -> 1 when the point is inside a polygon's
767 # outer ring and none of its holes (Fairfax County's hole is the City of
768 # Fairfax). Even-odd ray casting, with longitude as x.
769 sub _contains {
770 my ($geometry, $lat, $lon) = @_;
771 for my $polygon (_polygons($geometry)) {
772 my ($outer, @holes) = @{$polygon};
773 next unless _in_ring($outer, $lon, $lat);
774 return 1 unless grep { _in_ring($_, $lon, $lat) } @holes;
775 }
776 return 0;
777 }
778  
779 sub _in_ring {
780 my ($ring, $x, $y) = @_;
781 return 0 unless ref($ring) eq 'ARRAY' && @{$ring} >= 3;
782 my $inside = 0;
783 my ($px, $py) = @{ $ring->[-1] };
784 for my $position (@{$ring}) {
785 my ($qx, $qy) = @{$position};
786 if ((($qy > $y) != ($py > $y))
787 && ($x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx)) {
788 $inside = !$inside;
789 }
790 ($px, $py) = ($qx, $qy);
791 }
792 return $inside ? 1 : 0;
793 }
794  
795 1;
796  
797 __END__