| File: | blib/lib/Database/BI/Model/Boundary.pm |
| Coverage: | 98.0% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package Database::BI::Model::Boundary; | |||||
| 2 | ||||||
| 3 | # The outline of the area each map marker is in: its country, state or | |||||
| 4 | # province, county, city, town or neighbourhood (the level). | |||||
| 5 | # | |||||
| 6 | # A map can draw the boundary of the area around each of its markers. The | |||||
| 7 | # outlines come from OpenStreetMap's Nominatim, through its reverse lookup: | |||||
| 8 | # given a point and a zoom, it names the administrative area there and, with | |||||
| 9 | # polygon_geojson, sends its shape. Asking by point rather than by name means | |||||
| 10 | # the same code serves coordinate columns and geocoded places, in any country, | |||||
| 11 | # and needs no state or country column to tell one Richmond from another. | |||||
| 12 | # | |||||
| 13 | # Nominatim allows one request a second, so this module asks as little as it | |||||
| 14 | # can: | |||||
| 15 | # | |||||
| 16 | # 1. Each point is rounded to 3 decimal places (about 110 m), which is also | |||||
| 17 | # all of it that leaves this machine, and remembered with the outline it | |||||
| 18 | # fell in (or with none, for a point at sea). | |||||
| 19 | # 2. A point not remembered is first tested against the outlines already | |||||
| 20 | # known, through an index of their bounding boxes, so ten thousand shops | |||||
| 21 | # in one county cost one request, not ten thousand. | |||||
| 22 | # 3. Only then is Nominatim asked, at most online_max times a call, and a | |||||
| 23 | # point it does not answer is left pending, not remembered as nowhere. | |||||
| 24 | # | |||||
| 25 | # The outlines are simplified by Nominatim (polygon_threshold), about 7 KB each, | |||||
| 26 | # because they are written into the page. | |||||
| 27 | # | |||||
| 28 | # What Nominatim has at each level differs by country, and was probed in | |||||
| 29 | # November 2026 (the points and what came back are in the comments at %LEVELS). | |||||
| 30 | # A level is therefore a plan: a list of tries, each a reverse zoom and the | |||||
| 31 | # place ranks an answer may have, taken in order until one gives an outline. | |||||
| 32 | # | |||||
| 33 | # country zoom 3, rank 4. | |||||
| 34 | # state zoom 5, rank 8: a US or Indian state, a Canadian province, a | |||||
| 35 | # New Zealand region, England or Scotland. | |||||
| 36 | # county below, one rank a country. | |||||
| 37 | # city zoom 10, ranks 12 to 16, an administrative area or a place | |||||
| 38 | # mapped as an area: Toronto, Manchester, Canterbury (the | |||||
| 39 | # district), Bristol. Where zoom 10 gives only a point (York, | |||||
| 40 | # Pune), zoom 8 at rank 12: the unitary authority or city | |||||
| 41 | # district. A point in no city gets its rank 12 area | |||||
| 42 | # too (a US county): zoom 10 answers with it. New Zealand's cities are its territorial | |||||
| 43 | # authorities, rank 12 at zoom 8 (Hamilton City), or the region | |||||
| 44 | # where that is one (Auckland). | |||||
| 45 | # town zoom 12, ranks 13 to 18: Margate, a Toronto ward. Then zoom | |||||
| 46 | # 14, ranks 19 and 20, administrative areas only: a town | |||||
| 47 | # that is a civil parish (Westgate-on-Sea). | |||||
| 48 | # neighbourhood zoom 14, ranks 17 to 20: a Toronto neighbourhood, an English | |||||
| 49 | # civil parish (Westgate-on-Sea), a suburb mapped as an area | |||||
| 50 | # (Manchester's City Centre). Most suburbs are mapped as a | |||||
| 51 | # point (Cliftonville, Garlinge), and those have no outline. | |||||
| 52 | # | |||||
| 53 | # The larger the area, the more its outline is simplified (the level's detail), | |||||
| 54 | # or a country would be megabytes. An outline is kept under its detail, so one | |||||
| 55 | # relation drawn at two levels (Auckland, a state and a city) is kept twice. | |||||
| 56 | # | |||||
| 57 | # A "county" is the division of a country below its states. Which | |||||
| 58 | # of Nominatim's place ranks that is depends on the country, so %LEVELS gives a | |||||
| 59 | # rank for most (12: a US county, an English county, a German Landkreis, a | |||||
| 60 | # French departement, a Pakistani district) and the countries that differ (10: | |||||
| 61 | # an Indian or Bangladeshi district, a Chinese prefecture, a Spanish province; | |||||
| 62 | # 8: a Kenyan county), and config map_bounds_ranks can add more. Each reply | |||||
| 63 | # names its country, so a point is asked at the zoom of the last country seen, | |||||
| 64 | # and again at its own country's zoom when that guess was wrong: one extra | |||||
| 65 | # request at each border a map crosses. The rank an outline was accepted at is | |||||
| 66 | # kept with it, so a changed table asks again rather than draw the old level. | |||||
| 67 | # The other levels do the same with their plans: a point is asked the first try | |||||
| 68 | # of the last country's plan, and its own country's plan from there. | |||||
| 69 | ||||||
| 70 | 11 11 11 | 173772 9 98 | use strict; | |||
| 71 | 11 11 11 | 12 10 287 | use warnings; | |||
| 72 | ||||||
| 73 | 11 11 11 | 15 9 214 | use Carp qw(croak); | |||
| 74 | 11 11 11 | 33 9 62 | use JSON::PP (); | |||
| 75 | 11 11 11 | 16 14 216 | use List::Util qw(first); | |||
| 76 | 11 11 11 | 201 9424 66 | use Params::Get (); | |||
| 77 | 11 11 11 | 273 5346 159 | use Params::Validate::Strict qw(validate_strict); | |||
| 78 | 11 11 11 | 14 9 129 | use Readonly; | |||
| 79 | 11 11 11 | 16 10 129 | use Scalar::Util qw(blessed); | |||
| 80 | 11 11 11 | 18 6 136 | use Storable qw(dclone); | |||
| 81 | 11 11 11 | 456 4372 14396 | use URI (); | |||
| 82 | ||||||
| 83 | our $VERSION = '0.025.0'; | |||||
| 84 | ||||||
| 85 | # The place rank an answer must have at each level: rank for a country not | |||||
| 86 | # listed, countries for those that differ, by ISO 3166-1 alpha-2 code. Checked | |||||
| 87 | # against Nominatim's reverse lookup in November 2026: rank 12 | |||||
| 88 | # at zoom 8 is the county level in the US, UK, Ireland, Germany, France, Italy, | |||||
| 89 | # Pakistan, Mexico, Nigeria, South Africa, Russia, Indonesia and Canada. | |||||
| 90 | # Australia, Brazil and Japan have nothing between their states and their | |||||
| 91 | # towns, so a point there is nowhere. | |||||
| 92 | # | |||||
| 93 | # The other levels are plans: tries => [ { zoom, ranks => [low, high], places } ], | |||||
| 94 | # with plans => { country => [ tries ] } for a country that differs. places | |||||
| 95 | # lets a try take a place mapped as an area (place=city, town, suburb; a | |||||
| 96 | # relation or a closed way) as well as an administrative boundary. detail is | |||||
| 97 | # how far Nominatim may move an outline's edge to simplify it, in degrees, as | |||||
| 98 | # text: it is stored with each outline and compared. name and names are what | |||||
| 99 | # the area is called, as a word a caller can name it by to its readers | |||||
| 100 | # (name_for). What the reverse lookup gave, November 2026 (zoom: rank, name): | |||||
| 101 | # | |||||
| 102 | # Toronto 5: 8 Ontario; 8 and 10: 12 Toronto; 12: 18 Toronto Centre | |||||
| 103 | # (ward); 14: 20 Financial District | |||||
| 104 | # Pune 5: 8 Maharashtra; 8: 12 Pune City Subdistrict; 10 and up: | |||||
| 105 | # points only | |||||
| 106 | # Canterbury 8: 12 Kent; 10 and 12: 16 Canterbury (the district) | |||||
| 107 | # Manchester 8: 10 Greater Manchester; 10: 16 Manchester; 14: 19 City | |||||
| 108 | # Centre (place=suburb, a way) | |||||
| 109 | # Bristol, York 8: 12, the unitary authority; 10: 16 Bristol (place=city, a | |||||
| 110 | # relation), York a point | |||||
| 111 | # Hamilton NZ 5: 8 Waikato; 8, 10 and 12: 12 Hamilton City | |||||
| 112 | # Auckland 5 and 8: 8 Auckland; 10: 16 Waitemata (a local board) | |||||
| 113 | # Wellington 8: 12 Wellington City; 10: a point | |||||
| 114 | # Margate 10: 16 Thanet; 12: 18 Margate (place=town, a relation); 13 | |||||
| 115 | # and 14: points (Cliftonville, Westbrook, Garlinge) | |||||
| 116 | # Westgate-on-Sea 14: 20, the civil parish; 12: 18 Birchington, a point | |||||
| 117 | Readonly my %LEVELS => ( | |||||
| 118 | country => { | |||||
| 119 | name => 'country', | |||||
| 120 | detail => '0.02', # Canada 15 KB, India 29 KB | |||||
| 121 | tries => [ { zoom => 3, ranks => [ 4, 4 ] } ], | |||||
| 122 | }, | |||||
| 123 | state => { | |||||
| 124 | name => 'state', | |||||
| 125 | names => { | |||||
| 126 | ca => 'province', cn => 'province', es => 'region', fr => 'region', | |||||
| 127 | gb => 'country', it => 'region', jp => 'prefecture', nl => 'province', | |||||
| 128 | nz => 'region', pk => 'province', za => 'province', | |||||
| 129 | }, | |||||
| 130 | detail => '0.01', # Ontario 12 KB, Maharashtra 30 KB, England 7 KB | |||||
| 131 | tries => [ { zoom => 5, ranks => [ 8, 8 ] } ], | |||||
| 132 | }, | |||||
| 133 | county => { | |||||
| 134 | rank => 12, | |||||
| 135 | countries => { | |||||
| 136 | bd => 10, # district (zila); 12 is an upazila | |||||
| 137 | cn => 10, # prefecture-level city; 12 is a district | |||||
| 138 | es => 10, # province; Spain has no rank 12 | |||||
| 139 | in => 10, # district; 12 is a sub-district (tehsil, taluk) | |||||
| 140 | ke => 8, # county; 12 is a sub-county | |||||
| 141 | }, | |||||
| 142 | name => 'county', | |||||
| 143 | names => { | |||||
| 144 | bd => 'district', cn => 'prefecture', de => 'district', es => 'province', | |||||
| 145 | fr => 'department', in => 'district', it => 'province', | |||||
| 146 | }, | |||||
| 147 | # About 100 m. Each outline is simplified alone, so neighbours' shared | |||||
| 148 | # borders differ by up to this, which shows as gaps and overlaps now | |||||
| 149 | # that each is drawn on its own side of the border; 0.005 (500 m, 2 KB | |||||
| 150 | # a county) was 7 pixels out at the zoom a county fills the map, this | |||||
| 151 | # (7 KB) under 2. | |||||
| 152 | detail => '0.001', | |||||
| 153 | }, | |||||
| 154 | city => { | |||||
| 155 | name => 'city', | |||||
| 156 | names => { gb => 'district', nz => 'district' }, | |||||
| 157 | detail => '0.0005', # Thanet 4 KB | |||||
| 158 | tries => [ | |||||
| 159 | { zoom => 10, ranks => [ 12, 16 ], places => 1 }, | |||||
| 160 | { zoom => 8, ranks => [ 12, 12 ] }, | |||||
| 161 | ], | |||||
| 162 | plans => { | |||||
| 163 | nz => [ { zoom => 8, ranks => [ 8, 12 ] } ], | |||||
| 164 | }, | |||||
| 165 | }, | |||||
| 166 | town => { | |||||
| 167 | name => 'town', | |||||
| 168 | detail => '0.0002', | |||||
| 169 | tries => [ | |||||
| 170 | { zoom => 12, ranks => [ 13, 18 ], places => 1 }, | |||||
| 171 | # A parished English town is its civil parish, rank 20, and zoom | |||||
| 172 | # 12 there answers with the nearest town mapped as a point. | |||||
| 173 | { zoom => 14, ranks => [ 19, 20 ] }, | |||||
| 174 | ], | |||||
| 175 | }, | |||||
| 176 | neighbourhood => { | |||||
| 177 | name => 'neighbourhood', | |||||
| 178 | detail => '0.0002', # Westgate-on-Sea 1 KB | |||||
| 179 | tries => [ { zoom => 14, ranks => [ 17, 20 ], places => 1 } ], | |||||
| 180 | }, | |||||
| 181 | ); | |||||
| 182 | ||||||
| 183 | # The levels, largest area first: the order a reader chooses from. | |||||
| 184 | Readonly my @LEVEL_ORDER => qw(country state county city town neighbourhood); | |||||
| 185 | ||||||
| 186 | # The reverse zoom that asks for each rank. A zoom names the most detailed | |||||
| 187 | # rank it may return, so a point with no area at that rank comes back as | |||||
| 188 | # something larger (a state), which the rank check turns away rather than | |||||
| 189 | # drawing. | |||||
| 190 | Readonly my %ZOOM_FOR_RANK => (8 => 5, 10 => 6, 12 => 8); | |||||
| 191 | ||||||
| 192 | Readonly my $REVERSE_URL => 'https://nominatim.openstreetmap.org/reverse'; | |||||
| 193 | # The detail outlines had before levels did (the county's): an outline at it is | |||||
| 194 | # kept under its plain key, so a cache from 0.023.0 is still read. | |||||
| 195 | Readonly my $PLAIN_DETAIL => '0.001'; | |||||
| 196 | Readonly my $DECIMALS => 3; # of a point, in its key and in what is sent | |||||
| 197 | Readonly my $DEFAULT_MAX => 20; # Nominatim requests in one call, as map_geocode_online_max | |||||
| 198 | Readonly my $CACHE_DIR => 'boundary-cache'; # under model_dir, for file_cache() | |||||
| 199 | Readonly my $CACHE_NAMESPACE => __PACKAGE__; | |||||
| 200 | Readonly my $CACHE_MAX_SIZE => 8 * 1024 * 1024; # bytes, for the process-wide default | |||||
| 201 | ||||||
| 202 | my $json = JSON::PP->new->canonical->utf8; | |||||
| 203 | ||||||
| 204 - 321 | =head1 NAME
Database::BI::Model::Boundary - The outline of the area around each map marker
=head1 VERSION
0.025.0
=head1 SYNOPSIS
use Database::BI::Model::Boundary;
my $boundary = Database::BI::Model::Boundary->new(
cache => Database::BI::Model::Boundary->file_cache('.bi'),
online => 1,
level => 'state', # country, state, county (default), city, town, neighbourhood
);
my $result = $boundary->outlines([ [ 39.09, -77.64 ], [ 38.85, -77.31 ] ]);
$map->add_geojson(
{ type => 'FeatureCollection', features => $result->{features} },
name => 'County boundaries',
);
# A point the map page listed as pending, looked up on its own
my $answer = $boundary->lookup_point($result->{pending}[0]);
=head1 DESCRIPTION
Finds the area each point is in, at one level, and returns its outline as a GeoJSON
Feature, for L<HTML::OSM>'s C<add_geojson>. The outlines come from
OpenStreetMap's Nominatim reverse lookup, through the same throttled user agent
as the geocoder (L<Database::BI::Model::Geocode/nominatim_ua>), so the two
together never ask more than once a second.
Only the point is sent, rounded to three decimal places (about 110 metres).
Every answer is cached: a point with the outline it is in, and the outline
itself. A point inside an outline already known is matched here, without a
request, so many points in one county cost one lookup.
The levels, largest first:
=over 4
=item country
=item state
A US or Indian state, a Canadian province, a New Zealand region, England.
=item county
The default; see below.
=item city
A city or the district named after it: Toronto, Manchester, the district of
Canterbury, Hamilton City in New Zealand. Where OpenStreetMap has no city round a point, or has the city only as a point
(York, Pune), the area at the county's rank there: the unitary authority, the
city district, or the county itself.
=item town
A town or city ward: Margate, Toronto Centre. An English town that is a civil
parish (Westgate-on-Sea) is that parish.
=item neighbourhood
A neighbourhood, suburb or civil parish that OpenStreetMap has as an area.
Many suburbs are mapped only as a point, and those have no outline.
=back
Larger areas are simplified more, so an outline is a few kilobytes at any
level.
A county here is the division of a country below its states, whose place rank
in Nominatim depends on the country: 12 (a US county or independent city, an
English county, a German Landkreis, a French departement) unless the country is
listed otherwise: 10 for India, Bangladesh, China and Spain (district,
prefecture, province), 8 for Kenya. C<ranks> adds or changes countries.
Anything else Nominatim answers is taken as "no county here" and remembered as
such. A country with nothing at its rank (Australia, Brazil, Japan) gets no
outlines.
Each reply names the point's country, so a point is asked at the zoom of the
last country seen, and asked again when its own country wants another rank.
An outline is kept with the rank it was accepted at; when C<ranks> changes, the
points it covered are asked again.
=head1 METHODS
=head2 new
my $boundary = Database::BI::Model::Boundary->new(%args);
=head3 API SPECIFICATION
=head4 INPUT
cache : object with get() and set() (CHI) optional; default one
CHI Memory cache for the process
online : boolean optional, default 0: may Nominatim be asked
online_max : integer optional, default 20: requests in one outlines() call
level : string optional, default 'county'; one of levels()
ranks : hashref optional: { country code => place rank }, over the
county level's own list; codes are two letters (any case),
ranks 8, 10 or 12. The other levels ignore it
ua : object with get() optional: the user agent to ask with
(tests); default Geocode::nominatim_ua()
=head4 OUTPUT
A Database::BI::Model::Boundary object. Croaks on an unknown level, a cache
without get and set, or ranks that are not a hash of two-letter codes to 8, 10
or 12.
=cut | |||||
| 322 | ||||||
| 323 | sub new { | |||||
| 324 | 180 | 122793 | my $class = shift; | |||
| 325 | 180 | 398 | my $raw = Params::Get::get_params(undef, \@_) // {}; | |||
| 326 | ||||||
| 327 | 180 | 2725 | my $args = validate_strict( | |||
| 328 | schema => { | |||||
| 329 | cache => { type => 'object', optional => 1, default => undef }, | |||||
| 330 | online => { type => 'boolean', optional => 1, default => 0 }, | |||||
| 331 | online_max => { type => 'integer', optional => 1, default => $DEFAULT_MAX, min => 0 }, | |||||
| 332 | level => { type => 'string', optional => 1, default => 'county' }, | |||||
| 333 | ua => { type => 'object', optional => 1, default => undef, can => 'get' }, | |||||
| 334 | ranks => { type => 'hashref', optional => 1, default => undef }, | |||||
| 335 | }, | |||||
| 336 | input => $raw, | |||||
| 337 | ); | |||||
| 338 | ||||||
| 339 | 171 | 30604 | my $level_name = $args->{level} // ''; | |||
| 340 | 171 | 256 | my $level = $LEVELS{$level_name} | |||
| 341 | or croak "Unknown boundary level '$level_name'"; | |||||
| 342 | croak 'The boundary cache needs get() and set()' | |||||
| 343 | 163 | 967 | if defined($args->{cache}) && !($args->{cache}->can('get') && $args->{cache}->can('set')); | |||
| 344 | ||||||
| 345 | return bless { | |||||
| 346 | 162 | 217 | %{$args}, | |||
| 347 | 162 162 | 219 2086 | ranks => { %{ $level->{countries} // {} }, %{ $class->check_ranks($args->{ranks} // {}) } }, | |||
| 348 | 162 | 1140 | cache => $args->{cache} // _default_cache(), | |||
| 349 | }, $class; | |||||
| 350 | } | |||||
| 351 | ||||||
| 352 - 371 | =head2 check_ranks
my $ranks = Database::BI::Model::Boundary->check_ranks({ LK => 10 }); # { lk => 10 }
=head3 API SPECIFICATION
=head4 INPUT
ranks : hashref of { country code => place rank }
Domains: a code is exactly two ASCII letters (any case); a rank is
8, 10 or 12 as a whole number (7, 9, 11, 13, '08' and '8 ' are not)
=head4 OUTPUT
A new hashref with the codes in lower case and the ranks as numbers. Croaks
on a value that is not a hashref, a key that is not a two-letter code, or a
rank that is not 8, 10 or 12, naming the entry. Used by C<new> and by the
application's startup check of C<map_bounds_ranks>.
=cut | |||||
| 372 | ||||||
| 373 | sub check_ranks { | |||||
| 374 | 255 | 21369 | my (undef, $ranks) = @_; | |||
| 375 | 255 | 346 | croak 'Boundary ranks must be a hash of country codes to place ranks' | |||
| 376 | unless ref($ranks) eq 'HASH'; | |||||
| 377 | 246 | 137 | my %checked; | |||
| 378 | 246 246 | 160 301 | for my $code (sort keys %{$ranks}) { | |||
| 379 | 109 | 64 | my $rank = $ranks->{$code}; | |||
| 380 | 109 | 179 | croak "'$code' is not a two-letter country code" unless $code =~ /\A[A-Za-z]{2}\z/; | |||
| 381 | 120 | 456 | croak "the rank for '$code' must be one of " . join(', ', sort { $a <=> $b } keys %ZOOM_FOR_RANK) | |||
| 382 | 82 | 262 | unless defined($rank) && !ref($rank) && $rank =~ /\A[0-9]+\z/ && $ZOOM_FOR_RANK{$rank}; | |||
| 383 | 42 | 140 | croak "'$code' is given twice" if exists $checked{ lc $code }; | |||
| 384 | 38 | 40 | $checked{ lc $code } = $rank + 0; | |||
| 385 | } | |||||
| 386 | 175 | 304 | return \%checked; | |||
| 387 | } | |||||
| 388 | ||||||
| 389 - 406 | =head2 rank_for
my $rank = $boundary->rank_for('in'); # 10
=head3 API SPECIFICATION
=head4 INPUT
country : string, an ISO 3166-1 alpha-2 code in any case; undef or ''
for a point in no country (the sea)
=head4 OUTPUT
The place rank an outline in that country must have at the county level: the
country's own, from C<ranks> or the built-in list, else 12. At another level,
the most detailed rank its first try takes there.
=cut | |||||
| 407 | ||||||
| 408 | sub rank_for { | |||||
| 409 | 29 | 2058 | my ($self, $country) = @_; | |||
| 410 | 29 | 29 | my $level = $LEVELS{ $self->{level} }; | |||
| 411 | 29 | 55 | return $self->_plan($country)->[0]{ranks}[1] unless defined $level->{rank}; | |||
| 412 | my $rank = (defined($country) && !ref($country) && length($country)) | |||||
| 413 | 27 | 96 | ? $self->{ranks}{ lc $country } : undef; | |||
| 414 | 27 | 41 | return $rank // $level->{rank}; | |||
| 415 | } | |||||
| 416 | ||||||
| 417 - 439 | =head2 name_for
my $word = $boundary->name_for('in'); # 'district'
What this object's level is called in a country, so a caller can say
"district" on a map of India rather than "county".
=head3 API SPECIFICATION
=head4 INPUT
country : string, an ISO 3166-1 alpha-2 code in any case; undef or ''
for a point in no country
=head4 OUTPUT
One lower-case English word: C<country>, C<state>, C<region>, C<province>,
C<prefecture>, C<county>, C<district>, C<department>, C<city>, C<town> or
C<neighbourhood>. A country not listed gets the level's own name
(L</level_name>). It is a word to look a translation up by, not text to show.
Called on the class, it answers for the county level.
=cut | |||||
| 440 | ||||||
| 441 | sub name_for { | |||||
| 442 | 227 | 8136 | my ($self, $country) = @_; | |||
| 443 | 227 | 299 | my $level = $LEVELS{ ref($self) ? $self->{level} : 'county' }; | |||
| 444 | my $name = (defined($country) && !ref($country) && length($country)) | |||||
| 445 | 227 | 724 | ? ($level->{names} // {})->{ lc $country } : undef; | |||
| 446 | 227 | 763 | return $name // $level->{name}; | |||
| 447 | } | |||||
| 448 | ||||||
| 449 - 465 | =head2 level_name
my $word = Database::BI::Model::Boundary->level_name('state'); # 'state'
=head3 API SPECIFICATION
=head4 INPUT
level : string, one of levels()
=head4 OUTPUT
What the level's areas are called where no country says otherwise, as
L</name_for> gives it: the word to use before a point's country is known.
Undef for a level that is not one.
=cut | |||||
| 466 | ||||||
| 467 | sub level_name { | |||||
| 468 | 197 | 4056 | my (undef, $level) = @_; | |||
| 469 | 197 | 507 | return unless defined($level) && !ref($level) && $LEVELS{$level}; | |||
| 470 | 142 | 382 | return $LEVELS{$level}{name}; | |||
| 471 | } | |||||
| 472 | ||||||
| 473 - 488 | =head2 levels
my @levels = Database::BI::Model::Boundary->levels;
# ('country', 'state', 'county', 'city', 'town', 'neighbourhood')
=head3 API SPECIFICATION
=head4 INPUT
None.
=head4 OUTPUT
The names of the levels new() takes, the largest area first.
=cut | |||||
| 489 | ||||||
| 490 | sub levels { | |||||
| 491 | 130 | 54961 | return @LEVEL_ORDER; | |||
| 492 | } | |||||
| 493 | ||||||
| 494 - 516 | =head2 point_key my $key = Database::BI::Model::Boundary->point_key(39.0901, -77.6402); # '39.090,-77.640' =head3 API SPECIFICATION =head4 INPUT lat : number -90 .. 90 lon : number -180 .. 180 Domains: each is a plain decimal, an optional minus and ASCII digits with an optional fraction (1, -1.5, 12.345678). A plus sign, a bare point (.5, 5.), an exponent, spaces, a newline, a comma, NaN, Inf and non-ASCII digits are not numbers here. The edges -90, 90, -180 and 180 are in; anything past them, however slightly (90.0001), is out, even if it would round to an edge. =head4 OUTPUT The point rounded to three decimal places, as C<"lat,lon">: what the cache is keyed by and all of the point that is sent. Undef for a point out of range. =cut | |||||
| 517 | ||||||
| 518 | sub point_key { | |||||
| 519 | 101069 | 161677 | my (undef, $lat, $lon) = @_; | |||
| 520 | ||||||
| 521 | 101069 | 250766 | return unless defined($lat) && defined($lon) | |||
| 522 | && $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ && $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ | |||||
| 523 | && abs($lat) <= 90 && abs($lon) <= 180; | |||||
| 524 | ||||||
| 525 | my @parts = map { | |||||
| 526 | 100966 201932 | 42869 94186 | my $text = sprintf("%.${DECIMALS}f", $_); | |||
| 527 | 201932 | 254315 | $text =~ s/\A-(?=0\.0+\z)//; # no "-0.000", so a point has one key | |||
| 528 | 201932 | 87146 | $text; | |||
| 529 | } ($lat, $lon); | |||||
| 530 | 100966 | 54411 | return join(',', @parts); | |||
| 531 | } | |||||
| 532 | ||||||
| 533 - 563 | =head2 outlines
my $result = $boundary->outlines(\@points, lookup => 1);
=head3 API SPECIFICATION
=head4 INPUT
points : arrayref of [lat, lon]
lookup : boolean, default 1. 0 asks Nominatim nothing: the points not
known yet come back in pending, for the caller to look up one at
a time (lookup_point)
=head4 OUTPUT
{
features => [ GeoJSON Feature, ... ] one per outline, in the order
their first point came; properties { name, osm, called }
(called: what the division is called there, as name_for)
pending => [ point_key, ... ] points not known, not asked
inside => { point_key => osm, ... } the outline each point drawn is in,
by the osm of its Feature (to total what is in each)
counts => { points, drawn, attempted, nowhere }
offline => 0|1 points were left because Nominatim may not be asked
failed => 0|1 Nominatim did not answer; the rest were left
}
A point out of range is ignored. A Feature's name is the place's name as
OpenStreetMap has it: text, not HTML.
=cut | |||||
| 564 | ||||||
| 565 | sub outlines { | |||||
| 566 | 148 | 63187 | my ($self, $points, @rest) = @_; | |||
| 567 | 148 | 234 | croak 'outlines() needs an arrayref of [lat, lon]' unless ref($points) eq 'ARRAY'; | |||
| 568 | 143 | 190 | my %opt = @rest; | |||
| 569 | 143 | 231 | my $lookup = exists($opt{lookup}) ? $opt{lookup} : 1; | |||
| 570 | ||||||
| 571 | 143 | 696 | local ($@, $!); | |||
| 572 | ||||||
| 573 | 143 | 113 | my (@keys, %seen); | |||
| 574 | 143 143 | 97 151 | for my $point (@{$points}) { | |||
| 575 | 100370 | 53839 | next unless ref($point) eq 'ARRAY'; | |||
| 576 | 100367 100367 | 35128 53538 | my $key = $self->point_key(@{$point}[0, 1]); | |||
| 577 | 100367 | 137918 | push @keys, $key if defined($key) && !$seen{$key}++; | |||
| 578 | } | |||||
| 579 | ||||||
| 580 | 143 | 321 | my %counts = (points => scalar(@keys), drawn => 0, attempted => 0, nowhere => 0); | |||
| 581 | 143 | 137 | my (@order, %used, %inside, @pending, $failed, $offline); | |||
| 582 | 143 | 222 | my $index = $self->_index; | |||
| 583 | ||||||
| 584 | 143 | 149 | for my $key (@keys) { | |||
| 585 | 100354 | 46713 | my ($osm, $status) = $self->_known($key, $index); | |||
| 586 | 100354 | 70399 | if (!defined($status) && $lookup) { | |||
| 587 | 197 | 199 | if (!$self->_can_ask) { | |||
| 588 | 12 | 10 | $offline = 1; | |||
| 589 | } elsif (!$failed && $counts{attempted} < $self->{online_max}) { | |||||
| 590 | 144 | 398 | $counts{attempted}++; | |||
| 591 | 144 | 163 | ($osm, $status) = $self->_ask($key, $index); | |||
| 592 | 144 | 345 | $failed = 1 if $status eq 'failed'; | |||
| 593 | } | |||||
| 594 | } | |||||
| 595 | 100354 | 51303 | if (!defined($status) || $status eq 'failed') { | |||
| 596 | 100085 | 43840 | push @pending, $key; | |||
| 597 | 100085 | 53159 | next; | |||
| 598 | } | |||||
| 599 | 269 | 195 | if ($status eq 'nowhere') { | |||
| 600 | 24 | 30 | $counts{nowhere}++; | |||
| 601 | 24 | 27 | next; | |||
| 602 | } | |||||
| 603 | 245 | 379 | push @order, $osm unless $used{$osm}++; | |||
| 604 | 245 | 290 | $inside{$key} = $osm; | |||
| 605 | } | |||||
| 606 | ||||||
| 607 | 143 | 124 | my @features; | |||
| 608 | 143 | 146 | for my $osm (@order) { | |||
| 609 | 197 | 1215 | my $outline = $self->_get($self->_outline_key($osm)) or next; | |||
| 610 | push @features, { | |||||
| 611 | type => 'Feature', | |||||
| 612 | properties => { name => $outline->{name}, osm => $osm, | |||||
| 613 | called => $self->name_for($outline->{country}) }, | |||||
| 614 | # A copy: the cache may hand out the one it holds (an in-memory | |||||
| 615 | # layer does), and a caller that changes its result must not change | |||||
| 616 | # what the next one is given. | |||||
| 617 | 197 | 312 | geometry => (ref($outline->{geometry}) ? dclone($outline->{geometry}) : $outline->{geometry}), | |||
| 618 | }; | |||||
| 619 | } | |||||
| 620 | 143 | 855 | $counts{drawn} = scalar @features; | |||
| 621 | 143 197 | 152 214 | my %drawn = map { $_->{properties}{osm} => 1 } @features; | |||
| 622 | 143 245 | 160 180 | delete @inside{ grep { !$drawn{ $inside{$_} } } keys %inside }; | |||
| 623 | ||||||
| 624 | return { | |||||
| 625 | 143 | 21846 | features => \@features, | |||
| 626 | pending => \@pending, | |||||
| 627 | inside => \%inside, | |||||
| 628 | counts => \%counts, | |||||
| 629 | offline => $offline ? 1 : 0, | |||||
| 630 | failed => $failed ? 1 : 0, | |||||
| 631 | }; | |||||
| 632 | } | |||||
| 633 | ||||||
| 634 - 653 | =head2 lookup_point
my $answer = $boundary->lookup_point('39.090,-77.640');
=head3 API SPECIFICATION
=head4 INPUT
key : string, a point_key
=head4 OUTPUT
{ status => 'found' | 'nowhere' | 'held', name => string|undef, asked => 0|1 }
'found' and 'nowhere' are remembered. 'held' is a point that could not be
settled now - Nominatim did not answer, or may not be asked - and is asked
again next time. asked says whether Nominatim was asked. Croaks on a key
that is not a point_key.
=cut | |||||
| 654 | ||||||
| 655 | sub lookup_point { | |||||
| 656 | 55 | 10540 | my ($self, $key) = @_; | |||
| 657 | ||||||
| 658 | 55 | 202 | croak 'lookup_point() needs a point key such as 39.090,-77.640' | |||
| 659 | unless defined($key) && !ref($key) | |||||
| 660 | && $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/ | |||||
| 661 | && defined($self->point_key($1, $2)) && $self->point_key($1, $2) eq $key; | |||||
| 662 | ||||||
| 663 | 37 | 52 | local ($@, $!); | |||
| 664 | ||||||
| 665 | 37 | 50 | my $index = $self->_index; | |||
| 666 | 37 | 55 | my ($osm, $status) = $self->_known($key, $index); | |||
| 667 | 37 | 38 | my $asked = 0; | |||
| 668 | 37 | 73 | if (!defined($status) && $self->_can_ask) { | |||
| 669 | 22 | 53 | $asked = 1; | |||
| 670 | 22 | 29 | ($osm, $status) = $self->_ask($key, $index); | |||
| 671 | } | |||||
| 672 | ||||||
| 673 | 37 | 148 | return { status => 'held', name => undef, asked => $asked } | |||
| 674 | if !defined($status) || $status eq 'failed'; | |||||
| 675 | 25 | 49 | return { status => 'nowhere', name => undef, asked => $asked } if $status eq 'nowhere'; | |||
| 676 | ||||||
| 677 | 20 | 25 | my $outline = $self->_get($self->_outline_key($osm)); | |||
| 678 | 20 | 97 | return { status => 'found', name => ($outline ? $outline->{name} : undef), asked => $asked }; | |||
| 679 | } | |||||
| 680 | ||||||
| 681 - 696 | =head2 file_cache my $cache = Database::BI::Model::Boundary->file_cache($model_dir); =head3 API SPECIFICATION =head4 INPUT dir : string, an existing directory (model_dir) =head4 OUTPUT A CHI File cache under C<< <dir>/boundary-cache >>, with a copy of what it reads in memory for as long as the cache object lives. Croaks when dir is not a directory. =cut | |||||
| 697 | ||||||
| 698 | sub file_cache { | |||||
| 699 | 101 | 37806 | my (undef, $dir) = @_; | |||
| 700 | ||||||
| 701 | 101 | 737 | croak 'The boundary cache needs a directory, not ' . (defined($dir) ? $dir : 'undef') | |||
| 702 | unless defined($dir) && !ref($dir) && -d $dir; | |||||
| 703 | ||||||
| 704 | 96 | 196 | require CHI; | |||
| 705 | 96 | 183 | require File::Spec; | |||
| 706 | 96 | 293 | return CHI->new( | |||
| 707 | driver => 'File', | |||||
| 708 | root_dir => File::Spec->catdir($dir, $CACHE_DIR), | |||||
| 709 | namespace => $CACHE_NAMESPACE, | |||||
| 710 | # A copy in memory for this object, which a request makes afresh: it | |||||
| 711 | # saves reading the index and outlines again within the request. Not | |||||
| 712 | # global, which would share it with every cache of this namespace in | |||||
| 713 | # the process, whatever its folder, and keep a worker from seeing | |||||
| 714 | # what another has added since. | |||||
| 715 | l1_cache => { driver => 'RawMemory', global => 0, max_size => $CACHE_MAX_SIZE }, | |||||
| 716 | ); | |||||
| 717 | } | |||||
| 718 | ||||||
| 719 | # --------------------------------------------------------------------------- | |||||
| 720 | # Private | |||||
| 721 | # --------------------------------------------------------------------------- | |||||
| 722 | ||||||
| 723 | my $default_cache; | |||||
| 724 | ||||||
| 725 | sub _default_cache { | |||||
| 726 | 18 | 157 | require CHI; | |||
| 727 | 18 | 47 | $default_cache //= CHI->new( | |||
| 728 | driver => 'Memory', | |||||
| 729 | global => 1, | |||||
| 730 | namespace => $CACHE_NAMESPACE, | |||||
| 731 | max_size => $CACHE_MAX_SIZE, | |||||
| 732 | ); | |||||
| 733 | 18 | 20499 | return $default_cache; | |||
| 734 | } | |||||
| 735 | ||||||
| 736 | # _get($key) / _set($key, $value): the cache, under this level's prefix for a | |||||
| 737 | # point and under _outline_key for an outline. A cache that fails reads as empty and writes as nothing: the page | |||||
| 738 | # still draws, and asks again next time. | |||||
| 739 | sub _get { | |||||
| 740 | 101198 | 43915 | my ($self, $key) = @_; | |||
| 741 | 101198 101198 | 37295 507749 | my $value = eval { $self->{cache}->get($key) }; | |||
| 742 | 101198 | 7871361 | return $value; | |||
| 743 | } | |||||
| 744 | ||||||
| 745 | sub _set { | |||||
| 746 | 480 | 820 | my ($self, $key, $value) = @_; | |||
| 747 | 480 480 480 | 233 1983 156661 | return eval { $self->{cache}->set($key, $value, 'never'); 1 }; | |||
| 748 | } | |||||
| 749 | ||||||
| 750 | sub _point_cache_key { | |||||
| 751 | 100573 | 44300 | my ($self, $key) = @_; | |||
| 752 | 100573 | 59459 | return "point:$self->{level}:$key"; | |||
| 753 | } | |||||
| 754 | ||||||
| 755 | # _detail() -> how far this level's outlines are simplified, as text | |||||
| 756 | sub _detail { | |||||
| 757 | 981 | 857 | my $self = shift; | |||
| 758 | 981 | 1009 | return $LEVELS{ $self->{level} }{detail}; | |||
| 759 | } | |||||
| 760 | ||||||
| 761 | # _outline_key($osm) -> the cache key of an outline at this level's detail. | |||||
| 762 | # One relation is one outline at every level of the same detail, and a copy | |||||
| 763 | # apiece where they differ, so two levels never fetch over each other's. | |||||
| 764 | sub _outline_key { | |||||
| 765 | 504 | 344 | my ($self, $osm) = @_; | |||
| 766 | 504 | 295 | my $detail = $self->_detail; | |||
| 767 | 504 | 1929 | return $detail eq $PLAIN_DETAIL ? "outline:$osm" : "outline:$osm:$detail"; | |||
| 768 | } | |||||
| 769 | ||||||
| 770 | # _plan($country) -> arrayref of tries { zoom, ranks => [low, high], places } | |||||
| 771 | # | |||||
| 772 | # How this level is asked for in a country (undef or '' for none known): the | |||||
| 773 | # county level's one rank at the zoom that asks for it, else the level's | |||||
| 774 | # tries, or the country's own. | |||||
| 775 | sub _plan { | |||||
| 776 | 377 | 957 | my ($self, $country) = @_; | |||
| 777 | 377 | 496 | my $level = $LEVELS{ $self->{level} }; | |||
| 778 | 377 | 1069 | $country = (defined($country) && !ref($country)) ? lc($country) : ''; | |||
| 779 | 377 | 289 | if (defined $level->{rank}) { | |||
| 780 | 320 | 897 | my $rank = $self->{ranks}{$country} // $level->{rank}; | |||
| 781 | 320 | 719 | return [ { zoom => $ZOOM_FOR_RANK{$rank}, ranks => [ $rank, $rank ] } ]; | |||
| 782 | } | |||||
| 783 | 57 | 126 | return ($level->{plans} // {})->{$country} // $level->{tries}; | |||
| 784 | } | |||||
| 785 | ||||||
| 786 | # _plan_sig(\@plan) -> the plan as text, kept with a point found nowhere so a | |||||
| 787 | # changed plan asks again. | |||||
| 788 | sub _plan_sig { | |||||
| 789 | 30 | 67 | my $plan = shift; | |||
| 790 | 30 30 30 | 29 139 31 | return join(';', map { "$_->{zoom}:$_->{ranks}[0]-$_->{ranks}[1]" . ($_->{places} ? ':p' : '') } @{$plan}); | |||
| 791 | } | |||||
| 792 | ||||||
| 793 | # _accepts(\@plan, $rank) -> 1 when some try of the plan takes that rank | |||||
| 794 | sub _accepts { | |||||
| 795 | 145 | 507 | my ($plan, $rank) = @_; | |||
| 796 | 145 145 145 | 202 577 165 | return (first { $rank >= $_->{ranks}[0] && $rank <= $_->{ranks}[1] } @{$plan}) ? 1 : 0; | |||
| 797 | } | |||||
| 798 | ||||||
| 799 | # _index() -> arrayref of [osm, south, west, north, east] | |||||
| 800 | # | |||||
| 801 | # The bounding box of every outline this level has found, so a point can be | |||||
| 802 | # tested against the few that could hold it. Two processes adding at once can | |||||
| 803 | # lose one's entry; that costs a request later, not a wrong answer. | |||||
| 804 | sub _index { | |||||
| 805 | 312 | 198 | my $self = shift; | |||
| 806 | 312 | 509 | my $index = $self->_get("index:$self->{level}"); | |||
| 807 | 312 150 | 411 167 | return ref($index) eq 'ARRAY' ? [ @{$index} ] : []; | |||
| 808 | } | |||||
| 809 | ||||||
| 810 | # _known($key, \@index) -> ($osm, $status) or () | |||||
| 811 | # | |||||
| 812 | # What is known of a point without asking: remembered with an outline or with | |||||
| 813 | # none, or inside an outline the index holds (which is then remembered). | |||||
| 814 | sub _known { | |||||
| 815 | 100391 | 49812 | my ($self, $key, $index) = @_; | |||
| 816 | ||||||
| 817 | 100391 | 48703 | my $remembered = $self->_get($self->_point_cache_key($key)); | |||
| 818 | 100391 | 70181 | if (ref($remembered) eq 'HASH') { | |||
| 819 | # Nowhere, by the plan its country had then. 0.023.0 kept the rank | |||||
| 820 | # alone, which names a county plan. | |||||
| 821 | 12 | 12 | my $sig = $remembered->{plan}; | |||
| 822 | $sig //= "$ZOOM_FOR_RANK{ $remembered->{rank} }:$remembered->{rank}-$remembered->{rank}" | |||||
| 823 | 12 | 37 | if defined($remembered->{rank}) && $ZOOM_FOR_RANK{ $remembered->{rank} }; | |||
| 824 | return (undef, 'nowhere') | |||||
| 825 | 12 | 74 | if defined($sig) && $sig eq _plan_sig($self->_plan($remembered->{country})); | |||
| 826 | } elsif (defined($remembered) && length($remembered)) { | |||||
| 827 | 111 | 130 | return ($remembered, 'found') if $self->_current($self->_get($self->_outline_key($remembered))); | |||
| 828 | # The outline has gone from the cache, or its country's rank changed. | |||||
| 829 | } | |||||
| 830 | # '' is nowhere from before ranks were kept: ask again. | |||||
| 831 | ||||||
| 832 | 100279 | 50604 | my ($lat, $lon) = split /,/, $key; | |||
| 833 | 100279 100279 | 42242 43029 | for my $entry (@{$index}) { | |||
| 834 | # A damaged index entry (not five defined values) knows no outline. | |||||
| 835 | 587 2935 587 | 432 1889 336 | next unless ref($entry) eq 'ARRAY' && 5 == grep { defined && !ref } @{$entry}[0 .. 4]; | |||
| 836 | 585 585 | 235 319 | my ($osm, $south, $west, $north, $east) = @{$entry}; | |||
| 837 | 585 | 1057 | next if $lat < $south || $lat > $north || $lon < $west || $lon > $east; | |||
| 838 | 43 | 43 | my $outline = $self->_get($self->_outline_key($osm)); | |||
| 839 | 43 | 47 | next unless $self->_current($outline) && _contains($outline->{geometry}, $lat, $lon); | |||
| 840 | 31 | 44 | $self->_set($self->_point_cache_key($key), $osm); | |||
| 841 | 31 | 60 | return ($osm, 'found'); | |||
| 842 | } | |||||
| 843 | ||||||
| 844 | 100248 | 47341 | return; | |||
| 845 | } | |||||
| 846 | ||||||
| 847 | # _current($outline) -> 1 when an outline was accepted at the rank its country | |||||
| 848 | # wants now, and simplified as outlines are now. One kept before ranks were | |||||
| 849 | # (no rank), or at another level of detail, is not. | |||||
| 850 | sub _current { | |||||
| 851 | 161 | 131 | my ($self, $outline) = @_; | |||
| 852 | 161 | 292 | return 0 unless ref($outline) eq 'HASH' && defined($outline->{rank}); | |||
| 853 | 149 | 188 | return 0 unless ($outline->{detail} // '') eq $self->_detail; | |||
| 854 | 145 | 602 | return _accepts($self->_plan($outline->{country}), $outline->{rank}); | |||
| 855 | } | |||||
| 856 | ||||||
| 857 | # _last_country() / _last_country($code): the country of the last reply at | |||||
| 858 | # this level, whose rank the next point is asked at first. Kept in the cache, | |||||
| 859 | # so the first point of a later map is not asked twice. | |||||
| 860 | sub _last_country { | |||||
| 861 | 210 | 192 | my ($self, @set) = @_; | |||
| 862 | 210 | 168 | my $key = "country:$self->{level}"; | |||
| 863 | 210 | 177 | if (@set) { | |||
| 864 | 44 | 37 | $self->{last_country} = $set[0]; | |||
| 865 | 44 | 30 | $self->_set($key, $set[0]) unless ($self->_get($key) // '') eq $set[0]; | |||
| 866 | 44 | 36 | return $set[0]; | |||
| 867 | } | |||||
| 868 | 166 | 274 | return $self->{last_country} //= $self->_get($key) // ''; | |||
| 869 | } | |||||
| 870 | ||||||
| 871 | sub _can_ask { | |||||
| 872 | 228 | 137 | my $self = shift; | |||
| 873 | 228 | 245 | return 0 unless $self->{online}; | |||
| 874 | 209 | 293 | return 1 if $self->{ua}; | |||
| 875 | 153 | 268 | require Database::BI::Model::Geocode; | |||
| 876 | 153 | 223 | return Database::BI::Model::Geocode::nominatim_ua() ? 1 : 0; | |||
| 877 | } | |||||
| 878 | ||||||
| 879 | # _ask($key, \@index) -> ($osm, 'found') | (undef, 'nowhere') | (undef, 'failed') | |||||
| 880 | # | |||||
| 881 | # Reverse lookups down a plan. The first is the first try of the plan of the | |||||
| 882 | # last country seen; its reply names the point's country, whose plan is then | |||||
| 883 | # followed from its start (a try at a zoom already asked uses that reply), to | |||||
| 884 | # the first try that gives an outline. A found outline is remembered with its | |||||
| 885 | # country and rank, added to the index (and to @$index, so the caller's later | |||||
| 886 | # points are tested against it), and the point remembered with it. A point no | |||||
| 887 | # try gives an outline for is remembered as nowhere, with its country and the | |||||
| 888 | # plan. A failure is remembered as nothing. | |||||
| 889 | sub _ask { | |||||
| 890 | 166 | 135 | my ($self, $key, $index) = @_; | |||
| 891 | 166 | 162 | my ($lat, $lon) = split /,/, $key; | |||
| 892 | ||||||
| 893 | 166 | 118 | my %replies; # by zoom | |||
| 894 | my $reverse = sub { | |||||
| 895 | 306 | 248 | my $zoom = shift; | |||
| 896 | 306 | 605 | return $replies{$zoom} //= $self->_reverse($lat, $lon, $zoom); | |||
| 897 | 166 | 259 | }; | |||
| 898 | ||||||
| 899 | 166 | 216 | my $plan = $self->_plan($self->_last_country); | |||
| 900 | 166 | 702 | my $first = $reverse->($plan->[0]{zoom}) or return (undef, 'failed'); | |||
| 901 | ||||||
| 902 | 152 | 237 | my $country = ref($first->{address}) eq 'HASH' ? $first->{address}{country_code} : undef; | |||
| 903 | 152 | 258 | $country = (defined($country) && !ref($country) && $country =~ /\A[A-Za-z]{2}\z/) ? lc($country) : ''; | |||
| 904 | 152 | 113 | if (length $country) { | |||
| 905 | 44 | 41 | $self->_last_country($country); | |||
| 906 | 44 | 39 | $plan = $self->_plan($country); | |||
| 907 | } | |||||
| 908 | ||||||
| 909 | 152 | 259 | my ($reply, $osm); | |||
| 910 | # "Unable to geocode" is the sea at any zoom: no try will do better. | |||||
| 911 | 152 138 | 148 114 | for my $try (defined($first->{error}) ? () : @{$plan}) { | |||
| 912 | 140 | 163 | my $answer = $reverse->($try->{zoom}) or return (undef, 'failed'); | |||
| 913 | 139 | 133 | $osm = _outline_id($answer, $try) // next; | |||
| 914 | 133 | 82 | $reply = $answer; | |||
| 915 | 133 | 75 | last; | |||
| 916 | } | |||||
| 917 | ||||||
| 918 | 151 | 149 | unless ($reply) { | |||
| 919 | # The sea, and answers at other ranks or with no shape, alike. rank is | |||||
| 920 | # what 0.023.0 kept, and reads back as the same county plan. | |||||
| 921 | $self->_set($self->_point_cache_key($key), | |||||
| 922 | 18 | 28 | { country => $country, rank => $plan->[0]{ranks}[1], plan => _plan_sig($plan) }); | |||
| 923 | 18 | 77 | return (undef, 'nowhere'); | |||
| 924 | } | |||||
| 925 | ||||||
| 926 | 133 | 82 | my $geometry = $reply->{geojson}; | |||
| 927 | 133 | 84 | my $name = $reply->{name}; | |||
| 928 | 133 | 164 | $name = $reply->{display_name} unless defined($name) && length($name); | |||
| 929 | $self->_set($self->_outline_key($osm), { | |||||
| 930 | name => $name // $osm, | |||||
| 931 | geometry => $geometry, | |||||
| 932 | country => $country, | |||||
| 933 | 133 | 158 | rank => $reply->{place_rank} + 0, | |||
| 934 | detail => $self->_detail, | |||||
| 935 | }); | |||||
| 936 | ||||||
| 937 | 133 515 133 | 137 336 159 | unless (grep { $_->[0] eq $osm } @{$index}) { | |||
| 938 | 132 | 143 | my $box = _bounds($geometry); | |||
| 939 | 132 | 132 | if ($box) { | |||
| 940 | 131 131 131 | 67 92 138 | push @{$index}, [ $osm, @{$box} ]; | |||
| 941 | 131 | 154 | my $stored = $self->_index; | |||
| 942 | 131 131 131 514 131 | 77 83 117 271 105 | push @{$stored}, [ $osm, @{$box} ] unless grep { $_->[0] eq $osm } @{$stored}; | |||
| 943 | 131 | 372 | $self->_set("index:$self->{level}", $stored); | |||
| 944 | } | |||||
| 945 | } | |||||
| 946 | 133 | 169 | $self->_set($self->_point_cache_key($key), $osm); | |||
| 947 | ||||||
| 948 | 133 | 651 | return ($osm, 'found'); | |||
| 949 | } | |||||
| 950 | ||||||
| 951 | # _outline_id($reply, $try) -> 'R<id>' or 'W<id>' when the reply is an outline | |||||
| 952 | # the try takes, else undef. | |||||
| 953 | # | |||||
| 954 | # An outline is an area with a shape, at a rank in the try's range: an | |||||
| 955 | # administrative boundary's relation, or, for a try that takes places, a place | |||||
| 956 | # mapped as an area (place=city, town, suburb), which may be a closed way. A | |||||
| 957 | # place mapped as a point has no shape and is not one. | |||||
| 958 | sub _outline_id { | |||||
| 959 | 160 | 3007 | my ($reply, $try) = @_; | |||
| 960 | ||||||
| 961 | 160 | 136 | my $geometry = $reply->{geojson}; | |||
| 962 | 160 | 99 | my $rank = $reply->{place_rank}; | |||
| 963 | 160 | 157 | my $category = $reply->{category} // ''; | |||
| 964 | 160 | 137 | my $osm_type = $reply->{osm_type} // ''; | |||
| 965 | return unless defined($reply->{osm_id}) && $reply->{osm_id} =~ /\A[0-9]+\z/ | |||||
| 966 | && defined($rank) && !ref($rank) && $rank =~ /\A[0-9]+\z/ | |||||
| 967 | && $rank >= $try->{ranks}[0] && $rank <= $try->{ranks}[1] | |||||
| 968 | && ref($geometry) eq 'HASH' | |||||
| 969 | && ($geometry->{type} // '') =~ /\A(?:Multi)?Polygon\z/ | |||||
| 970 | 160 | 1111 | && ref($geometry->{coordinates}) eq 'ARRAY'; | |||
| 971 | ||||||
| 972 | 143 | 441 | my $boundary = $category eq 'boundary' && ($reply->{type} // '') eq 'administrative' | |||
| 973 | && $osm_type eq 'relation'; | |||||
| 974 | 143 | 161 | my $place = $try->{places} && $category eq 'place' && ($osm_type eq 'relation' || $osm_type eq 'way'); | |||
| 975 | 143 | 184 | return unless $boundary || $place; | |||
| 976 | ||||||
| 977 | 136 | 206 | return ($osm_type eq 'way' ? 'W' : 'R') . $reply->{osm_id}; | |||
| 978 | } | |||||
| 979 | ||||||
| 980 | # _reverse($lat, $lon, $zoom) -> the decoded reply, or undef when Nominatim | |||||
| 981 | # did not answer with JSON. | |||||
| 982 | sub _reverse { | |||||
| 983 | 193 | 197 | my ($self, $lat, $lon, $zoom) = @_; | |||
| 984 | ||||||
| 985 | 193 | 486 | my $uri = URI->new($REVERSE_URL); | |||
| 986 | 193 | 8942 | $uri->query_form( | |||
| 987 | lat => $lat, | |||||
| 988 | lon => $lon, | |||||
| 989 | zoom => $zoom, | |||||
| 990 | format => 'jsonv2', | |||||
| 991 | polygon_geojson => 1, | |||||
| 992 | polygon_threshold => $self->_detail, | |||||
| 993 | 'accept-language' => 'en', | |||||
| 994 | ); | |||||
| 995 | ||||||
| 996 | 193 | 11070 | require Database::BI::Model::Geocode; | |||
| 997 | 193 | 294 | my $ua = $self->{ua} // Database::BI::Model::Geocode::nominatim_ua(); | |||
| 998 | 193 193 | 234 258 | my $res = eval { $ua->get($uri) }; | |||
| 999 | 193 | 65050 | return unless blessed($res) && $res->can('is_success') && $res->is_success; | |||
| 1000 | ||||||
| 1001 | 178 178 | 2090 262 | my $reply = eval { $json->decode($res->decoded_content // '') }; | |||
| 1002 | 178 | 149056 | return ref($reply) eq 'HASH' ? $reply : undef; | |||
| 1003 | } | |||||
| 1004 | ||||||
| 1005 | # _polygons($geometry) -> list of polygons, each an arrayref of rings, each | |||||
| 1006 | # ring an arrayref of [lon, lat]. | |||||
| 1007 | sub _polygons { | |||||
| 1008 | 196 | 113 | my $geometry = shift; | |||
| 1009 | 196 | 457 | return () unless ref($geometry) eq 'HASH' && ref($geometry->{coordinates}) eq 'ARRAY'; | |||
| 1010 | 189 | 272 | return ($geometry->{coordinates}) if ($geometry->{type} // '') eq 'Polygon'; | |||
| 1011 | 10 8 | 17 9 | return @{ $geometry->{coordinates} } if ($geometry->{type} // '') eq 'MultiPolygon'; | |||
| 1012 | 2 | 3 | return (); | |||
| 1013 | } | |||||
| 1014 | ||||||
| 1015 | # _bounds($geometry) -> [south, west, north, east], or undef with no points | |||||
| 1016 | sub _bounds { | |||||
| 1017 | 138 | 996 | my $geometry = shift; | |||
| 1018 | 138 | 93 | my ($south, $west, $north, $east); | |||
| 1019 | 138 | 129 | for my $polygon (_polygons($geometry)) { | |||
| 1020 | 138 138 | 63 153 | for my $position (@{ $polygon->[0] // [] }) { | |||
| 1021 | 664 664 | 273 297 | my ($lon, $lat) = @{$position}; | |||
| 1022 | 664 | 569 | $south = $lat if !defined($south) || $lat < $south; | |||
| 1023 | 664 | 510 | $north = $lat if !defined($north) || $lat > $north; | |||
| 1024 | 664 | 487 | $west = $lon if !defined($west) || $lon < $west; | |||
| 1025 | 664 | 546 | $east = $lon if !defined($east) || $lon > $east; | |||
| 1026 | } | |||||
| 1027 | } | |||||
| 1028 | 138 | 168 | return defined($south) ? [ $south, $west, $north, $east ] : undef; | |||
| 1029 | } | |||||
| 1030 | ||||||
| 1031 | # _contains($geometry, $lat, $lon) -> 1 when the point is inside a polygon's | |||||
| 1032 | # outer ring and none of its holes (Fairfax County's hole is the City of | |||||
| 1033 | # Fairfax). Even-odd ray casting, with longitude as x. | |||||
| 1034 | sub _contains { | |||||
| 1035 | 56 | 5440 | my ($geometry, $lat, $lon) = @_; | |||
| 1036 | 56 | 51 | for my $polygon (_polygons($geometry)) { | |||
| 1037 | # Premise 1: the geometry came from a web service and a cache file. | |||||
| 1038 | # Premise 2: a damaged entry must not turn a map into a 500. | |||||
| 1039 | # Conclusion: what is not a polygon holds no point. | |||||
| 1040 | 53 | 67 | next unless ref($polygon) eq 'ARRAY'; | |||
| 1041 | 50 50 | 28 38 | my ($outer, @holes) = @{$polygon}; | |||
| 1042 | 50 | 54 | next unless _in_ring($outer, $lon, $lat); | |||
| 1043 | 43 10 | 73 16 | return 1 unless grep { _in_ring($_, $lon, $lat) } @holes; | |||
| 1044 | } | |||||
| 1045 | 21 | 32 | return 0; | |||
| 1046 | } | |||||
| 1047 | ||||||
| 1048 | # _is_position($value) -> 1 | 0 | |||||
| 1049 | # | |||||
| 1050 | # A GeoJSON position is a list of at least two defined numbers. Anything else | |||||
| 1051 | # in a ring means the ring is damaged, and a damaged ring holds no point. | |||||
| 1052 | sub _is_position { | |||||
| 1053 | 408 | 186 | my ($position) = @_; | |||
| 1054 | 408 405 | 238 255 | return 0 unless ref($position) eq 'ARRAY' && @{$position} >= 2; | |||
| 1055 | 404 | 609 | return (defined $position->[0] && defined $position->[1] | |||
| 1056 | && !ref($position->[0]) && !ref($position->[1])) ? 1 : 0; | |||||
| 1057 | } | |||||
| 1058 | ||||||
| 1059 | sub _in_ring { | |||||
| 1060 | 79 | 6214 | my ($ring, $x, $y) = @_; | |||
| 1061 | 79 74 | 86 89 | return 0 unless ref($ring) eq 'ARRAY' && @{$ring} >= 3; | |||
| 1062 | 71 | 35 | my $inside = 0; | |||
| 1063 | 71 | 59 | return 0 unless _is_position($ring->[-1]); | |||
| 1064 | 70 70 | 38 53 | my ($px, $py) = @{ $ring->[-1] }; | |||
| 1065 | 70 70 | 39 70 | for my $position (@{$ring}) { | |||
| 1066 | 337 | 142 | return 0 unless _is_position($position); | |||
| 1067 | 332 332 | 154 146 | my ($qx, $qy) = @{$position}; | |||
| 1068 | 332 | 339 | if ((($qy > $y) != ($py > $y)) | |||
| 1069 | && ($x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx)) { | |||||
| 1070 | 58 | 35 | $inside = !$inside; | |||
| 1071 | } | |||||
| 1072 | 332 | 175 | ($px, $py) = ($qx, $qy); | |||
| 1073 | } | |||||
| 1074 | 65 | 84 | return $inside ? 1 : 0; | |||
| 1075 | } | |||||
| 1076 | ||||||
| 1077 | 1; | |||||
| 1078 | ||||||