blib/lib/HTML/OSM.pm

filter: Statementstmt 99.6% 625 / 627 Branchbran 96.7% 325 / 336 Conditioncond 82.7% 254 / 307 MC/DCmcdc 66.0% 111 / 168 Subroutinesub 100% 44 / 44 Podpod 100% 10 / 10 totaltotal 91.7% 1369 / 1492 CC 295 SCAR 35.4
CC
295
Cov
95%
onload_render
92.8
_geojson_js
31.0
_point_args
22.0
CRAP 34.6
↑ Summary
1 package HTML::OSM;
2  
3 18 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 18 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 18 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 18 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 18 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 18 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 18 ▶use JSON::MaybeXS qw(decode_json encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 18 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 18 ▶use Object::Configure 0.15;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 18 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 18 ▶use Params::Validate::Strict 0.28;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 18 ▶use POSIX qw(localeconv setlocale LC_NUMERIC);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 18 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 18 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 18 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 18 ▶use URI::Escape qw(uri_escape_utf8);
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 =head1 NAME
22  
23 HTML::OSM - Generate an interactive OpenStreetMap with Leaflet.js
24  
25 =head1 VERSION
26  
27 Version 0.17
28  
29 =cut
30  
31 18 our $VERSION = '0.17';
32  
33 # CDN URLs pinned to tested versions. Override via constructor params to use
34 # a self-hosted copy or a different version.
35 18 Readonly::Scalar my $LEAFLET_CSS_URL => 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
36 18 Readonly::Scalar my $LEAFLET_JS_URL => 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
37 18 Readonly::Scalar my $CLUSTER_JS_URL => 'https://unpkg.com/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js';
38 18 Readonly::Scalar my $CLUSTER_CSS_URL => 'https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.css';
39 18 Readonly::Scalar my $CLUSTER_DEFAULT_CSS_URL => 'https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css';
40 18 Readonly::Scalar my $HEATMAP_JS_URL => 'https://unpkg.com/leaflet.heat@0.2.0/dist/leaflet-heat.js';
41 18 Readonly::Scalar my $GPX_JS_URL => 'https://cdnjs.cloudflare.com/ajax/libs/leaflet-gpx/1.7.0/gpx.min.js';
42 18 Readonly::Scalar my $TILE_URL => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
43 18 Readonly::Scalar my $TILE_ATTRIBUTION => '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
44 18 Readonly::Scalar my $NOMINATIM_HOST => 'nominatim.openstreetmap.org/search';
45 # A Content-Security-Policy nonce: base64 or base64url, so it cannot end the
46 # attribute it is written into.
47 18 Readonly::Scalar my $NONCE_RE => qr{\A[A-Za-z0-9+/_=-]+\z};
48  
49 # Rendering defaults, also used when a stored value is unusable at render time
50 18 Readonly::Scalar my $DEFAULT_ZOOM => 12;
51 18 Readonly::Scalar my $DEFAULT_HEIGHT => '400px';
52 18 Readonly::Scalar my $DEFAULT_WIDTH => '600px';
53 18 Readonly::Scalar my $DEFAULT_RADIUS => 25;
54 18 Readonly::Scalar my $DEFAULT_BLUR => 15;
55  
56 # A CSS length: a number with an optional unit, or 'auto'
57 18 Readonly::Scalar my $CSS_LENGTH => qr/\A(?:auto|[0-9]+(?:\.[0-9]+)?(?:px|%|em|rem|ex|ch|vh|vw|vmin|vmax|pt|pc|cm|mm|in)?)\z/;
58  
59 # WGS-84 valid ranges
60 18 Readonly::Scalar my $LAT_MIN => -90;
61 18 Readonly::Scalar my $LAT_MAX => 90;
62 18 Readonly::Scalar my $LON_MIN => -180;
63 18 Readonly::Scalar my $LON_MAX => 180;
64 18 Readonly::Scalar my $ZOOM_MIN => 0;
65 18 Readonly::Scalar my $ZOOM_MAX => 19;
66  
67 # The highest maxZoom Leaflet supports on a tile layer
68 18 Readonly::Scalar my $MAX_ZOOM_LIMIT => 28;
69  
70 # Circle markers: Leaflet's default path colour, and a hex colour check
71 18 Readonly::Scalar my $DEFAULT_CIRCLE_RADIUS => 8;
72 18 Readonly::Scalar my $DEFAULT_CIRCLE_COLOUR => '#3388ff';
73 18 Readonly::Scalar my $HEX_COLOUR => qr/\A#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\z/;
74  
75 # The key (legend): the corners Leaflet puts a control in, where it goes by
76 # default, what it says when nothing it lists is in view, and the largest
77 # swatch it draws for an entry with a radius, in pixels
78 18 Readonly::Array my @LEGEND_POSITIONS => qw(topright topleft bottomright bottomleft);
79 18 Readonly::Scalar my $DEFAULT_LEGEND_POSITION => 'topright';
80 18 Readonly::Scalar my $DEFAULT_LEGEND_EMPTY => 'Nothing in this view';
81 18 Readonly::Scalar my $LEGEND_SWATCH_MAX => 25;
82 # Where a GeoJSON layer's key goes: away from the marker key and the layer
83 # control, which are top right.
84 18 Readonly::Scalar my $DEFAULT_KEY_POSITION => 'bottomright';
85  
86 =head1 SYNOPSIS
87  
88 use HTML::OSM;
89  
90 my $map = HTML::OSM->new(
91 coordinates => [
92 [37.7749, -122.4194, 'San Francisco'],
93 [undef, undef, 'Paris'],
94 ],
95 zoom => 10,
96 );
97 my ($head, $body) = $map->onload_render();
98  
99 =over 4
100  
101 =item * Caching
102  
103 Geocode results are cached via L<CHI> (default: in-memory, 1-day TTL).
104 Supply your own C<cache> object to persist across processes.
105  
106 =item * Rate-Limiting
107  
108 Set C<min_interval> (seconds) to throttle outbound Nominatim calls
109 and comply with the API fair-use policy.
110  
111 =item * Tile server
112  
113 C<tile_url> replaces the OpenStreetMap tile layer, so a map can use an
114 internal tile server or run on an air-gapped network. It accepts the same
115 Leaflet placeholders as the default, for example
116 C<http://tiles.internal/{z}/{x}/{y}.png>. The attribution remains the
117 OpenStreetMap credit, which is the usual requirement for OSM-derived tiles.
118 The in-page search box still calls Nominatim when a reader uses it; set
119 C<< search => 0 >> to leave it out.
120  
121 =item * Maximum zoom
122  
123 C<max_zoom> (0 to 28) stops readers zooming in further than the tile server
124 has tiles for. Without it, Leaflet allows zooming past the server's coverage
125 and the map shows empty grey tiles. When it is not given, no limit is set.
126  
127 =item * Tile attribution
128  
129 C<tile_attribution> replaces the credit shown in the corner of the map.
130 Set it when the tiles come from a provider that asks for a different
131 credit. The value is HTML that Leaflet renders as it is, so pass only
132 trusted text.
133  
134 =item * Nominatim contact address
135  
136 C<email> is added to every Nominatim request the module makes, as the
137 Nominatim usage policy asks of heavy users. It is not put into the rendered
138 page, so the in-page search box sends no address.
139  
140 =item * Content-Security-Policy
141  
142 C<nonce> puts C<nonce="..."> on every C<< <script> >> that C<onload_render()>
143 writes, the Leaflet and plugin scripts in the head as well as the map's own,
144 so a page whose policy allows scripts only by nonce draws the map without
145 C<'unsafe-inline'>. It must be base64 or base64url (C<A-Z a-z 0-9 + / _ - =>),
146 so it cannot end the attribute; C<onload_render()> checks it again, because a
147 config file or a clone skips C<new()>'s check. Give a fresh one for each
148 response. The C<< <style> >> blocks carry none: the policy's C<style-src>
149 needs C<'unsafe-inline'> anyway for the styles Leaflet sets.
150  
151 =item * Search box
152  
153 By default the rendered page has a search box that sends whatever the reader
154 types to Nominatim, and a button that clears the markers it adds. Set
155 C<< search => 0 >> to leave both out, so that nothing typed on the page leaves
156 the reader's machine. The "Reset Map" button is always included.
157  
158 =item * Fitting the markers
159  
160 By default the map opens at C<zoom> (12) around the middle of the markers,
161 which can leave them all out of view. C<< fit => 1 >> opens it on every
162 pin and circle marker instead, zooming in no further than C<zoom>, and the
163 "Reset Map" button returns there. A centre set with C<center()> wins.
164  
165 =item * Scale and key
166  
167 C<< scale => 1 >> adds a scale bar, and C<legend> a key that lists only what
168 is in view. Both change as the reader zooms; see L</Scale and key>.
169  
170 =back
171  
172 =head1 DESCRIPTION
173  
174 C<HTML::OSM> builds an interactive map from OpenStreetMap tiles and the
175 Leaflet.js library. Give it points as latitude and longitude, as place
176 names, or as geocoder result objects. It can also draw GeoJSON shapes,
177 heatmaps, GPX tracks and choropleth (colour-filled region) layers, and can
178 group nearby markers into clusters. A named GeoJSON layer gets a checkbox on
179 the map, so the reader can turn it on and off.
180  
181 Place names are turned into coordinates by an injected geocoder or, without
182 one, by the Nominatim service. The answers are cached, and requests can be
183 spaced out with C<min_interval>.
184  
185 C<onload_render()> returns two HTML fragments: one for the page's
186 C<< <head> >> and one for its C<< <body> >>. The interface follows
187 L<HTML::GoogleMaps::V3>, so code written for that module needs few changes.
188  
189 =head2 Scale and key
190  
191 my $map = HTML::OSM->new(
192 scale => 1,
193 legend_title => 'Country',
194 legend => [
195 { label => 'England', colour => '#e41a1c', group => 'en' },
196 { label => 'France', colour => '#377eb8', group => 'fr' },
197 { label => '100 people', colour => '#888888', radius => 14 },
198 ],
199 );
200 $map->add_marker([51.5074, -0.1278], html => 'London', group => 'en');
201 $map->add_circle_marker([48.8566, 2.3522], html => 'Paris', group => 'fr',
202 colour => '#377eb8');
203  
204 C<< scale => 1 >> adds Leaflet's scale bar, in kilometres and miles, to the
205 bottom left corner. It is redrawn whenever the map moves or zooms. The
206 default is no scale bar.
207  
208 C<legend> draws a key in a corner of the map: C<legend_position> is
209 C<topright> (the default), C<topleft>, C<bottomright> or C<bottomleft>.
210 C<legend_title> is printed above the entries. Each entry is a hashref:
211  
212 =over 4
213  
214 =item C<label>
215  
216 The text, required. It is written as text, never as HTML.
217  
218 =item C<colour>
219  
220 A hex colour, C<#rgb> or C<#rrggbb>, for the round swatch. The default is
221 C<#3388ff>, Leaflet's own blue.
222  
223 =item C<radius>
224  
225 The swatch's radius in pixels, for a key to the sizes of circle markers.
226 Without it the swatch is 12 pixels across. A large radius is drawn at
227 most 50 pixels across.
228  
229 =item C<group>
230  
231 The entry is listed only while a marker given the same C<group> (through
232 C<add_marker> or C<add_circle_marker>) is inside the map's view. Each time
233 the reader pans or zooms, the key is drawn again, so it shows only the
234 entries for what can be seen. A marker hidden in a cluster still counts.
235 An entry without a group is always listed.
236  
237 =back
238  
239 When no entry is listed, the key says C<legend_empty>, by default
240 "Nothing in this view".
241  
242 C<new()> croaks on an entry it cannot use, and on an unknown position.
243 Values from a config file or a clone skip that check, so C<onload_render()>
244 checks them again. It leaves out a bad entry and uses C<topright> for a bad
245 position, with a warning.
246  
247 =head1 SUBROUTINES/METHODS
248  
249 =head2 new
250  
251 Construct a new C<HTML::OSM> object.
252  
253 my $map = HTML::OSM->new(%params);
254 my $map = HTML::OSM->new(\%params);
255  
256 Both method-style (C<< HTML::OSM->new(...) >>) and function-style
257 (C<HTML::OSM::new(...)>) calls are supported.
258 Calling C<< $existing_obj->new(%overrides) >> performs a shallow clone,
259 merging C<%overrides> onto the existing object's state without re-validating.
260  
261 =head3 API SPECIFICATION
262  
263 =head4 INPUT
264  
265 {
266 cache => { type => object, can => [get, set], optional },
267 cluster => { type => boolean, optional },
268 cluster_css_url => { type => string, optional },
269 cluster_default_css_url => { type => string, optional },
270 cluster_js_url => { type => string, optional },
271 config_file => { type => string, optional },
272 coordinates => { type => arrayref, optional },
273 css_url => { type => string, optional },
274 email => { type => string, optional },
275 fit => { type => boolean, optional },
276 geocoder => { type => object, can => geocode, optional },
277 gpx_js_url => { type => string, optional },
278 heatmap_js_url => { type => string, optional },
279 height => { type => string, optional },
280 host => { type => string, optional },
281 js_url => { type => string, optional },
282 legend => { type => arrayref, optional },
283 legend_empty => { type => string, optional },
284 legend_position => { type => string, enum => [topright, topleft, bottomright, bottomleft], optional },
285 legend_title => { type => string, optional },
286 logger => { type => object, optional },
287 max_zoom => { type => integer, min => 0, max => 28, optional },
288 min_interval => { type => number, min => 0, optional },
289 nonce => { type => string, matches => qr/\A[A-Za-z0-9+\/_=-]+\z/, optional },
290 scale => { type => boolean, optional },
291 search => { type => boolean, optional },
292 tile_attribution => { type => string, optional },
293 tile_url => { type => string, optional },
294 ua => { type => object, optional },
295 width => { type => string, optional },
296 zoom => { type => integer, min => 0, max => 19, optional },
297 }
298  
299 =head4 OUTPUT
300  
301 { type => object, isa => 'HTML::OSM' }
302  
303 =head3 MESSAGES
304  
305 | Message | Meaning / Resolution |
306 |------------------------------------------------|-----------------------------------------------|
307 | (validation error from Params::Validate::Strict) | A param has the wrong type or is out of range |
308 | new(): invalid legend_position: VALUE | Not one of topright, topleft, bottomright, bottomleft |
309 | new(): legend entry N: ... | An entry of legend is unusable; see L</Scale and key> |
310  
311 =head3 PSEUDOCODE
312  
313 1. If $class is neither a package name nor a blessed ref, treat as
314 function-style call: prepend $class back onto @_ and use __PACKAGE__.
315 2. If $class is a blessed ref (clone call): merge override params onto a
316 shallow copy and return immediately, bypassing schema validation.
317 3. Validate all supplied args against the declared schema.
318 4. Merge config-file settings via Object::Configure.
319 5. Resolve the cache: caller-supplied object, or in-memory CHI instance.
320 6. Bless and return with Readonly CDN constants as defaults.
321  
322 =cut
323  
324 sub new
325 577 ▶{
Subroutine new: called CC=12 SCAR=24.9
Pod documented
326 577 my $class = shift;
327  
328 # Function-style call: HTML::OSM::new(key => val).
329 # Perl places the first argument where the class name should be,
330 # so we put it back and set the class explicitly.
331 577 ▶ if(defined($class) && !blessed($class) && !UNIVERSAL::isa($class, __PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $class and not builtin::blessed($class) and not UNIVERSAL::isa($class, __PACKAGE__)) 3 574 577
Condition100%6/6
defined $class and not builtin::blessed($class) and not UNIVERSAL::isa($class, __PACKAGE__)
!ll&&!rl&&r
315433
defined $class and not builtin::blessed($class)
!ll&&!rl&&r
328546
MC/DC100%3/3
defined $class and not builtin::blessed($class) and not UNIVERSAL::isa($class, __PACKAGE__)
defined $class not builtin::blessed($class) not UNIVERSAL::isa($class, __PACKAGE__)
Truth table100%4/4
A and not(B) and not(C)
A= defined $classB= not builtin::blessed($class)C= not UNIVERSAL::isa($class, __PACKAGE__)
ABCresult
0XX0
10X0
1100
1111
332 3 unshift @_, $class;
333 3 $class = __PACKAGE__;
334 }
335  
336 # Clone path: $obj->new(%overrides) — shallow-merge onto the existing
337 # object without re-running schema validation so subclasses can extend.
338 577 ▶ if(blessed($class)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($class)) 28 549 577
339 28 ▶ my $extra = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
244
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
340 28 return bless { %{$class}, %{$extra} }, ref($class);
341 }
342  
343 549 ▶ $class //= __PACKAGE__;
Condition100%2/2
$class //= __PACKAGE__
l!l
5463
MC/DC100%1/1
$class //= __PACKAGE__
$class
Truth table100%2/2
A
A= $class
Aresult
11
00
344  
345 549 ▶ my $params = Params::Validate::Strict::validate_strict({
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
190359
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
346 args => Params::Get::get_params(undef, \@_) || {},
347 schema => {
348 cache => { type => 'object', can => [qw(get set)], optional => 1 },
349 cluster => { type => 'boolean', optional => 1 },
350 cluster_css_url => { type => 'string', optional => 1 },
351 cluster_default_css_url => { type => 'string', optional => 1 },
352 cluster_js_url => { type => 'string', optional => 1 },
353 config_file => { type => 'string', optional => 1 },
354 coordinates => { type => 'arrayref', optional => 1 },
355 css_url => { type => 'string', optional => 1 },
356 email => { type => 'string', optional => 1 },
357 fit => { type => 'boolean', optional => 1 },
358 geocoder => { type => 'object', can => 'geocode', optional => 1 },
359 gpx_js_url => { type => 'string', optional => 1 },
360 heatmap_js_url => { type => 'string', optional => 1 },
361 height => { type => 'string', optional => 1 },
362 host => { type => 'string', optional => 1 },
363 js_url => { type => 'string', optional => 1 },
364 legend => { type => 'arrayref', optional => 1 },
365 legend_empty => { type => 'string', optional => 1 },
366 legend_position => { type => 'string', optional => 1 },
367 legend_title => { type => 'string', optional => 1 },
368 logger => { type => 'object', optional => 1 },
369 max_zoom => { type => 'integer', min => $ZOOM_MIN, max => $MAX_ZOOM_LIMIT, optional => 1 },
370 min_interval => { type => 'number', min => 0, optional => 1 },
371 nonce => { type => 'string', matches => $NONCE_RE, optional => 1 },
372 scale => { type => 'boolean', optional => 1 },
373 search => { type => 'boolean', optional => 1 },
374 tile_attribution => { type => 'string', optional => 1 },
375 tile_url => { type => 'string', optional => 1 },
376 ua => { type => 'object', optional => 1 },
377 width => { type => 'string', optional => 1 },
378 zoom => { type => 'integer', min => $ZOOM_MIN, max => $ZOOM_MAX, optional => 1 },
379 },
380 });
381  
382 # The key is checked here so a mistake is reported where it was made;
383 # onload_render() checks it again, for values from a config file or a clone
384 517 ▶ if(defined(my $position = $params->{'legend_position'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $position = $params->{"legend_position"})) 5 512 517
385 5 ▶ unless(grep { $_ eq $position } @LEGEND_POSITIONS) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $position;} @LEGEND_POSITIONS) 1 4 5
386 1 croak "new(): invalid legend_position: $position";
387 }
388 }
389 516 ▶ _legend_entries($params->{'legend'}, 'new()') if defined($params->{'legend'});
Branch: 1 branch
BranchTrueFalseTotal
if defined $params->{"legend"} 17 499 516
390  
391 # Config file values override programmatic defaults (separation of config and code).
392 509 $params = Object::Configure::configure($class, $params);
393  
394 # Inject the resolved cache so the bless hash spreads it correctly.
395 509 ▶ $params->{cache} //= CHI->new(
Condition66%2/3
$params->{"cache"} //= "CHI"->new("driver", "Memory", "global", 1, "expires_in", "1 day")
l!l&&r!l&&!r
55040
MC/DC0%0/2
$params->{"cache"} //= "CHI"->new("driver", "Memory", "global", 1, "expires_in", "1 day")
$params->{"cache"} "CHI"->new("driver", "Memory", "global", 1, "expires_in", "1 day")
Truth table66%2/3
A //= B
A= $params->{"cache"}B= "CHI"->new("driver", "Memory", "global", 1, "expires_in", "1 day")
ABresult
1X1
011
000
396 driver => 'Memory',
397 global => 1,
398 expires_in => '1 day',
399 );
400  
401 return bless {
402 # Defaults — spread of %{$params} below overrides each one when supplied.
403 coordinates => [],
404 height => $DEFAULT_HEIGHT,
405 host => $NOMINATIM_HOST,
406 width => $DEFAULT_WIDTH,
407 zoom => $DEFAULT_ZOOM,
408 min_interval => 0,
409 last_request => 0,
410 cluster => 0,
411 search => 1,
412 scale => 0,
413 fit => 0,
414 legend_position => $DEFAULT_LEGEND_POSITION,
415 legend_empty => $DEFAULT_LEGEND_EMPTY,
416 css_url => $LEAFLET_CSS_URL,
417 js_url => $LEAFLET_JS_URL,
418 cluster_js_url => $CLUSTER_JS_URL,
419 cluster_css_url => $CLUSTER_CSS_URL,
420 cluster_default_css_url => $CLUSTER_DEFAULT_CSS_URL,
421 heatmap_js_url => $HEATMAP_JS_URL,
422 gpx_js_url => $GPX_JS_URL,
423 tile_url => $TILE_URL,
424 tile_attribution => $TILE_ATTRIBUTION,
425 509 %{$params},
426 }, $class;
427 }
428  
429 =head2 add_marker
430  
431 Add a point marker to the map.
432  
433 $map->add_marker([51.5074, -0.1278], html => 'London');
434 $map->add_marker('Paris, France', html => 'Paris');
435 $map->add_marker($geo_coder_result);
436  
437 Returns 1 on success, 0 if the point cannot be resolved or is out of range.
438 An empty address, or an arrayref that does not hold exactly two elements,
439 also returns 0.
440  
441 =head3 API SPECIFICATION
442  
443 =head4 INPUT
444  
445 point : arrayref [lat, lon] | string address | object with latitude()/longitude()
446 html : string (optional popup label)
447 icon : string (optional icon URL)
448 group : string (optional; the key entry this marker belongs to, see L</Scale and key>)
449  
450 =head4 OUTPUT
451  
452 { type => integer, enum => [0, 1] }
453  
454 =head3 MESSAGES
455  
456 | Message | Meaning / Resolution |
457 |-----------------------------------------|---------------------------------------------|
458 | add_marker(): unknown point type: TYPE | Point is a ref type with no lat/lon methods |
459 | add_marker(): group must be a string | group is a reference |
460 | Skipping invalid coordinate: (LAT, LON) | Warning: the point is not numeric or is out of range; 0 is returned |
461  
462 =head3 EXAMPLES
463  
464 # Coordinate array with a popup label
465 $map->add_marker([51.5074, -0.1278], html => 'London');
466  
467 # String address geocoded via the injected geocoder or Nominatim
468 $map->add_marker('Paris, France', html => 'Paris');
469  
470 # Custom icon URL with a popup
471 $map->add_marker(
472 [40.7128, -74.0060],
473 html => 'New York',
474 icon => 'https://example.com/pin.png',
475 );
476  
477 # Geo::Coder result object that implements latitude()/longitude()
478 my $result = $geocoder->geocode('Berlin, Germany');
479 $map->add_marker($result, html => 'Berlin');
480  
481 # Accumulate several markers, warn on geocode failure
482 for my $city (@cities) {
483 $map->add_marker($city->{coords}, html => $city->{name})
484 or warn "Could not place $city->{name}";
485 }
486  
487 =cut
488  
489 sub add_marker
490 292 ▶{
Subroutine add_marker: called CC=3 SCAR=11.0
Pod documented
491 292 my $self = shift;
492  
493 292 my ($lat, $lon, $params) = $self->_point_args('add_marker', @_);
494 287 my $group = $self->_group_arg('add_marker', $params);
495 286 ▶ return 0 unless defined($lat);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lat 36 250 286
496  
497 # The group is stored only when given, so a marker without one keeps its old shape
498 250 ▶ push @{$self->{coordinates}}, [$lat, $lon, $params->{'html'}, $params->{'icon'}, (defined($group) ? $group : ())];
Branch: 1 branch
BranchTrueFalseTotal
defined $group ? : 3 247 250
499 250 return 1;
500 }
501  
502 =head2 add_circle_marker
503  
504 Add a filled circle whose size in pixels can show a quantity, such as the
505 population of a town.
506  
507 $map->add_circle_marker([51.5074, -0.1278],
508 html => 'London',
509 radius => 12,
510 colour => '#e45c3a',
511 );
512  
513 The point may be anything C<add_marker()> accepts. The radius is in screen
514 pixels, so a circle stays the same size as the reader zooms in and out.
515 With C<< cluster => 1 >>, circles join the same cluster group as the pin
516 markers.
517  
518 Returns 1 on success, 0 if the point cannot be resolved or is out of range.
519  
520 =head3 API SPECIFICATION
521  
522 =head4 INPUT
523  
524 point : arrayref [lat, lon] | string address | object with latitude()/longitude()
525 html : string (optional popup label)
526 radius : number > 0 and < 1e6 (optional, default 8)
527 colour : string hex #rrggbb or #rgb, any case (optional, default '#3388ff')
528 group : string (optional; the key entry this circle belongs to, see L</Scale and key>)
529  
530 =head4 OUTPUT
531  
532 { type => integer, enum => [0, 1] }
533  
534 =head3 MESSAGES
535  
536 | Message | Meaning / Resolution |
537 |-----------------------------------------------------|---------------------------------------------|
538 | add_circle_marker(): radius must be a positive number | radius is 0, negative, 1e6 or more, or not a plain number |
539 | add_circle_marker(): invalid colour: VALUE | colour is not a #rgb or #rrggbb hex string |
540 | add_circle_marker(): unknown point type: TYPE | Point is a ref type with no lat/lon methods |
541 | add_circle_marker(): group must be a string | group is a reference |
542 | Skipping invalid coordinate: (LAT, LON) | Warning: the point is not numeric or is out of range; 0 is returned |
543  
544 =head3 EXAMPLES
545  
546 # Bubble whose area shows the population
547 $map->add_circle_marker([$lat, $lon],
548 html => "$city ($pop)",
549 radius => sqrt($pop / $max_pop) * 30,
550 colour => '#e45c3a',
551 );
552  
553 # Mixed map: pins for offices, circles for market size
554 $map->add_marker([$lat1, $lon1], html => 'HQ');
555 $map->add_circle_marker([$lat2, $lon2], html => 'Market A', radius => 20);
556  
557 =cut
558  
559 sub add_circle_marker
560 43 ▶{
Subroutine add_circle_marker: called CC=10 SCAR=23.1
Pod documented
561 43 my $self = shift;
562  
563 43 my ($lat, $lon, $params) = $self->_point_args('add_circle_marker', @_);
564  
565 # Check the options even when the point is unusable, so a bad radius or
566 # colour is reported whatever the data
567 42 ▶ my $radius = $params->{'radius'} // $DEFAULT_CIRCLE_RADIUS;
Condition66%2/3
$params->{"radius"} // $DEFAULT_CIRCLE_RADIUS
l!l&&r!l&&!r
14280
MC/DC0%0/2
$params->{"radius"} // $DEFAULT_CIRCLE_RADIUS
$params->{"radius"} $DEFAULT_CIRCLE_RADIUS
Truth table66%2/3
A // B
A= $params->{"radius"}B= $DEFAULT_CIRCLE_RADIUS
ABresult
1X1
011
000
568 42 my $checked = _positive_number($radius, undef);
569 42 ▶ if(!defined($checked)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $checked) 8 34 42
570 8 my $msg = 'add_circle_marker(): radius must be a positive number';
571 8 ▶ $self->{logger}->error($msg) if $self->{logger};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"logger"} 8 0 8
572 8 croak $msg;
573 }
574  
575 34 ▶ my $colour = $params->{'colour'} // $DEFAULT_CIRCLE_COLOUR;
Condition66%2/3
$params->{"colour"} // $DEFAULT_CIRCLE_COLOUR
l!l&&r!l&&!r
12220
MC/DC0%0/2
$params->{"colour"} // $DEFAULT_CIRCLE_COLOUR
$params->{"colour"} $DEFAULT_CIRCLE_COLOUR
Truth table66%2/3
A // B
A= $params->{"colour"}B= $DEFAULT_CIRCLE_COLOUR
ABresult
1X1
011
000
576 34 ▶ if(ref($colour) || $colour !~ $HEX_COLOUR) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $colour or not $colour =~ /$HEX_COLOUR/) 7 27 34
Condition100%3/3
ref $colour or not $colour =~ /$HEX_COLOUR/
l!l&&r!l&&!r
1627
MC/DC100%2/2
ref $colour or not $colour =~ /$HEX_COLOUR/
ref $colour not $colour =~ /$HEX_COLOUR/
Truth table100%3/3
A or not(B)
A= ref $colourB= not $colour =~ /$HEX_COLOUR/
ABresult
1X1
011
000
577 7 my $msg = "add_circle_marker(): invalid colour: $colour";
578 7 ▶ $self->{logger}->error($msg) if $self->{logger};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"logger"} 7 0 7
579 7 croak $msg;
580 }
581  
582 27 my $group = $self->_group_arg('add_circle_marker', $params);
583  
584 26 ▶ return 0 unless defined($lat);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lat 3 23 26
585  
586 23 ▶ push @{$self->{circle_markers}}, [$lat, $lon, $params->{'html'}, $checked, lc($colour), (defined($group) ? $group : ())];
Branch: 1 branch
BranchTrueFalseTotal
defined $group ? : 1 22 23
587 23 return 1;
588 }
589  
590 =head2 add_geojson
591  
592 Add a GeoJSON layer to the map.
593  
594 $map->add_geojson(\%data, style => { color => '#ff0000' }, popup => 'name');
595  
596 The first argument may be a hashref/arrayref (GeoJSON structure) or a JSON string.
597 Give it a C<name> and the reader can hide and show it (see L</LAYER CONTROL>).
598 Returns 1 on success.
599  
600 =head3 API SPECIFICATION
601  
602 =head4 INPUT
603  
604 data : hashref | arrayref | string (JSON)
605 style : hashref Leaflet path-style options (color, weight, fillColor, fillOpacity)
606 popup : string Feature property name whose value becomes the popup text
607 name : string Label of the layer's checkbox in the map's layer control
608 show : boolean Whether a named layer is drawn when the map opens (default 1)
609 key : hashref A key to the layer's colours, shown while the layer is
610 (see L</LAYER KEY>):
611 { entries => [ { label, colour }, ... ], title?, position? }
612 bands : string Feature property holding a list of colours, each drawn
613 as a line of its own just inside the outline, side by side
614 (see L</BANDS>)
615  
616 =head4 OUTPUT
617  
618 { type => integer, value => 1 }
619  
620 =head3 MESSAGES
621  
622 | Message | Meaning / Resolution |
623 |-------------------------------------------|---------------------------------|
624 | (JSON parse error) | data string is not valid JSON |
625 | add_geojson: name must be a string | name is a reference or empty |
626 | add_geojson: show must not be a reference | show is a reference |
627 | add_geojson: key ... | key is unusable; the message |
628 | | says which part |
629 | add_geojson: bands must be a string | bands is a reference or empty |
630  
631 =head3 LAYER CONTROL
632  
633 Give a layer a C<name> and the map gains Leaflet's layer control, a box of
634 checkboxes in its top right corner, one for each name, so the reader can hide
635 and show that layer. C<< show => 0 >> starts it hidden: the reader turns it
636 on. As with C<search>, the strings C<false>, C<no> and C<off> are false.
637  
638 Layers given the same name share one checkbox, which is ticked when any of
639 them has C<show> on. A layer with no name is always drawn, whatever C<show>
640 says, because nothing could turn it on. The control is written once, after
641 the last GeoJSON layer, and is left open (not collapsed into an icon), so the
642 reader can see what can be turned on.
643  
644 The name is shown as text: Leaflet writes it into the page as HTML, so it is
645 escaped first, and C<< <b> >> is shown as written.
646  
647 =head3 LAYER KEY
648  
649 $map->add_geojson(\%busy, style => { color => '#d73027' }, name => 'Counties',
650 key => {
651 title => 'Population',
652 entries => [
653 { label => '100,000 or more', colour => '#d73027' },
654 { label => 'under 100,000', colour => '#1a9850' },
655 ],
656 });
657 $map->add_geojson(\%quiet, style => { color => '#1a9850' }, name => 'Counties');
658  
659 C<key> draws a key to a layer's colours in a corner of the map: a short line
660 of each colour, as an outline is drawn, beside its label. It is shown while
661 the layer is: unticking the layer's checkbox hides the key too, and ticking it
662 shows it again. A layer with no name is always drawn, so its key always
663 shows.
664  
665 =over 4
666  
667 =item C<entries>
668  
669 Required, at least one: hashrefs of C<label> (text, required) and C<colour>
670 (C<#rgb> or C<#rrggbb>, required), listed in the order given.
671  
672 =item C<title>
673  
674 Text printed above the entries.
675  
676 =item C<position>
677  
678 C<bottomright> (the default), C<bottomleft>, C<topright> or C<topleft>. The
679 marker key (C<legend>) and the layer control are top right by default.
680  
681 =back
682  
683 Layers that share a name share one key: the first C<key> given for that name.
684 Every text reaches the page as text, never as HTML.
685  
686 =head3 BANDS
687  
688 # Kent's outline is red with blue inside it; Surrey's is all green
689 $kent->{properties}{colours} = [ '#d73027', '#4575b4' ];
690 $surrey->{properties}{colours} = [ '#1a9850' ];
691 $map->add_geojson({ type => 'FeatureCollection', features => [ $kent, $surrey ] },
692 style => { weight => 2, fill => 0 }, bands => 'colours');
693  
694 C<bands> names a feature property that holds a list of colours (C<#rrggbb>).
695 A polygon's outline is then drawn just inside its edge, not along the middle
696 of it, in a line of the width C<style> gives. So where two polygons share a
697 border, each one's colour is on its own side: the border reads as a line twice
698 as wide, a different colour either side, and neither hides the other.
699  
700 A polygon with several colours, for an area that belongs to more than one
701 group, gets a line of each, side by side: the first against the edge, each
702 further one further inside. A feature without the property, or with no colour
703 that can be used, is drawn as C<style> says. Only polygons are banded; a line
704 or point takes the first colour.
705  
706 The lines are cut to the inside of the polygon, which needs Leaflet's default
707 SVG drawing. A map drawn on a canvas shows them uncut, along the middle of the
708 edge, the first colour on top. A popup opens from the outline as before.
709 Neighbours' lines meet exactly only where their shared border is the same in
710 both polygons; outlines simplified one at a time leave small gaps or overlaps.
711  
712 =head3 EXAMPLES
713  
714 # Pre-parsed GeoJSON structure with style and popup property
715 $map->add_geojson(
716 { type => 'FeatureCollection', features => \@features },
717 style => { color => '#ff0000', weight => 2, fillOpacity => 0.4 },
718 popup => 'name',
719 );
720  
721 # Raw JSON string - decoded automatically
722 $map->add_geojson('{"type":"FeatureCollection","features":[]}');
723  
724 # Multiple GeoJSON layers with different styles on the same map
725 $map->add_geojson(\%country_borders, style => { color => '#333333', fillOpacity => 0 });
726 $map->add_geojson(\%river_data, style => { color => '#0099ff', weight => 1 });
727  
728 # County outlines the reader can turn on: hidden at first
729 $map->add_geojson(
730 { type => 'FeatureCollection', features => \@counties },
731 style => { color => '#555555', weight => 1, fill => 0 },
732 popup => 'name',
733 name => 'County boundaries',
734 show => 0,
735 );
736  
737 =cut
738  
739 sub add_geojson
740 115 ▶{
Subroutine add_geojson: called CC=11 SCAR=24.0
Pod documented
741 115 my $self = shift;
742 115 my $data = shift;
743 115 ▶ my $params = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
8035
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
744  
745 # Accept either a pre-parsed structure or a raw JSON string
746 115 ▶ $data = decode_json($data) if !ref($data);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data 9 106 115
747  
748 # The name labels a checkbox, so it must be text; show is a flag.
749 110 ▶ if(defined(my $name = $params->{name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $name = $params->{"name"})) 44 66 110
750 44 ▶ croak 'add_geojson: name must be a string' if ref($name) || !length($name);
Branch: 1 branch
BranchTrueFalseTotal
if ref $name or not length $name 2 42 44
Condition100%3/3
ref $name or not length $name
l!l&&r!l&&!r
1142
MC/DC100%2/2
ref $name or not length $name
ref $name not length $name
Truth table100%3/3
A or not(B)
A= ref $nameB= not length $name
ABresult
1X1
011
000
751 }
752 108 ▶ croak 'add_geojson: show must not be a reference' if ref($params->{show});
Branch: 1 branch
BranchTrueFalseTotal
if ref $params->{"show"} 1 107 108
753 # bands names a feature property, as popup does
754 107 ▶ if(defined(my $bands = $params->{bands})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $bands = $params->{"bands"})) 10 97 107
755 10 ▶ croak 'add_geojson: bands must be a string' if ref($bands) || !length($bands);
Branch: 1 branch
BranchTrueFalseTotal
if ref $bands or not length $bands 2 8 10
Condition100%3/3
ref $bands or not length $bands
l!l&&r!l&&!r
118
MC/DC100%2/2
ref $bands or not length $bands
ref $bands not length $bands
Truth table100%3/3
A or not(B)
A= ref $bandsB= not length $bands
ABresult
1X1
011
000
756 }
757 105 ▶ $params = { %{$params}, key => _layer_key($params->{key}) } if defined($params->{key});
Branch: 1 branch
BranchTrueFalseTotal
if defined $params->{"key"} 28 77 105
758  
759 85 push @{$self->{geojson}}, { data => $data, opts => $params };
760 85 return 1;
761 }
762  
763 =head2 add_heatmap
764  
765 Add a heatmap layer to the map.
766  
767 $map->add_heatmap([[51.5, -0.1, 0.8], [51.6, -0.2, 0.5]], radius => 25);
768  
769 Each point is C<[$lat, $lon]> or C<[$lat, $lon, $intensity]> (intensity: 0-1).
770 Requires the Leaflet.heat plugin (C<heatmap_js_url>).
771 Returns 1 on success.
772  
773 =head3 API SPECIFICATION
774  
775 =head4 INPUT
776  
777 points : arrayref of ([lat, lon] | [lat, lon, intensity])
778 radius : number default 25 (a value that is not a positive number uses the default)
779 blur : number default 15 (a value that is not a positive number uses the default)
780  
781 =head4 OUTPUT
782  
783 { type => integer, value => 1 }
784  
785 =head3 MESSAGES
786  
787 | Message | Meaning / Resolution |
788 |-----------------------------------------|-----------------------------------|
789 | add_heatmap: points must be an arrayref | First argument is not an arrayref |
790  
791 =head3 EXAMPLES
792  
793 # Basic heatmap - [lat, lon] per point
794 $map->add_heatmap([
795 [51.5074, -0.1278],
796 [51.6000, -0.2000],
797 [51.4000, 0.0000],
798 ]);
799  
800 # With intensity values (0..1) and custom radius/blur
801 $map->add_heatmap(
802 [ [51.5, -0.1, 0.9], [51.6, -0.2, 0.5], [51.4, 0.0, 0.2] ],
803 radius => 30,
804 blur => 20,
805 );
806  
807 =cut
808  
809 sub add_heatmap
810 37 ▶{
Subroutine add_heatmap: called CC=3 SCAR=11.0
Pod documented
811 37 my $self = shift;
812 37 my $points = shift;
813 37 ▶ my $params = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
532
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
814  
815 37 ▶ croak 'add_heatmap: points must be an arrayref' unless ref($points) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $points eq "ARRAY" 11 26 37
816  
817 26 push @{$self->{heatmap_layers}}, { points => $points, opts => $params };
818 26 return 1;
819 }
820  
821 =head2 add_gpx
822  
823 Add a GPX track to the map from a URL.
824  
825 $map->add_gpx('https://example.com/track.gpx');
826  
827 The map view is auto-fitted to the track bounds after loading.
828 Requires the leaflet-gpx plugin (C<gpx_js_url>).
829 Returns 1 on success.
830  
831 =head3 API SPECIFICATION
832  
833 =head4 INPUT
834  
835 url : string URL of the GPX file (required)
836  
837 =head4 OUTPUT
838  
839 { type => integer, value => 1 }
840  
841 =head3 MESSAGES
842  
843 | Message | Meaning / Resolution |
844 |--------------------------|--------------------------|
845 | add_gpx: url is required | No URL argument supplied |
846  
847 =head3 EXAMPLES
848  
849 # Add a GPX track from a public URL; the map auto-fits to its bounds
850 $map->add_gpx('https://example.com/route.gpx');
851  
852 # Multiple tracks on the same map
853 $map->add_gpx('https://example.com/morning-run.gpx');
854 $map->add_gpx('https://example.com/evening-walk.gpx');
855  
856 =cut
857  
858 sub add_gpx
859 30 ▶{
Subroutine add_gpx: called CC=2 SCAR=6.9
Pod documented
860 30 my $self = shift;
861 30 my $params = Params::Get::get_params('url', \@_);
862 26 my $url = $params->{'url'};
863  
864 26 ▶ croak 'add_gpx: url is required' unless $url;
Branch: 1 branch
BranchTrueFalseTotal
unless $url 4 22 26
865  
866 22 push @{$self->{gpx_tracks}}, $url;
867 22 return 1;
868 }
869  
870 =head2 add_choropleth
871  
872 Add a choropleth (data-driven colour fill) layer to the map.
873  
874 $map->add_choropleth(
875 \@geojson_features,
876 { England => 100, Scotland => 80, Wales => 60 },
877 key => 'name',
878 scale => ['#ffffcc', '#a1dab4', '#41b6c4', '#2c7fb8', '#253494'],
879 );
880  
881 Colours are pre-computed in Perl and baked into the emitted JavaScript.
882 No extra browser plugin is required.
883 Returns 1 on success.
884  
885 =head3 API SPECIFICATION
886  
887 =head4 INPUT
888  
889 features : arrayref of GeoJSON Feature hashrefs (required)
890 values : hashref { feature_property_value => numeric_value } (required)
891 key : string feature property to match against values (default: 'name')
892 scale : arrayref hex-colour strings low-to-high (default: 5-step YlGnBu)
893  
894 =head4 OUTPUT
895  
896 { type => integer, value => 1 }
897  
898 =head3 MESSAGES
899  
900 | Message | Meaning / Resolution |
901 |---------------------------------------------|-----------------------------------|
902 | add_choropleth: features must be an arrayref | First argument is not an arrayref |
903 | add_choropleth: values must be a hashref | Second argument is not a hashref |
904  
905 =head3 EXAMPLES
906  
907 # Default 5-step YlGnBu scale, key property "name"
908 $map->add_choropleth(
909 \@geojson_features,
910 { England => 100, Scotland => 80, Wales => 60 },
911 );
912  
913 # Custom 3-step scale and a different GeoJSON property as the key
914 $map->add_choropleth(
915 \@geojson_features,
916 { England => 100, Scotland => 80, Wales => 60 },
917 key => 'country',
918 scale => ['#f7fbff', '#6baed6', '#08519c'],
919 );
920  
921 # choropleth-only map - center() must be called explicitly
922 $map->center([54.0, -2.0]);
923 $map->add_choropleth(\@uk_features, \%population_by_region);
924 my ($head, $body) = $map->onload_render();
925  
926 =cut
927  
928 sub add_choropleth
929 48 ▶{
Subroutine add_choropleth: called CC=11 SCAR=24.0
Pod documented
930 48 my $self = shift;
931 48 my $features = shift;
932 48 my $values = shift;
933 48 ▶ my $params = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
1533
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
934  
935 48 ▶ croak 'add_choropleth: features must be an arrayref' unless ref($features) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $features eq "ARRAY" 6 42 48
936 42 ▶ croak 'add_choropleth: values must be a hashref' unless ref($values) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $values eq "HASH" 5 37 42
937  
938 37 ▶ my $key = $params->{key} || 'name';
Condition100%2/2
$params->{'key'} || 'name'
l!l
730
MC/DC100%1/1
$params->{'key'} || 'name'
$params->{'key'}
Truth table100%2/2
A
A= $params->{'key'}
Aresult
11
00
939 37 ▶ my $scale = $params->{scale} || ['#ffffcc', '#a1dab4', '#41b6c4', '#2c7fb8', '#253494'];
Condition100%2/2
$params->{'scale'} || ['#ffffcc', '#a1dab4', '#41b6c4', '#2c7fb8', '#253494']
l!l
928
MC/DC100%1/1
$params->{'scale'} || ['#ffffcc', '#a1dab4', '#41b6c4', '#2c7fb8', '#253494']
$params->{'scale'}
Truth table100%2/2
A
A= $params->{'scale'}
Aresult
11
00
940  
941 # Compute colour index for each feature in Perl so the browser needs no
942 # extra maths — the resulting lookup object is baked into the JS.
943 37 my @sorted_vals = sort { $a <=> $b } values %{$values};
944 37 ▶ my ($min, $max) = ($sorted_vals[0] // 0, $sorted_vals[-1] // 0);
Condition100%4/4
$sorted_vals[0] // 0
l!l
334
$sorted_vals[-1] // 0
l!l
334
MC/DC100%1/1
$sorted_vals[0] // 0
$sorted_vals[0]
MC/DC100%1/1
$sorted_vals[-1] // 0
$sorted_vals[-1]
Truth table100%2/2
A
A= $sorted_vals[0]
Aresult
11
00
Truth table100%2/2
A
A= $sorted_vals[-1]
Aresult
11
00
945 37 ▶ $max = $min + 1 if $max == $min; # avoid division by zero for single-value sets
Branch: 1 branch
BranchTrueFalseTotal
if $max == $min 22 15 37
946  
947 37 my %colors;
948 37 ▶ while(my ($k, $v) = each %{$values}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$values;}) 55 37 92
949 55 my $idx = int(($v - $min) / ($max - $min) * $#{$scale});
950 55 ▶ $idx = $#{$scale} if $idx > $#{$scale};
Branch: 1 branch
BranchTrueFalseTotal
if $idx > $#{$scale;} 1 54 55
951 55 $colors{$k} = $scale->[$idx];
952 }
953  
954 37 push @{$self->{choropleth_layers}}, {
955 features => $features,
956 values => $values,
957 colors => \%colors,
958 key => $key,
959 };
960 37 return 1;
961 }
962  
963 =head2 center
964  
965 Set the map centre to a given point.
966  
967 $map->center([40.7128, -74.0060]);
968 $map->center($geo_object);
969 $map->center('Berlin, Germany');
970  
971 Returns 1 on success, 0 if the point cannot be resolved or is out of range.
972 An empty address also returns 0.
973  
974 =head3 API SPECIFICATION
975  
976 =head4 INPUT
977  
978 point : arrayref [lat, lon] | object with latitude()/longitude() | string address
979  
980 =head4 OUTPUT
981  
982 { type => integer, enum => [0, 1] }
983  
984 =head3 MESSAGES
985  
986 | Message | Meaning / Resolution |
987 |----------------------------------------------------|---------------------------------|
988 | center(): usage: point => [ latitude, longitude ] | No point argument supplied |
989 | center(): point must have latitude and longitude | Arrayref has != 2 elements |
990 | center(): unknown point type: TYPE | Ref type has no lat/lon methods |
991 | Skipping invalid coordinate: (LAT, LON) | Warning: point is not numeric or is out of range; 0 is returned |
992  
993 =head3 EXAMPLES
994  
995 # Coordinate array
996 $map->center([40.7128, -74.0060]);
997  
998 # Object that implements latitude()/longitude() (e.g. a Geo::Coder result)
999 $map->center($geocoder->geocode('Berlin, Germany'));
1000  
1001 # String address resolved via the injected geocoder or Nominatim
1002 $map->center('Eiffel Tower, Paris, France');
1003  
1004 # Required when rendering without point markers (GeoJSON-only, choropleth, etc.)
1005 $map->center([54.0, -2.0]);
1006 $map->add_geojson(\%uk_regions, popup => 'name');
1007 my ($head, $body) = $map->onload_render();
1008  
1009 =cut
1010  
1011 sub center
1012 74 ▶{
Subroutine center: called CC=12 SCAR=24.9
Pod documented
1013 74 my $self = shift;
1014 74 my $params = Params::Get::get_params('point', \@_);
1015 70 my $point = $params->{'point'};
1016  
1017 70 ▶ croak 'center(): usage: point => [ latitude, longitude ]' unless defined($point);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $point 2 68 70
1018  
1019 68 my ($lat, $lon);
1020  
1021 68 ▶ if(ref($point) eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $point eq 'ARRAY') { } 55 13 68
elsif (ref $point and $point->can('latitude')) { } 2 11 13
elsif (not ref $point) { } 7 4 11
1022 croak 'center(): point must have latitude and longitude'
1023 55 ▶ if scalar(@{$point}) != 2;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$point;} != 2 7 48 55
1024 48 ($lat, $lon) = @{$point};
1025 ▶ } elsif(ref($point) && $point->can('latitude')) {
Condition100%3/3
ref $point and $point->can("latitude")
!ll&&!rl&&r
742
MC/DC100%2/2
ref $point and $point->can("latitude")
ref $point $point->can("latitude")
Truth table100%3/3
A and B
A= ref $pointB= $point->can("latitude")
ABresult
0X0
100
111
1026 2 ($lat, $lon) = ($point->latitude(), $point->longitude());
1027 } elsif(!ref($point)) {
1028 # An empty address cannot be resolved
1029 7 ▶ return 0 unless length($point);
Branch: 1 branch
BranchTrueFalseTotal
unless length $point 1 6 7
1030 6 ($lat, $lon) = $self->_fetch_coordinates($point);
1031 } else {
1032 4 my $msg = 'center(): unknown point type: ' . ref($point);
1033 4 ▶ $self->{logger}->error($msg) if $self->{logger};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"logger"} 4 0 4
1034 4 croak $msg;
1035 }
1036  
1037 56 ▶ return 0 unless defined($lat) && defined($lon);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lat and defined $lon 4 52 56
Condition66%2/3
defined $lat and defined $lon
!ll&&!rl&&r
4052
MC/DC50%1/2
defined $lat and defined $lon
defined $lat defined $lon
Truth table66%2/3
A and B
A= defined $latB= defined $lon
ABresult
0X0
100
111
1038  
1039 # Store the text form with a '.' decimal point, whatever the locale
1040 52 ($lat, $lon) = (_num_str($lat), _num_str($lon));
1041 52 ▶ return 0 unless _validate($lat, $lon);
Branch: 1 branch
BranchTrueFalseTotal
unless _validate($lat, $lon) 5 47 52
1042  
1043 47 $self->{'center'} = [$lat, $lon];
1044 47 return 1;
1045 }
1046  
1047 =head2 zoom
1048  
1049 Get or set the zoom level (0 = world, 19 = building).
1050  
1051 $map->zoom(10);
1052 my $z = $map->zoom();
1053  
1054 =head3 API SPECIFICATION
1055  
1056 =head4 INPUT
1057  
1058 { zoom => { type => integer, min => 0, max => 19, optional => 1 } }
1059  
1060 =head4 OUTPUT
1061  
1062 { type => integer, min => 0, max => 19 }
1063  
1064 =head3 MESSAGES
1065  
1066 | Message | Meaning / Resolution |
1067 |------------------------------|-------------------------------------------|
1068 | (Params::Validate::Strict) | zoom is not an integer or is out of range |
1069  
1070 =head3 EXAMPLES
1071  
1072 # Setter: store the zoom level
1073 $map->zoom(14);
1074  
1075 # Getter: retrieve the current level
1076 my $level = $map->zoom();
1077 print "Current zoom: $level\n"; # 14
1078  
1079 # Setter return value equals the new level
1080 my $confirmed = $map->zoom(10);
1081 die 'unexpected' unless $confirmed == 10;
1082  
1083 # Chain: set via new(), read back via zoom()
1084 my $m = HTML::OSM->new(zoom => 6);
1085 $m->zoom($m->zoom() + 2); # nudge up by 2
1086  
1087 =cut
1088  
1089 sub zoom
1090 63 ▶{
Subroutine zoom: called CC=3 SCAR=11.0
Pod documented
1091 63 my $self = shift;
1092  
1093 63 ▶ if(scalar(@_)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 31 32 63
1094 31 my $params = Params::Validate::Strict::validate_strict({
1095 args => Params::Get::get_params('zoom', \@_),
1096 schema => {
1097 zoom => { optional => 1, type => 'integer', min => $ZOOM_MIN, max => $ZOOM_MAX },
1098 },
1099 });
1100 17 ▶ $self->{'zoom'} = $params->{'zoom'} if defined($params->{'zoom'});
Branch: 1 branch
BranchTrueFalseTotal
if defined $params->{"zoom"} 17 0 17
1101 }
1102  
1103 49 return $self->{'zoom'};
1104 }
1105  
1106 =head2 onload_render
1107  
1108 Render the map and return a two-element list suitable for embedding in HTML.
1109  
1110 my ($head_html, $body_html) = $map->onload_render();
1111  
1112 C<$head_html> contains the Leaflet CSS, JavaScript, and plugin assets.
1113 Place it inside C<< <head>...</head> >>.
1114  
1115 C<$body_html> contains the search box (unless C<< search => 0 >>), control
1116 buttons, map C<< <div> >>, and the initialisation C<< <script> >>.
1117 Place it inside C<< <body>...</body> >> where the map should appear.
1118  
1119 The rendered page provides:
1120  
1121 =over 4
1122  
1123 =item * A Nominatim-powered search box that adds temporary markers.
1124 Left out when C<< search => 0 >>.
1125  
1126 =item * A "Clear search markers" button that removes those temporary markers,
1127 leaving static markers (added via C<add_marker>) intact.
1128 Left out when C<< search => 0 >>.
1129  
1130 =item * A "Reset Map" button that returns the view to the initial centre and zoom,
1131 or to every marker when C<< fit => 1 >>.
1132  
1133 =item * A scale bar, when C<< scale => 1 >>.
1134  
1135 =item * A key, when C<legend> has entries, that lists only the groups in view.
1136  
1137 =back
1138  
1139 Values that reach the object without going through C<new()>'s checks (from a
1140 config file or a clone) are checked again here. A C<zoom> that is not an
1141 integer from 0 to 19 is replaced by 12, and a C<width> or C<height> that is
1142 not a CSS length (such as C<600px>, C<100%> or C<auto>) is replaced by the
1143 default. A C<max_zoom> that is not an integer from 0 to 28 is ignored. Each
1144 replacement gives a warning.
1145  
1146 =head3 API SPECIFICATION
1147  
1148 =head4 INPUT
1149  
1150 (none - uses object state)
1151  
1152 =head4 OUTPUT
1153  
1154 { type => list, elements => [string, string] }
1155  
1156 =head3 MESSAGES
1157  
1158 | Message | Meaning / Resolution |
1159 |--------------------------------------------------|---------------------------------------------|
1160 | No map data provided | No markers, circle markers, GeoJSON, heatmap, GPX, or choropleth added yet |
1161 | center() must be called when no point markers are provided | Non-marker-only render needs explicit centre |
1162 | Skipping invalid coordinate: (LAT, LON) | Warning: a marker is not numeric or out of range; it is left off the map |
1163 | onload_render: invalid nonce | nonce from a config file or clone is not base64 or base64url |
1164 | onload_render: invalid zoom 'Z', using 12 | Warning: zoom from a config file or clone is out of range |
1165 | onload_render: invalid max_zoom 'Z', ignoring it | Warning: max_zoom from a config file or clone is not an integer from 0 to 28 |
1166 | onload_render: invalid width 'W', using 600px | Warning: width is not a CSS length |
1167 | onload_render: invalid height 'H', using 400px | Warning: height is not a CSS length |
1168 | onload_render: invalid legend_position 'P', using topright | Warning: legend_position from a config file or clone is not a corner |
1169 | onload_render: legend entry N: ...; leaving it out of the key | Warning: a legend entry from a config file or clone is unusable |
1170 | onload_render: legend must be an arrayref; leaving it out of the key | Warning: legend from a config file or clone is not an arrayref; no key is drawn |
1171 | _fetch_coordinates: failed to decode Nominatim response: ERROR | Warning: Nominatim returned something that is not JSON; the marker is skipped |
1172 | _fetch_coordinates: unrecognised geocoder result type: TYPE | Warning: the injected geocoder returned an unknown type; the marker is skipped |
1173  
1174 =head3 EXAMPLES
1175  
1176 # Minimal: one marker, embed in a CGI response
1177 use HTML::OSM;
1178 my $map = HTML::OSM->new(zoom => 12);
1179 $map->add_marker([51.5074, -0.1278], html => 'London');
1180 my ($head, $body) = $map->onload_render();
1181 print "Content-Type: text/html\n\n";
1182 print "<html><head>$head</head><body>$body</body></html>\n";
1183  
1184 # Mixed layers: markers + GeoJSON, explicit center
1185 $map->center([51.5, -0.1]);
1186 $map->add_geojson(\%borough_data, popup => 'name', style => { color => '#333' });
1187 $map->add_marker([51.5074, -0.1278], html => 'City of London');
1188 my ($head_html, $body_html) = $map->onload_render();
1189  
1190 # Template Toolkit integration
1191 $tt->process('map.tt', {
1192 map_head => scalar(($map->onload_render())[0]),
1193 map_body => scalar(($map->onload_render())[1]),
1194 });
1195  
1196 =head3 PSEUDOCODE
1197  
1198 1. Gather all data layers; croak if none populated.
1199 2. Geocode/validate each coordinate tuple; discard invalids with a warning.
1200 A tuple with no coordinates and no address is discarded.
1201 Check circle markers the same way.
1202 Re-check zoom, max_zoom, width and height; fall back with a warning.
1203 3. Determine map centre: caller-supplied > computed midpoint of the bounds
1204 of the pin and circle markers. With fit and no caller centre, also
1205 fit the view to those bounds, at most at zoom, on load and on reset.
1206 Croak if neither is available.
1207 4. Build <head>: Leaflet CSS + JS; inject cluster/heatmap/GPX plugin assets
1208 only when the corresponding layer type is present.
1209 5. Build <body>: search box and clear-search button (when search is on),
1210 reset button, map <div>.
1211 6. Initialise Leaflet map, tile layer (with maxZoom when max_zoom is set),
1212 and the searchMarkers array when search is on.
1213 7. Emit JS for each pin and circle marker (via one clusterGroup when
1214 cluster is set), then the scale bar when scale is set, then the key
1215 when legend has entries: its entries, the groups and where each
1216 grouped marker is, redrawn on every moveend.
1217 8. Emit JS for each GeoJSON, heatmap, GPX, and choropleth layer.
1218 9. Attach event listeners: reset-view, and when search is on,
1219 clear-search-markers and search-on-Enter.
1220 10. Return ($head, $body).
1221  
1222 =cut
1223  
1224 sub onload_render
1225 262 ▶{
Subroutine onload_render: called CC=88 SCAR=45.3
Pod documented
1226 262 my $self = shift;
1227  
1228 262 my $height = _css_length('height', $self->{'height'}, $DEFAULT_HEIGHT);
1229 262 my $width = _css_length('width', $self->{'width'}, $DEFAULT_WIDTH);
1230 262 my $zoom = $self->{'zoom'};
1231 262 ▶ my $coordinates = $self->{coordinates} || [];
Condition50%1/2
$self->{'coordinates'} || []
l!l
2620
MC/DC0%0/1
$self->{'coordinates'} || []
$self->{'coordinates'}
Truth table50%1/2
A
A= $self->{'coordinates'}
Aresult
11
00
1232 262 ▶ my $geojson_layers = $self->{geojson} || [];
Condition100%2/2
$self->{'geojson'} || []
l!l
60202
MC/DC100%1/1
$self->{'geojson'} || []
$self->{'geojson'}
Truth table100%2/2
A
A= $self->{'geojson'}
Aresult
11
00
1233 262 ▶ my $heatmap_layers = $self->{heatmap_layers} || [];
Condition100%2/2
$self->{'heatmap_layers'} || []
l!l
16246
MC/DC100%1/1
$self->{'heatmap_layers'} || []
$self->{'heatmap_layers'}
Truth table100%2/2
A
A= $self->{'heatmap_layers'}
Aresult
11
00
1234 262 ▶ my $gpx_tracks = $self->{gpx_tracks} || [];
Condition100%2/2
$self->{'gpx_tracks'} || []
l!l
13249
MC/DC100%1/1
$self->{'gpx_tracks'} || []
$self->{'gpx_tracks'}
Truth table100%2/2
A
A= $self->{'gpx_tracks'}
Aresult
11
00
1235 262 ▶ my $choropleth_layers = $self->{choropleth_layers} || [];
Condition100%2/2
$self->{'choropleth_layers'} || []
l!l
19243
MC/DC100%1/1
$self->{'choropleth_layers'} || []
$self->{'choropleth_layers'}
Truth table100%2/2
A
A= $self->{'choropleth_layers'}
Aresult
11
00
1236 262 ▶ my $circle_markers = $self->{circle_markers} || [];
Condition100%2/2
$self->{'circle_markers'} || []
l!l
21241
MC/DC100%1/1
$self->{'circle_markers'} || []
$self->{'circle_markers'}
Truth table100%2/2
A
A= $self->{'circle_markers'}
Aresult
11
00
1237  
1238 262 ▶ unless(@$coordinates || @$geojson_layers || @$heatmap_layers
Branch: 1 branch
BranchTrueFalseTotal
unless (@$coordinates or @$geojson_layers or @$heatmap_layers or @$gpx_tracks or @$choropleth_layers or @$circle_markers) 8 254 262
Condition93%14/15
@$coordinates or @$geojson_layers or @$heatmap_layers or @$gpx_tracks or @$choropleth_layers or @$circle_markers
l!l&&r!l&&!r
241138
@$coordinates or @$geojson_layers or @$heatmap_layers or @$gpx_tracks or @$choropleth_layers
l!l&&r!l&&!r
2231821
@$coordinates or @$geojson_layers or @$heatmap_layers or @$gpx_tracks
l!l&&r!l&&!r
223039
@$coordinates or @$geojson_layers or @$heatmap_layers
l!l&&r!l&&!r
221239
@$coordinates or @$geojson_layers
l!l&&r!l&&!r
2031841
MC/DC83%5/6
@$coordinates or @$geojson_layers or @$heatmap_layers or @$gpx_tracks or @$choropleth_layers or @$circle_markers
@$coordinates @$geojson_layers @$heatmap_layers @$gpx_tracks @$choropleth_layers @$circle_markers
Truth table85%6/7
A or B or C or D or E or F
A= @$coordinatesB= @$geojson_layersC= @$heatmap_layersD= @$gpx_tracksE= @$choropleth_layersF= @$circle_markers
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
1239 || @$gpx_tracks || @$choropleth_layers
1240 || @$circle_markers) {
1241 8 ▶ $self->{logger}->error('No map data provided') if $self->{logger};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"logger"} 8 0 8
1242 8 croak 'No map data provided';
1243 }
1244  
1245 # A nonce from a config file or a clone skipped new()'s check, and is
1246 # written into an attribute.
1247 254 my $nonce_attr = '';
1248 254 ▶ if(defined(my $nonce = $self->{'nonce'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $nonce = $self->{"nonce"})) 18 236 254
1249 18 ▶ croak 'onload_render: invalid nonce' if ref($nonce) || $nonce !~ $NONCE_RE;
Branch: 1 branch
BranchTrueFalseTotal
if ref $nonce or not $nonce =~ /$NONCE_RE/ 1 17 18
Condition66%2/3
ref $nonce or not $nonce =~ /$NONCE_RE/
l!l&&r!l&&!r
0117
MC/DC50%1/2
ref $nonce or not $nonce =~ /$NONCE_RE/
ref $nonce not $nonce =~ /$NONCE_RE/
Truth table66%2/3
A or not(B)
A= ref $nonceB= not $nonce =~ /$NONCE_RE/
ABresult
1X1
011
000
1250 17 $nonce_attr = qq{ nonce="$nonce"};
1251 }
1252  
1253 # Config-file and clone values skip new()'s schema, so check zoom again
1254 # before it is put into the JavaScript.
1255 253 ▶ if(!defined($zoom) || $zoom !~ /\A[0-9]+\z/ || $zoom < $ZOOM_MIN || $zoom > $ZOOM_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $zoom && $zoom =~ /\A[0-9]+\z/ or $zoom < $ZOOM_MIN or $zoom > $ZOOM_MAX) 2 251 253
Condition77%7/9
not defined $zoom && $zoom =~ /\A[0-9]+\z/ or $zoom < $ZOOM_MIN or $zoom > $ZOOM_MAX
l!l&&r!l&&!r
11251
not defined $zoom && $zoom =~ /\A[0-9]+\z/ or $zoom < $ZOOM_MIN
l!l&&r!l&&!r
10252
defined $zoom && $zoom =~ /\A[0-9]+\z/
!ll&&!rl&&r
01252
MC/DC50%2/4
not defined $zoom && $zoom =~ /\A[0-9]+\z/ or $zoom < $ZOOM_MIN or $zoom > $ZOOM_MAX
defined $zoom $zoom =~ /\A[0-9]+\z/ $zoom < $ZOOM_MIN $zoom > $ZOOM_MAX
Truth table60%3/5
not(A && B) or C or D
A= defined $zoomB= $zoom =~ /\A[0-9]+\z/C= $zoom < $ZOOM_MIND= $zoom > $ZOOM_MAX
ABCDresult
0XXX1
10XX1
111X1
11011
11000
1256 2 ▶ carp sprintf("onload_render: invalid zoom '%s', using %d", $zoom // 'undef', $DEFAULT_ZOOM);
Condition50%1/2
$zoom // "undef"
l!l
20
MC/DC0%0/1
$zoom // "undef"
$zoom
Truth table50%1/2
A
A= $zoom
Aresult
11
00
1257 2 $zoom = $DEFAULT_ZOOM;
1258 }
1259  
1260 # Geocode address strings; validate and discard bad numeric pairs.
1261 253 my @valid_coordinates;
1262 253 for my $coord (@$coordinates) {
1263 229 my ($lat, $lon, $label, $icon_url, $group) = @$coord;
1264 229 ▶ if(!defined $lat || !defined $lon) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $lat and defined $lon) 4 225 229
Condition66%2/3
defined $lat and defined $lon
!ll&&!rl&&r
40225
MC/DC50%1/2
defined $lat and defined $lon
defined $lat defined $lon
Truth table66%2/3
A and B
A= defined $latB= defined $lon
ABresult
0X0
100
111
1265 # No coordinates and no address: nothing to look up
1266 4 ▶ next unless defined($label) && length($label);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $label and length $label 1 3 4
Condition66%2/3
defined $label and length $label
!ll&&!rl&&r
103
MC/DC50%1/2
defined $label and length $label
defined $label length $label
Truth table66%2/3
A and B
A= defined $labelB= length $label
ABresult
0X0
100
111
1267 3 ($lat, $lon) = $self->_fetch_coordinates($label);
1268 }
1269 # Validate ALL coordinates here — including geocoder-returned ones.
1270 # A compromised geocoder or Nominatim response could return a crafted
1271 # lat/lon string that would inject JS if embedded without validation.
1272 228 ▶ next unless defined($lat) && defined($lon);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lat and defined $lon 0 228 228
Condition33%1/3
defined $lat and defined $lon
!ll&&!rl&&r
00228
MC/DC0%0/2
defined $lat and defined $lon
defined $lat defined $lon
Truth table33%1/3
A and B
A= defined $latB= defined $lon
ABresult
0X0
100
111
1273 228 ($lat, $lon) = (_num_str($lat), _num_str($lon));
1274 228 ▶ next unless _validate($lat, $lon);
Branch: 1 branch
BranchTrueFalseTotal
unless _validate($lat, $lon) 6 222 228
1275 222 push @valid_coordinates, [$lat, $lon, $label, $icon_url, _group_value($group)];
1276 }
1277  
1278 # add_circle_marker checked these, but a clone can bring in anything
1279 253 my @valid_circles;
1280 253 for my $circle (@$circle_markers) {
1281 25 my ($lat, $lon, $label, $radius, $colour, $group) = @$circle;
1282 25 ▶ next unless defined($lat) && defined($lon);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lat and defined $lon 0 25 25
Condition33%1/3
defined $lat and defined $lon
!ll&&!rl&&r
0025
MC/DC0%0/2
defined $lat and defined $lon
defined $lat defined $lon
Truth table33%1/3
A and B
A= defined $latB= defined $lon
ABresult
0X0
100
111
1283 25 ($lat, $lon) = (_num_str($lat), _num_str($lon));
1284 25 ▶ next unless _validate($lat, $lon);
Branch: 1 branch
BranchTrueFalseTotal
unless _validate($lat, $lon) 1 24 25
1285 24 $radius = _positive_number($radius, $DEFAULT_CIRCLE_RADIUS);
1286 24 ▶ $colour = $DEFAULT_CIRCLE_COLOUR unless defined($colour) && !ref($colour) && $colour =~ $HEX_COLOUR;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $colour and not ref $colour and $colour =~ /$HEX_COLOUR/ 1 23 24
Condition50%3/6
defined $colour and not ref $colour and $colour =~ /$HEX_COLOUR/
!ll&&!rl&&r
0123
defined $colour and not ref $colour
!ll&&!rl&&r
0024
MC/DC33%1/3
defined $colour and not ref $colour and $colour =~ /$HEX_COLOUR/
defined $colour not ref $colour $colour =~ /$HEX_COLOUR/
Truth table50%2/4
A and not(B) and C
A= defined $colourB= not ref $colourC= $colour =~ /$HEX_COLOUR/
ABCresult
0XX0
10X0
1100
1111
1287 24 push @valid_circles, [$lat, $lon, $label, $radius, lc($colour), _group_value($group)];
1288 }
1289  
1290 # Only an integer in Leaflet's range is put into the tile layer options
1291 253 my $max_zoom = $self->{'max_zoom'};
1292 253 ▶ if(defined($max_zoom) && ($max_zoom !~ /\A[0-9]+\z/ || $max_zoom > $MAX_ZOOM_LIMIT)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $max_zoom and !($max_zoom =~ /\A[0-9]+\z/) || $max_zoom > $MAX_ZOOM_LIMIT) 4 249 253
Condition100%6/6
defined $max_zoom and !($max_zoom =~ /\A[0-9]+\z/) || $max_zoom > $MAX_ZOOM_LIMIT
!ll&&!rl&&r
24364
not $max_zoom =~ /\A[0-9]+\z/ or $max_zoom > $MAX_ZOOM_LIMIT
l!l&&r!l&&!r
316
MC/DC100%3/3
defined $max_zoom and !($max_zoom =~ /\A[0-9]+\z/) || $max_zoom > $MAX_ZOOM_LIMIT
defined $max_zoom not $max_zoom =~ /\A[0-9]+\z/ $max_zoom > $MAX_ZOOM_LIMIT
Truth table100%4/4
A and not(B) or C
A= defined $max_zoomB= not $max_zoom =~ /\A[0-9]+\z/C= $max_zoom > $MAX_ZOOM_LIMIT
ABCresult
0XX0
1000
11X1
1011
1293 4 carp "onload_render: invalid max_zoom '$max_zoom', ignoring it";
1294 4 undef $max_zoom;
1295 }
1296 253 ▶ my $max_zoom_js = defined($max_zoom) ? ",\n\t\t\t\tmaxZoom: $max_zoom" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $max_zoom ? : 6 247 253
1297  
1298 # A config file can give the words 'false', 'no' or 'off'
1299 253 my $search = $self->{'search'};
1300 253 ▶ $search = 0 if defined($search) && $search =~ /\A(?:false|no|off)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $search and $search =~ /\A(?:false|no|off)\z/i 5 248 253
Condition66%2/3
defined $search and $search =~ /\A(?:false|no|off)\z/i
!ll&&!rl&&r
02485
MC/DC50%1/2
defined $search and $search =~ /\A(?:false|no|off)\z/i
defined $search $search =~ /\A(?:false|no|off)\z/i
Truth table66%2/3
A and B
A= defined $searchB= $search =~ /\A(?:false|no|off)\z/i
ABresult
0X0
100
111
1301  
1302 # The scale bar and the key, checked again like the rest
1303 253 my $scale = $self->{'scale'};
1304 253 ▶ $scale = 0 if defined($scale) && $scale =~ /\A(?:false|no|off)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $scale and $scale =~ /\A(?:false|no|off)\z/i 1 252 253
Condition66%2/3
defined $scale and $scale =~ /\A(?:false|no|off)\z/i
!ll&&!rl&&r
02521
MC/DC50%1/2
defined $scale and $scale =~ /\A(?:false|no|off)\z/i
defined $scale $scale =~ /\A(?:false|no|off)\z/i
Truth table66%2/3
A and B
A= defined $scaleB= $scale =~ /\A(?:false|no|off)\z/i
ABresult
0X0
100
111
1305 253 ▶ my @legend = defined($self->{'legend'}) ? _legend_entries($self->{'legend'}) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'legend'} ? : 11 242 253
1306 253 ▶ my $legend_position = $self->{'legend_position'} // $DEFAULT_LEGEND_POSITION;
Condition33%1/3
$self->{"legend_position"} // $DEFAULT_LEGEND_POSITION
l!l&&r!l&&!r
25300
MC/DC0%0/2
$self->{"legend_position"} // $DEFAULT_LEGEND_POSITION
$self->{"legend_position"} $DEFAULT_LEGEND_POSITION
Truth table33%1/3
A // B
A= $self->{"legend_position"}B= $DEFAULT_LEGEND_POSITION
ABresult
1X1
011
000
1307 253 ▶ unless(!ref($legend_position) && grep { $_ eq $legend_position } @LEGEND_POSITIONS) {
Branch: 1 branch
BranchTrueFalseTotal
unless (not ref $legend_position and grep {$_ eq $legend_position;} @LEGEND_POSITIONS) 1 252 253
Condition66%2/3
not ref $legend_position and grep {$_ eq $legend_position;} @LEGEND_POSITIONS
!ll&&!rl&&r
01252
MC/DC50%1/2
not ref $legend_position and grep {$_ eq $legend_position;} @LEGEND_POSITIONS
not ref $legend_position grep {$_ eq $legend_position;} @LEGEND_POSITIONS
Truth table66%2/3
not(A) and B
A= not ref $legend_positionB= grep {$_ eq $legend_position;} @LEGEND_POSITIONS
ABresult
0X0
100
111
1308 1 carp "onload_render: invalid legend_position '$legend_position', using $DEFAULT_LEGEND_POSITION";
1309 1 $legend_position = $DEFAULT_LEGEND_POSITION;
1310 }
1311  
1312 # fit => 1 opens the map on every marker rather than at zoom around their
1313 # midpoint; a centre the caller set wins over it
1314 253 my $fit = $self->{'fit'};
1315 253 ▶ $fit = 0 if defined($fit) && $fit =~ /\A(?:false|no|off)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $fit and $fit =~ /\A(?:false|no|off)\z/i 1 252 253
Condition66%2/3
defined $fit and $fit =~ /\A(?:false|no|off)\z/i
!ll&&!rl&&r
02521
MC/DC50%1/2
defined $fit and $fit =~ /\A(?:false|no|off)\z/i
defined $fit $fit =~ /\A(?:false|no|off)\z/i
Truth table66%2/3
A and B
A= defined $fitB= $fit =~ /\A(?:false|no|off)\z/i
ABresult
0X0
100
111
1316 253 my $fit_js;
1317  
1318 # Determine map centre: caller-set wins; else compute from marker bounds.
1319 253 my ($center_lat, $center_lon);
1320 253 ▶ if($self->{'center'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'center'}) { } 40 213 253
elsif (@valid_coordinates or @valid_circles) { } 205 8 213
1321 40 ($center_lat, $center_lon) = @{$self->{'center'}};
1322 ▶ } elsif(@valid_coordinates || @valid_circles) {
Condition100%3/3
@valid_coordinates or @valid_circles
l!l&&r!l&&!r
192138
MC/DC100%2/2
@valid_coordinates or @valid_circles
@valid_coordinates @valid_circles
Truth table100%3/3
A or B
A= @valid_coordinatesB= @valid_circles
ABresult
1X1
011
000
1323 205 my ($min_lat, $min_lon, $max_lat, $max_lon) = (90, 180, -90, -180);
1324 205 for my $c (@valid_coordinates, @valid_circles) {
1325 # Convert with _num_val: some perls read '51.5074' as 51 under de_DE
1326 236 my ($lat, $lon) = (_num_val($c->[0]), _num_val($c->[1]));
1327 236 ▶ $min_lat = $lat if $lat < $min_lat;
Branch: 1 branch
BranchTrueFalseTotal
if $lat < $min_lat 228 8 236
1328 236 ▶ $max_lat = $lat if $lat > $max_lat;
Branch: 1 branch
BranchTrueFalseTotal
if $lat > $max_lat 208 28 236
1329 236 ▶ $min_lon = $lon if $lon < $min_lon;
Branch: 1 branch
BranchTrueFalseTotal
if $lon < $min_lon 210 26 236
1330 236 ▶ $max_lon = $lon if $lon > $max_lon;
Branch: 1 branch
BranchTrueFalseTotal
if $lon > $max_lon 225 11 236
1331 }
1332 205 $center_lat = ($min_lat + $max_lat) / 2;
1333 205 $center_lon = ($min_lon + $max_lon) / 2;
1334 # The zoom is the most it may zoom in, so one marker is not shown
1335 # at street level
1336 205 ▶ if($fit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fit) 1 204 205
1337 1 my ($south, $west, $north, $east) = map { _num_str($_) } ($min_lat, $min_lon, $max_lat, $max_lon);
1338 1 $fit_js = "map.fitBounds([[$south, $west], [$north, $east]], { padding: [30, 30], maxZoom: $zoom });";
1339 }
1340 } else {
1341 8 croak 'center() must be called when no point markers are provided';
1342 }
1343 # The midpoint is a new number, so it needs the same treatment as markers
1344 245 ($center_lat, $center_lon) = (_num_str($center_lat), _num_str($center_lon));
1345  
1346 # --- <head> ---
1347 245 my %url = map { $_ => _html_attr($self->{$_}) }
1348 qw(css_url js_url cluster_css_url cluster_default_css_url cluster_js_url heatmap_js_url gpx_js_url);
1349 245 my $head = qq{
1350 <link rel="stylesheet" href="$url{css_url}" />
1351 <script$nonce_attr src="$url{js_url}"></script>
1352 };
1353  
1354 245 ▶ if($self->{cluster}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cluster"}) 13 232 245
1355 13 $head .= qq{
1356 <link rel="stylesheet" href="$url{cluster_css_url}" />
1357 <link rel="stylesheet" href="$url{cluster_default_css_url}" />
1358 <script$nonce_attr src="$url{cluster_js_url}"></script>
1359 };
1360 }
1361 245 ▶ $head .= qq{\t\t<script$nonce_attr src="$url{heatmap_js_url}"></script>\n} if @$heatmap_layers;
Branch: 1 branch
BranchTrueFalseTotal
if @$heatmap_layers 15 230 245
1362 245 ▶ $head .= qq{\t\t<script$nonce_attr src="$url{gpx_js_url}"></script>\n} if @$gpx_tracks;
Branch: 1 branch
BranchTrueFalseTotal
if @$gpx_tracks 12 233 245
1363  
1364 245 ▶ if($search) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search) { } 196 49 245
1365 196 $head .= qq{
1366 <style>
1367 #map { width: $width; height: $height; }
1368 #search-box { margin: 10px; padding: 5px; }
1369 #reset-button, #clear-search-button { margin: 10px; padding: 5px; cursor: pointer; }
1370 </style>
1371 };
1372 } else {
1373 49 $head .= qq{
1374 <style>
1375 #map { width: $width; height: $height; }
1376 #reset-button { margin: 10px; padding: 5px; cursor: pointer; }
1377 </style>
1378 };
1379 }
1380  
1381 # --- <body> ---
1382 245 my $tile_url = _js_string($self->{tile_url});
1383 245 my $tile_attribution = _js_string($self->{tile_attribution});
1384 245 my $body = '';
1385 245 ▶ if($search) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search) 196 49 245
1386 196 $body .= qq{
1387 <input type="text" id="search-box" placeholder="Enter location">
1388 <button id="clear-search-button">Clear search markers</button>};
1389 }
1390 245 $body .= qq{
1391 <button id="reset-button">Reset Map</button>
1392 <div id="map"></div>
1393 <script$nonce_attr>
1394 var map = L.map('map').setView([$center_lat, $center_lon], $zoom);
1395 L.tileLayer('$tile_url', {
1396 attribution: '$tile_attribution'$max_zoom_js
1397 }).addTo(map);
1398 };
1399 245 ▶ $body .= "\t\t\t$fit_js\n" if $fit_js;
Branch: 1 branch
BranchTrueFalseTotal
if $fit_js 1 244 245
1400 245 ▶ $body .= "\n\t\t\tvar searchMarkers = [];\n" if $search;
Branch: 1 branch
BranchTrueFalseTotal
if $search 196 49 245
1401  
1402 # Point and circle markers — optionally grouped into one cluster layer.
1403 245 ▶ my $clustered = $self->{cluster} && (@valid_coordinates || @valid_circles);
Condition66%4/6
$self->{'cluster'} && (@valid_coordinates || @valid_circles)
!ll&&!rl&&r
232013
@valid_coordinates or @valid_circles
l!l&&r!l&&!r
1210
MC/DC33%1/3
$self->{'cluster'} && (@valid_coordinates || @valid_circles)
$self->{'cluster'} @valid_coordinates @valid_circles
Truth table75%3/4
A && B or C
A= $self->{'cluster'}B= @valid_coordinatesC= @valid_circles
ABCresult
0XX0
1000
11X1
1011
1404 245 ▶ $body .= "\t\t\tvar clusterGroup = L.markerClusterGroup();\n" if $clustered;
Branch: 1 branch
BranchTrueFalseTotal
if $clustered 13 232 245
1405 245 ▶ if(@valid_coordinates) {
Branch: 1 branch
BranchTrueFalseTotal
if (@valid_coordinates) 199 46 245
1406  
1407 199 for my $coord (@valid_coordinates) {
1408 222 my ($lat, $lon, $label, $icon_url) = @$coord;
1409 222 my $js_label = _js_string($label);
1410 222 ▶ if($icon_url) {
Branch: 2 branches
BranchTrueFalseTotal
if ($icon_url) { } 4 218 222
elsif ($self->{'cluster'}) { } 18 200 218
1411 4 my $js_icon = _js_string($icon_url);
1412 my $add_cmd = $self->{cluster}
1413 4 ▶ ? 'clusterGroup.addLayer(m);'
Branch: 1 branch
BranchTrueFalseTotal
$self->{'cluster'} ? : 2 2 4
1414 : 'm.addTo(map);';
1415 4 $body .= qq{
1416 (function() {
1417 var icon = L.icon({ iconUrl: '$js_icon', iconAnchor: [16,32], popupAnchor: [0,-32] });
1418 var m = L.marker([$lat, $lon], { icon: icon }).bindPopup('$js_label');
1419 $add_cmd
1420 })();
1421 };
1422 } elsif($self->{cluster}) {
1423 18 $body .= "\t\t\tclusterGroup.addLayer(L.marker([$lat, $lon]).bindPopup('$js_label'));\n";
1424 } else {
1425 200 $body .= "\t\t\tL.marker([$lat, $lon]).addTo(map).bindPopup('$js_label');\n";
1426 }
1427 }
1428 }
1429  
1430 245 for my $circle (@valid_circles) {
1431 24 my ($lat, $lon, $label, $radius, $colour) = @$circle;
1432 24 ▶ my $popup = (defined($label) && length($label))
Branch: 1 branch
BranchTrueFalseTotal
defined $label && length $label ? : 6 18 24
Condition66%2/3
defined $label and length $label
!ll&&!rl&&r
1806
MC/DC50%1/2
defined $label and length $label
defined $label length $label
Truth table66%2/3
A and B
A= defined $labelB= length $label
ABresult
0X0
100
111
1433 ? ".bindPopup('" . _js_string($label) . "')"
1434 : '';
1435 24 my $circle_js = "L.circleMarker([$lat, $lon], { radius: $radius, color: '$colour', fillColor: '$colour', fillOpacity: 0.7 })$popup";
1436 24 ▶ if($self->{cluster}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'cluster'}) { } 2 22 24
1437 2 $body .= "\t\t\tclusterGroup.addLayer($circle_js);\n";
1438 } else {
1439 22 $body .= "\t\t\t$circle_js.addTo(map);\n";
1440 }
1441 }
1442  
1443 245 ▶ $body .= "\t\t\tmap.addLayer(clusterGroup);\n" if $clustered;
Branch: 1 branch
BranchTrueFalseTotal
if $clustered 13 232 245
1444  
1445 # Leaflet's scale bar redraws itself as the map moves and zooms
1446 245 ▶ $body .= "\t\t\tL.control.scale().addTo(map);\n" if $scale;
Branch: 1 branch
BranchTrueFalseTotal
if $scale 1 244 245
1447  
1448 # The key lists what is in view, so it needs where each grouped marker is
1449 245 ▶ if(@legend) {
Branch: 1 branch
BranchTrueFalseTotal
if (@legend) 9 236 245
1450 my @points = (
1451 11 (map { [ @{$_}[0, 1, 4] ] } @valid_coordinates),
1452 9 (map { [ @{$_}[0, 1, 5] ] } @valid_circles),
1453 );
1454 9 $body .= $self->_legend_js(\@legend, $legend_position, \@points);
1455 }
1456  
1457 # GeoJSON layers.
1458 245 $body .= _geojson_js($geojson_layers);
1459  
1460 # Heatmap layers.
1461 244 for my $layer (@$heatmap_layers) {
1462 16 my $pts = _html_json($layer->{points});
1463 16 ▶ my $opts = $layer->{opts} || {};
Condition50%1/2
$layer->{'opts'} || {}
l!l
160
MC/DC0%0/1
$layer->{'opts'} || {}
$layer->{'opts'}
Truth table50%1/2
A
A= $layer->{'opts'}
Aresult
11
00
1464 # Only plain positive numbers reach the JavaScript
1465 16 my $radius = _positive_number($opts->{radius}, $DEFAULT_RADIUS);
1466 16 my $blur = _positive_number($opts->{blur}, $DEFAULT_BLUR);
1467 16 $body .= "\t\t\tL.heatLayer($pts, { radius: $radius, blur: $blur }).addTo(map);\n";
1468 }
1469  
1470 # GPX tracks — browser fetches the file; fitBounds called on load.
1471 244 for my $url (@$gpx_tracks) {
1472 13 my $js_url = _js_string($url);
1473 13 $body .= "\t\t\tnew L.GPX('$js_url', { async: true }).on('loaded', function(e){ map.fitBounds(e.target.getBounds()); }).addTo(map);\n";
1474 }
1475  
1476 # Choropleth layers — colours are pre-baked; no browser-side scale maths.
1477 244 for my $layer (@$choropleth_layers) {
1478 21 my $fc_json = _html_json({ type => 'FeatureCollection', features => $layer->{features} });
1479 21 my $colors_json = _html_json($layer->{colors});
1480 21 my $values_json = _html_json($layer->{values});
1481 21 my $js_key = _js_string($layer->{key});
1482 21 $body .= qq{
1483 (function() {
1484 var choroplethColors = $colors_json;
1485 var choroplethValues = $values_json;
1486 L.geoJSON($fc_json, {
1487 style: function(f) {
1488 var k = f.properties && f.properties['$js_key'];
1489 return { fillColor: choroplethColors[k] || '#cccccc',
1490 weight: 2, opacity: 1, color: 'white',
1491 dashArray: '3', fillOpacity: 0.7 };
1492 },
1493 onEachFeature: function(f, l) {
1494 var k = f.properties && f.properties['$js_key'];
1495 if(k && choroplethValues[k] !== undefined) {
1496 l.bindPopup(k + ': ' + choroplethValues[k]);
1497 }
1498 }
1499 }).addTo(map);
1500 })();
1501 };
1502 }
1503  
1504 # Event handlers.
1505 244 $body .= qq{
1506 document.getElementById('reset-button').addEventListener('click', function() {
1507 244 ▶ ${\ ($fit_js // "map.setView([$center_lat, $center_lon], $zoom);") }
Condition100%2/2
$fit_js // "map.setView([$center_lat, $center_lon], $zoom);"
l!l
1243
MC/DC100%1/1
$fit_js // "map.setView([$center_lat, $center_lon], $zoom);"
$fit_js
Truth table100%2/2
A
A= $fit_js
Aresult
11
00
1508 });
1509 };
1510  
1511 244 ▶ if($search) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search) 195 49 244
1512 195 $body .= qq{
1513 document.getElementById('clear-search-button').addEventListener('click', function() {
1514 searchMarkers.forEach(function(m) { map.removeLayer(m); });
1515 searchMarkers = [];
1516 });
1517  
1518 document.getElementById('search-box').addEventListener('keyup', function(event) {
1519 if(event.key === 'Enter') {
1520 var query = event.target.value.trim();
1521 if(!query) { alert('Please enter a valid location.'); return; }
1522 fetch('https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(query))
1523 .then(function(r) { return r.json(); })
1524 .then(function(data) {
1525 if(data.length > 0) {
1526 var lat = data[0].lat, lon = data[0].lon;
1527 map.setView([lat, lon], 14);
1528 searchMarkers.push(L.marker([lat, lon]).addTo(map).bindPopup(query).openPopup());
1529 } else {
1530 alert('No results found. Try a different location.');
1531 }
1532 })
1533 .catch(function(err) {
1534 console.error('Search error:', err);
1535 alert('Failed to fetch location. Please check your internet connection.');
1536 });
1537 }
1538 });
1539 };
1540 }
1541 244 $body .= "\t\t</script>\n";
1542  
1543 244 return ($head, $body);
1544 }
1545  
1546 # _point_args: Split a marker method's arguments into a point and options,
1547 # and resolve the point to coordinates.
1548 # Purpose: add_marker and add_circle_marker take the same kinds of point.
1549 # Entry: $self, $caller (method name for messages), then the caller's @_.
1550 # Exit: ($lat, $lon, \%params) with dot-decimal, range-checked coordinates;
1551 # (undef, undef, \%params) when the point cannot be used.
1552 # Side Effects: May call the geocoder; croaks on an unknown point type; _validate carps.
1553 sub _point_args
1554 335 ▶{
Subroutine _point_args: called CC=22 SCAR=30.9
1555 335 my ($self, $caller, @args) = @_;
1556 335 my ($params, $point);
1557  
1558 335 ▶ if(ref($args[0]) eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $args[0] eq 'ARRAY') { } 292 43 335
elsif (builtin::blessed($args[0]) and $args[0]->can('latitude')) { } 6 37 43
elsif (defined $args[0] and not ref $args[0] and scalar(@args) % 2 != 0) { } 24 13 37
1559 292 $point = shift @args;
1560 292 ▶ $params = Params::Get::get_params(undef, \@args) || {};
Condition100%2/2
Params::Get::get_params(undef, \@args) || {}
l!l
143149
MC/DC100%1/1
Params::Get::get_params(undef, \@args) || {}
Params::Get::get_params(undef, \@args)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@args)
Aresult
11
00
1561 # Single-element arrayref is a wrapped address string
1562 292 ▶ $point = $point->[0] if scalar(@{$point}) == 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$point;} == 1 6 286 292
1563 ▶ } elsif(blessed($args[0]) && $args[0]->can('latitude')) {
Condition100%3/3
builtin::blessed($args[0]) and $args[0]->can("latitude")
!ll&&!rl&&r
3346
MC/DC100%2/2
builtin::blessed($args[0]) and $args[0]->can("latitude")
builtin::blessed($args[0]) $args[0]->can("latitude")
Truth table100%3/3
A and B
A= builtin::blessed($args[0])B= $args[0]->can("latitude")
ABresult
0X0
100
111
1564 # Geo object as first positional arg: extract before Params::Get sees it,
1565 # otherwise Params::Get mistakes the blessed hashref for the params hash.
1566 6 $point = shift @args;
1567 6 ▶ $params = Params::Get::get_params(undef, \@args) || {};
Condition100%2/2
Params::Get::get_params(undef, \@args) || {}
l!l
24
MC/DC100%1/1
Params::Get::get_params(undef, \@args) || {}
Params::Get::get_params(undef, \@args)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@args)
Aresult
11
00
1568 ▶ } elsif(defined($args[0]) && !ref($args[0]) && scalar(@args) % 2 != 0) {
Condition100%6/6
defined $args[0] and not ref $args[0] and scalar(@args) % 2 != 0
!ll&&!rl&&r
6724
defined $args[0] and not ref $args[0]
!ll&&!rl&&r
1531
MC/DC100%3/3
defined $args[0] and not ref $args[0] and scalar(@args) % 2 != 0
defined $args[0] not ref $args[0] scalar(@args) % 2 != 0
Truth table100%4/4
A and not(B) and C
A= defined $args[0]B= not ref $args[0]C= scalar(@args) % 2 != 0
ABCresult
0XX0
10X0
1100
1111
1569 # Plain string as first positional arg, optionally followed by key-value pairs.
1570 # An odd total count signals a leading positional; even count means all key-value.
1571 24 $point = shift @args;
1572 24 ▶ $params = Params::Get::get_params(undef, \@args) || {};
Condition100%2/2
Params::Get::get_params(undef, \@args) || {}
l!l
618
MC/DC100%1/1
Params::Get::get_params(undef, \@args) || {}
Params::Get::get_params(undef, \@args)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@args)
Aresult
11
00
1573 } else {
1574 13 $params = Params::Get::get_params('point', @args);
1575 12 $point = $params->{'point'};
1576 }
1577 334 ▶ $params ||= {};
Condition50%1/2
$params ||= {}
l!l
3340
MC/DC0%0/1
$params ||= {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
1578  
1579 334 my ($lat, $lon);
1580  
1581 334 ▶ if(ref($point) eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $point eq 'ARRAY') { } 288 46 334
elsif (not ref $point) { } 35 11 46
elsif ($point->can('latitude')) { } 6 5 11
1582 288 ▶ return (undef, undef, $params) if scalar(@{$point}) != 2;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$point;} != 2 7 281 288
1583 281 ($lat, $lon) = @{$point};
1584 } elsif(!ref($point)) {
1585 # An empty or missing address cannot be resolved
1586 35 ▶ return (undef, undef, $params) unless defined($point) && length($point);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $point and length $point 5 30 35
Condition100%3/3
defined $point and length $point
!ll&&!rl&&r
2330
MC/DC100%2/2
defined $point and length $point
defined $point length $point
Truth table100%3/3
A and B
A= defined $pointB= length $point
ABresult
0X0
100
111
1587 30 ($lat, $lon) = $self->_fetch_coordinates($point);
1588 } elsif($point->can('latitude')) {
1589 6 ($lat, $lon) = ($point->latitude(), $point->longitude());
1590 } else {
1591 5 my $msg = "$caller(): unknown point type: " . ref($point);
1592 5 ▶ $self->{logger}->error($msg) if $self->{logger};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"logger"} 5 0 5
1593 5 croak $msg;
1594 }
1595  
1596 317 ▶ return (undef, undef, $params) unless defined($lat) && defined($lon);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lat and defined $lon 14 303 317
Condition66%2/3
defined $lat and defined $lon
!ll&&!rl&&r
140303
MC/DC50%1/2
defined $lat and defined $lon
defined $lat defined $lon
Truth table66%2/3
A and B
A= defined $latB= defined $lon
ABresult
0X0
100
111
1597  
1598 # Store the text form with a '.' decimal point, whatever the locale
1599 303 ($lat, $lon) = (_num_str($lat), _num_str($lon));
1600 303 ▶ return (undef, undef, $params) unless _validate($lat, $lon);
Branch: 1 branch
BranchTrueFalseTotal
unless _validate($lat, $lon) 14 289 303
1601  
1602 289 return ($lat, $lon, $params);
1603 }
1604  
1605 # _group_arg: Read a marker method's group option.
1606 # Purpose: add_marker and add_circle_marker both take group, the name of the
1607 # key entry a marker belongs to.
1608 # Entry: $self, $caller (method name for messages), \%params.
1609 # Exit: The group as a string, or undef when none was given.
1610 # Side Effects: Croaks (and logs) when group is a reference.
1611 sub _group_arg
1612 314 ▶{
Subroutine _group_arg: called CC=4 SCAR=13.9
1613 314 my ($self, $caller, $params) = @_;
1614  
1615 314 my $group = $params->{'group'};
1616 314 ▶ return undef unless defined($group);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $group 308 6 314
1617 6 ▶ if(ref($group)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $group) 2 4 6
1618 2 my $msg = "$caller(): group must be a string";
1619 2 ▶ $self->{logger}->error($msg) if $self->{logger};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"logger"} 2 0 2
1620 2 croak $msg;
1621 }
1622 4 return "$group";
1623 }
1624  
1625 # _group_value: A stored marker's group, as onload_render() embeds it.
1626 # Purpose: A clone can bring in anything, so a group that is not a plain
1627 # value is dropped rather than embedded.
1628 # Entry: Any scalar.
1629 # Exit: A string, or undef.
1630 sub _group_value
1631 246 ▶{
Subroutine _group_value: called CC=3 SCAR=11.0
1632 246 my $group = shift;
1633  
1634 246 ▶ return (defined($group) && !ref($group)) ? "$group" : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $group && !ref($group) ? : 3 243 246
Condition100%3/3
defined $group and not ref $group
!ll&&!rl&&r
24213
MC/DC100%2/2
defined $group and not ref $group
defined $group not ref $group
Truth table100%3/3
A and not(B)
A= defined $groupB= not ref $group
ABresult
0X0
100
111
1635 }
1636  
1637 # _legend_entries: Check the entries of the key.
1638 # Purpose: new() reports a bad entry where it was made; onload_render() sees
1639 # values from a config file or a clone too, so it skips them instead.
1640 # Entry: $entries (the legend option); $caller, given only by new(), makes
1641 # a bad entry croak.
1642 # Exit: A list of hashrefs { label, colour, radius?, group? }, colour a
1643 # lower-case hex string and radius from _positive_number.
1644 # Side Effects: Croaks when $caller is given, else carps, for each bad entry.
1645 sub _legend_entries
1646 28 ▶{
Subroutine _legend_entries: called CC=14 SCAR=26.4
1647 28 my ($entries, $caller) = @_;
1648  
1649 11 ▶ my $fail = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1650 11 my $msg = shift;
1651 11 ▶ croak "$caller: $msg" if defined($caller);
Branch: 1 branch
BranchTrueFalseTotal
if defined $caller 7 4 11
1652 4 carp "onload_render: $msg; leaving it out of the key";
1653 4 return;
1654 28 };
1655  
1656 28 ▶ if(ref($entries) ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entries ne "ARRAY") 1 27 28
1657 1 $fail->('legend must be an arrayref');
1658 1 return ();
1659 }
1660  
1661 27 my @checked;
1662 27 for my $n (1 .. scalar(@{$entries})) {
1663 33 my $entry = $entries->[$n - 1];
1664 33 ▶ if(ref($entry) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry ne "HASH") 2 31 33
1665 2 $fail->("legend entry $n is not a hashref");
1666 1 next;
1667 }
1668 31 my ($label, $colour, $radius, $group) = @{$entry}{qw(label colour radius group)};
1669 31 ▶ if(!defined($label) || ref($label) || !length($label)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $label or ref $label or not length $label) 3 28 31
Condition83%5/6
not defined $label or ref $label or not length $label
l!l&&r!l&&!r
2128
not defined $label or ref $label
l!l&&r!l&&!r
2029
MC/DC66%2/3
not defined $label or ref $label or not length $label
not defined $label ref $label not length $label
Truth table75%3/4
not(A) or B or not(C)
A= not defined $labelB= ref $labelC= not length $label
ABCresult
1XX1
01X1
0011
0000
1670 3 $fail->("legend entry $n: label is required");
1671 1 next;
1672 }
1673 28 ▶ $colour //= $DEFAULT_CIRCLE_COLOUR;
Condition66%2/3
$colour //= $DEFAULT_CIRCLE_COLOUR
l!l&&r!l&&!r
6220
MC/DC0%0/2
$colour //= $DEFAULT_CIRCLE_COLOUR
$colour $DEFAULT_CIRCLE_COLOUR
Truth table66%2/3
A //= B
A= $colourB= $DEFAULT_CIRCLE_COLOUR
ABresult
1X1
011
000
1674 28 ▶ if(ref($colour) || $colour !~ $HEX_COLOUR) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $colour or not $colour =~ /$HEX_COLOUR/) 2 26 28
Condition66%2/3
ref $colour or not $colour =~ /$HEX_COLOUR/
l!l&&r!l&&!r
0226
MC/DC50%1/2
ref $colour or not $colour =~ /$HEX_COLOUR/
ref $colour not $colour =~ /$HEX_COLOUR/
Truth table66%2/3
A or not(B)
A= ref $colourB= not $colour =~ /$HEX_COLOUR/
ABresult
1X1
011
000
1675 2 $fail->("legend entry $n: invalid colour: $colour");
1676 1 next;
1677 }
1678 26 my %out = (label => "$label", colour => lc($colour));
1679 26 ▶ if(defined($radius)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $radius) 4 22 26
1680 4 my $checked = _positive_number($radius, undef);
1681 4 ▶ if(!defined($checked)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $checked) 2 2 4
1682 2 $fail->("legend entry $n: radius must be a positive number");
1683 0 next;
1684 }
1685 2 $out{'radius'} = $checked;
1686 }
1687 24 ▶ if(defined($group)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $group) 7 17 24
1688 7 ▶ if(ref($group)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $group) 1 6 7
1689 1 $fail->("legend entry $n: group must be a string");
1690 0 next;
1691 }
1692 6 $out{'group'} = "$group";
1693 }
1694 23 push @checked, \%out;
1695 }
1696 20 return @checked;
1697 }
1698  
1699 # _legend_js: The script that draws the key and keeps it to what is in view.
1700 # Purpose: An entry with a group is listed only while a marker of that group
1701 # is inside the map's bounds, so the key follows the reader's zoom
1702 # and pan. Markers inside a cluster count: the check is on where a
1703 # marker is, not on whether Leaflet is drawing it on its own.
1704 # Entry: $self; \@entries from _legend_entries; $position (a Leaflet
1705 # corner, already checked); \@points of [lat, lon, group] with
1706 # validated coordinates.
1707 # Exit: JavaScript for inside the map's <script> block. Every text reaches
1708 # the page through textContent, never as markup.
1709 sub _legend_js
1710 9 ▶{
Subroutine _legend_js: called CC=5 SCAR=16.3
1711 9 my ($self, $entries, $position, $points) = @_;
1712  
1713 # Groups are numbered, so each marker adds two numbers and an index
1714 9 my (%index, @groups);
1715 9 my @point_js;
1716 9 for my $p (@{$points}) {
1717 12 my ($lat, $lon, $group) = @{$p};
1718 12 ▶ next unless defined($group);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $group 9 3 12
1719 3 ▶ $index{$group} //= do { push @groups, $group; $#groups };
Condition33%1/3
$index{$group} //= do { push @groups, $group; $#groups }
l!l&&r!l&&!r
030
MC/DC0%0/2
$index{$group} //= do { push @groups, $group; $#groups }
$index{$group} do { push @groups, $group; $#groups }
Truth table33%1/3
A //= B
A= $index{$group}B= do { push @groups, $group; $#groups }
ABresult
1X1
011
000
1720 3 push @point_js, "[$lat,$lon,$index{$group}]";
1721 }
1722  
1723 9 my $entries_json = _html_json($entries);
1724 9 my $groups_json = _html_json(\@groups);
1725 9 my $points_js = join(',', @point_js);
1726 9 my $title = _js_string($self->{'legend_title'});
1727 9 ▶ my $empty = _js_string($self->{'legend_empty'} // $DEFAULT_LEGEND_EMPTY);
Condition33%1/3
$self->{"legend_empty"} // $DEFAULT_LEGEND_EMPTY
l!l&&r!l&&!r
900
MC/DC0%0/2
$self->{"legend_empty"} // $DEFAULT_LEGEND_EMPTY
$self->{"legend_empty"} $DEFAULT_LEGEND_EMPTY
Truth table33%1/3
A // B
A= $self->{"legend_empty"}B= $DEFAULT_LEGEND_EMPTY
ABresult
1X1
011
000
1728  
1729 9 return qq{
1730 (function() {
1731 var legendEntries = $entries_json;
1732 var legendGroups = $groups_json;
1733 var legendPoints = [$points_js];
1734 var legendTitle = '$title';
1735 var legendEmpty = '$empty';
1736 var legend = L.control({ position: '$position' });
1737 legend.onAdd = function() {
1738 var div = L.DomUtil.create('div', 'html-osm-legend');
1739 div.style.cssText = 'background: rgba(255,255,255,0.9); color: #222; padding: 6px 8px; border-radius: 4px; box-shadow: 0 1px 4px rgba(0,0,0,0.3); font: 12px/1.5 sans-serif; max-height: 40vh; overflow-y: auto;';
1740 L.DomEvent.disableClickPropagation(div);
1741 L.DomEvent.disableScrollPropagation(div);
1742 return div;
1743 };
1744 legend.addTo(map);
1745 function drawLegend() {
1746 var div = legend.getContainer();
1747 var bounds = map.getBounds();
1748 var inView = {};
1749 legendPoints.forEach(function(p) {
1750 if(bounds.contains(L.latLng(p[0], p[1]))) { inView[legendGroups[p[2]]] = true; }
1751 });
1752 while(div.firstChild) { div.removeChild(div.firstChild); }
1753 if(legendTitle.length) {
1754 var title = document.createElement('strong');
1755 title.style.display = 'block';
1756 title.textContent = legendTitle;
1757 div.appendChild(title);
1758 }
1759 var shown = 0;
1760 legendEntries.forEach(function(e) {
1761 if(e.group !== undefined && !inView[e.group]) { return; }
1762 var row = document.createElement('div');
1763 row.className = 'html-osm-legend-entry';
1764 var size = e.radius ? Math.min(2 * e.radius, 2 * $LEGEND_SWATCH_MAX) : 12;
1765 var swatch = document.createElement('span');
1766 swatch.style.cssText = 'display: inline-block; vertical-align: middle; margin-right: 6px; border-radius: 50%; opacity: 0.85;';
1767 swatch.style.width = size + 'px';
1768 swatch.style.height = size + 'px';
1769 swatch.style.background = e.colour;
1770 swatch.style.border = '1px solid ' + e.colour;
1771 row.appendChild(swatch);
1772 row.appendChild(document.createTextNode(e.label));
1773 div.appendChild(row);
1774 shown++;
1775 });
1776 if(!shown) {
1777 var none = document.createElement('em');
1778 none.textContent = legendEmpty;
1779 div.appendChild(none);
1780 }
1781 }
1782 drawLegend();
1783 map.on('moveend', drawLegend);
1784 })();
1785 };
1786 }
1787  
1788 # _fetch_coordinates: Resolve a place-name string to a (lat, lon) pair.
1789 # Purpose: Centralise all geocoding logic — try the injected geocoder first,
1790 # fall back to a direct Nominatim HTTP call with caching and rate-limiting.
1791 # Entry: $self, $location (non-empty string).
1792 # Exit: ($lat, $lon) strings on success; (undef, undef) on failure.
1793 # Side Effects: May sleep to honour min_interval; writes to $self->{cache}.
1794 sub _fetch_coordinates
1795 60 ▶{
Subroutine _fetch_coordinates: called CC=20 SCAR=30.0
1796 60 my ($self, $location) = @_;
1797  
1798 60 ▶ croak 'address not given to _fetch_coordinates' unless $location;
Branch: 1 branch
BranchTrueFalseTotal
unless $location 2 58 60
1799  
1800 # Prefer an injected geocoder (e.g. Geo::Coder::List) to avoid HTTP.
1801 58 ▶ if(my $geocoder = $self->{'geocoder'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $geocoder = $self->{"geocoder"}) 36 22 58
1802 36 my $rc = $geocoder->geocode($location);
1803 36 ▶ return (undef, undef) unless defined $rc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rc 10 26 36
1804  
1805 26 ▶ if(blessed($rc) && $rc->can('latitude')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($rc) and $rc->can("latitude")) 2 24 26
Condition100%3/3
builtin::blessed($rc) and $rc->can("latitude")
!ll&&!rl&&r
2312
MC/DC100%2/2
builtin::blessed($rc) and $rc->can("latitude")
builtin::blessed($rc) $rc->can("latitude")
Truth table100%3/3
A and B
A= builtin::blessed($rc)B= $rc->can("latitude")
ABresult
0X0
100
111
1806 2 return ($rc->latitude(), $rc->longitude());
1807 }
1808 24 ▶ if(ref($rc) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rc eq "HASH") 21 3 24
1809 return ($rc->{lat}, $rc->{lon})
1810 21 ▶ if defined($rc->{lat}) && defined($rc->{lon});
Branch: 1 branch
BranchTrueFalseTotal
if defined $rc->{"lat"} and defined $rc->{"lon"} 17 4 21
Condition100%3/3
defined $rc->{"lat"} and defined $rc->{"lon"}
!ll&&!rl&&r
3117
MC/DC100%2/2
defined $rc->{"lat"} and defined $rc->{"lon"}
defined $rc->{"lat"} defined $rc->{"lon"}
Truth table100%3/3
A and B
A= defined $rc->{"lat"}B= defined $rc->{"lon"}
ABresult
0X0
100
111
1811 return ($rc->{geometry}{location}{lat}, $rc->{geometry}{location}{lng})
1812 4 ▶ if defined($rc->{geometry}{location}{lat});
Branch: 1 branch
BranchTrueFalseTotal
if defined $rc->{"geometry"}{"location"}{"lat"} 2 2 4
1813 }
1814 # Some geocoders return a flat [lat, lon] arrayref
1815 5 ▶ return @{$rc} if ref($rc) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $rc eq "ARRAY" 2 3 5
1816  
1817 # Unrecognised return type — treat as failure
1818 3 carp '_fetch_coordinates: unrecognised geocoder result type: ' . ref($rc);
1819 3 return (undef, undef);
1820 }
1821  
1822 # Direct Nominatim path: apply caching and rate-limiting.
1823 22 my $cache_key = 'osm:' . uri_escape_utf8($location);
1824 22 ▶ if(my $cached = $self->{cache}->get($cache_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"cache"}->get($cache_key)) 4 18 22
1825 4 return ($cached->{lat}, $cached->{lon});
1826 }
1827  
1828 # Honour the minimum interval between outbound requests.
1829 18 my $elapsed = time() - $self->{last_request};
1830 18 ▶ if($elapsed < $self->{min_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 3 15 18
1831 3 Time::HiRes::sleep($self->{min_interval} - $elapsed);
1832 }
1833  
1834 # Configure only a UA we create; a caller's UA is used as supplied
1835 18 my $ua = $self->{'ua'};
1836 18 ▶ if(!$ua) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ua) 4 14 18
1837 4 $ua = LWP::UserAgent->new(agent => __PACKAGE__ . "/$VERSION");
1838 4 $ua->default_header(accept_encoding => 'gzip,deflate');
1839 4 $ua->env_proxy(1);
1840 }
1841  
1842 18 my $url = 'https://' . $self->{'host'} . '?format=json&q=' . uri_escape_utf8($location);
1843 18 ▶ $url .= '&email=' . uri_escape_utf8($self->{'email'}) if $self->{'email'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"email"} 1 17 18
1844 18 my $response = $ua->get($url);
1845 18 $self->{'last_request'} = time();
1846  
1847 18 ▶ if($response->is_success()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_success) 15 3 18
1848 # eval guard: Nominatim normally returns valid JSON, but a maintenance
1849 # page or rate-limit response could return HTML with a 200 OK. Dying
1850 # inside _fetch_coordinates would bubble uncaught to add_marker / onload_render.
1851 15 my $data = eval { decode_json($response->decoded_content()) };
1852 15 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 13 15
1853 2 carp "_fetch_coordinates: failed to decode Nominatim response: $@";
1854 2 return (undef, undef);
1855 }
1856 13 ▶ $data = $data->[0] if ref($data) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $data eq "ARRAY" 10 3 13
1857 13 ▶ if(ref($data) eq 'HASH' && defined($data->{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH" and defined $data->{"lat"}) 10 3 13
Condition100%3/3
ref $data eq "HASH" and defined $data->{"lat"}
!ll&&!rl&&r
2110
MC/DC100%2/2
ref $data eq "HASH" and defined $data->{"lat"}
ref $data eq "HASH" defined $data->{"lat"}
Truth table100%3/3
A and B
A= ref $data eq "HASH"B= defined $data->{"lat"}
ABresult
0X0
100
111
1858 10 $self->{'cache'}->set($cache_key, $data);
1859 10 return ($data->{lat}, $data->{lon});
1860 }
1861 }
1862  
1863 6 return (undef, undef);
1864 }
1865  
1866 # _validate: Check that a (lat, lon) pair is numeric and within WGS-84 bounds.
1867 # Purpose: Single guard point for all coordinate ingestion; emits a carp when
1868 # both values are defined but wrong so the caller can log without dying.
1869 # Entry: ($lat, $lon) — any scalar, including undef.
1870 # Exit: 1 if valid, 0 if not.
1871 # Side Effects: carp when coordinates are defined but out-of-range/non-numeric.
1872 sub _validate
1873 647 ▶{
Subroutine _validate: called CC=14 SCAR=26.4
1874 647 my ($lat, $lon) = map { _num_str($_) } @_;
1875  
1876 # Require at least one digit (rejects empty string — unlike \d* which matches '').
1877 # Leading-decimal notation (e.g. -.5167) is valid per Changes 0.05.
1878 # \z (not $) prevents a trailing \n from sneaking through: $ matches before
1879 # a final newline, which would make "0\n" valid and embed a newline in JS.
1880 647 my $numeric = qr/^-?(?:\d+(?:\.\d+)?|\.\d+)\z/;
1881  
1882 # Range checks use _num_val, which does not depend on the locale
1883 647 ▶ my $ok = defined($lat) && defined($lon)
Condition100%21/21
defined $lat && defined $lon && $lat =~ /$numeric/ && $lon =~ /$numeric/ && _num_val($lat) >= $LAT_MIN && _num_val($lat) <= $LAT_MAX && _num_val($lon) >= $LON_MIN && _num_val($lon) <= $LON_MAX
!ll&&!rl&&r
532592
defined $lat and defined $lon and $lat =~ /$numeric/ and $lon =~ /$numeric/ and _num_val($lat) >= $LAT_MIN and _num_val($lat) <= $LAT_MAX and _num_val($lon) >= $LON_MIN
!ll&&!rl&&r
494594
defined $lat and defined $lon and $lat =~ /$numeric/ and $lon =~ /$numeric/ and _num_val($lat) >= $LAT_MIN and _num_val($lat) <= $LAT_MAX
!ll&&!rl&&r
3118598
defined $lat and defined $lon and $lat =~ /$numeric/ and $lon =~ /$numeric/ and _num_val($lat) >= $LAT_MIN
!ll&&!rl&&r
292616
defined $lat and defined $lon and $lat =~ /$numeric/ and $lon =~ /$numeric/
!ll&&!rl&&r
236618
defined $lat and defined $lon and $lat =~ /$numeric/
!ll&&!rl&&r
320624
defined $lat and defined $lon
!ll&&!rl&&r
21644
MC/DC100%8/8
defined $lat && defined $lon && $lat =~ /$numeric/ && $lon =~ /$numeric/ && _num_val($lat) >= $LAT_MIN && _num_val($lat) <= $LAT_MAX && _num_val($lon) >= $LON_MIN && _num_val($lon) <= $LON_MAX
defined $lat defined $lon $lat =~ /$numeric/ $lon =~ /$numeric/ _num_val($lat) >= $LAT_MIN _num_val($lat) <= $LAT_MAX _num_val($lon) >= $LON_MIN _num_val($lon) <= $LON_MAX
Truth table100%9/9
A and B and C and D and E and F and G && H
A= defined $latB= defined $lonC= $lat =~ /$numeric/D= $lon =~ /$numeric/E= _num_val($lat) >= $LAT_MINF= _num_val($lat) <= $LAT_MAXG= _num_val($lon) >= $LON_MINH= _num_val($lon) <= $LON_MAX
ABCDEFGHresult
0XXXXXXX0
10XXXXXX0
110XXXXX0
1110XXXX0
11110XXX0
111110XX0
1111110X0
111111100
111111111
1884 && $lat =~ $numeric && $lon =~ $numeric
1885 && _num_val($lat) >= $LAT_MIN && _num_val($lat) <= $LAT_MAX
1886 && _num_val($lon) >= $LON_MIN && _num_val($lon) <= $LON_MAX;
1887  
1888 647 ▶ carp(sprintf 'Skipping invalid coordinate: (%s, %s)',
Branch: 1 branch
BranchTrueFalseTotal
if not $ok and defined $lat and defined $lon 52 595 647
Condition80%8/10
not $ok and defined $lat and defined $lon
!ll&&!rl&&r
594152
not $ok and defined $lat
!ll&&!rl&&r
592253
$lat // "undef"
l!l
520
$lon // "undef"
l!l
520
MC/DC100%3/3
not $ok and defined $lat and defined $lon
not $ok defined $lat defined $lon
MC/DC0%0/1
$lat // "undef"
$lat
MC/DC0%0/1
$lon // "undef"
$lon
Truth table100%4/4
not(A) and B and C
A= not $okB= defined $latC= defined $lon
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $lat
Aresult
11
00
Truth table50%1/2
A
A= $lon
Aresult
11
00
1889 $lat // 'undef', $lon // 'undef')
1890 if !$ok && defined($lat) && defined($lon);
1891  
1892 647 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 592 55 647
1893 }
1894  
1895 # _html_json: Encode data as JSON and make the result safe for embedding in a
1896 # <script> block. JSON encoders do not escape '/' by default, so a value like
1897 # '</script>' would close the enclosing script tag and allow HTML injection.
1898 # Escaping every '</' as '<\/' prevents this without altering the decoded value.
1899 # Encoding runs under the C numeric locale: some encoders print numbers through
1900 # the C library or Perl's own stringification, and under a locale such as
1901 # de_DE 0.5 could come out as 0,5, which JSON reads as two numbers.
1902 # Entry: Any Perl data structure accepted by encode_json.
1903 # Exit: JSON string safe for direct insertion inside a <script> block.
1904 # Side Effects: LC_NUMERIC is switched to 'C' for the encode and then restored.
1905 sub _html_json
1906 189 ▶{
Subroutine _html_json: called CC=3 SCAR=11.0
1907 189 my $data = shift;
1908  
1909 189 my $saved_error = $@;
1910 189 my $saved_locale = setlocale(LC_NUMERIC);
1911 189 setlocale(LC_NUMERIC, 'C');
1912 189 my $j = eval { encode_json($data) };
1913 189 my $err = $@;
1914 189 ▶ setlocale(LC_NUMERIC, $saved_locale) if defined($saved_locale);
Branch: 1 branch
BranchTrueFalseTotal
if defined $saved_locale 189 0 189
1915 189 ▶ die $err unless defined($j);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $j 2 187 189
1916 187 $@ = $saved_error;
1917  
1918 187 $j =~ s|</|<\\/|g;
1919 187 return $j;
1920 }
1921  
1922 # The JavaScript function that draws a layer's key and shows it while the
1923 # layer is shown: layerKey(layer, key), key as _layer_key returns it. Every
1924 # text goes in through textContent. It is written into a function's scope,
1925 # never the page's.
1926 18 Readonly::Scalar my $LAYER_KEY_JS => <<'JS';
1927 function layerKey(layer, k) {
1928 var key = L.control({ position: k.position });
1929 key.onAdd = function() {
1930 var div = L.DomUtil.create('div', 'html-osm-legend html-osm-layer-key');
1931 div.style.cssText = 'background: rgba(255,255,255,0.9); color: #222; padding: 6px 8px; border-radius: 4px; box-shadow: 0 1px 4px rgba(0,0,0,0.3); font: 12px/1.5 sans-serif; max-height: 40vh; overflow-y: auto;';
1932 L.DomEvent.disableClickPropagation(div);
1933 L.DomEvent.disableScrollPropagation(div);
1934 if(k.title) {
1935 var title = document.createElement('strong');
1936 title.style.display = 'block';
1937 title.textContent = k.title;
1938 div.appendChild(title);
1939 }
1940 k.entries.forEach(function(e) {
1941 var row = document.createElement('div');
1942 row.className = 'html-osm-legend-entry';
1943 var swatch = document.createElement('span');
1944 swatch.style.cssText = 'display: inline-block; vertical-align: middle; margin-right: 6px; width: 18px; height: 0;';
1945 swatch.style.borderTop = '3px solid ' + e.colour;
1946 row.appendChild(swatch);
1947 row.appendChild(document.createTextNode(e.label));
1948 div.appendChild(row);
1949 });
1950 return div;
1951 };
1952 if(map.hasLayer(layer)) { key.addTo(map); }
1953 map.on('overlayadd', function(e) { if(e.layer === layer) { key.addTo(map); } });
1954 map.on('overlayremove', function(e) { if(e.layer === layer) { key.remove(); } });
1955 }
1956 JS
1957  
1958 # The JavaScript functions that draw a banded layer: bandLayer(data, style,
1959 # each, prop) is L.geoJSON(data, ...) with every polygon's outline drawn once
1960 # for each colour in its property prop, every line inside the polygon. The
1961 # polygon's own line is made invisible: it stays to take clicks and to be the
1962 # shape the others are cut to. Each colour is a second polygon over it, cut to
1963 # the inside of the first by an SVG clip path, so a line 2*j widths wide shows
1964 # j widths inside the edge; the widest is added first, so each narrower one
1965 # covers all but the innermost width of the one before, and the first colour
1966 # ends up against the edge. The clip path refers to the first polygon's own
1967 # path element, so it follows the map as it is zoomed. Leaflet makes a new
1968 # path element each time a layer is put back on the map, hence the 'add'
1969 # handlers. A colour reaches the page only when it is #rrggbb. It is written
1970 # into a function's scope, never the page's.
1971 18 Readonly::Scalar my $BAND_JS => <<'JS';
1972 function bandInside(base, style, colour, weight) {
1973 var opts = {};
1974 for(var k in style) { opts[k] = style[k]; }
1975 opts.color = colour;
1976 opts.weight = weight;
1977 opts.fill = false;
1978 opts.interactive = false;
1979 var inner = L.polygon(base.getLatLngs(), opts);
1980 var id = 'html-osm-band-' + L.stamp(base);
1981 base.on('add', function() {
1982 var under = base.getElement && base.getElement();
1983 if(under && under.ownerSVGElement) {
1984 under.setAttribute('id', id);
1985 under.setAttribute('clip-rule', 'evenodd');
1986 }
1987 });
1988 inner.on('add', function() {
1989 var path = inner.getElement && inner.getElement();
1990 var svg = path && path.ownerSVGElement;
1991 if(!svg) { return; }
1992 var ns = 'http://www.w3.org/2000/svg';
1993 if(!svg.querySelector('#' + id + '-clip')) {
1994 var defs = svg.querySelector('defs');
1995 if(!defs) {
1996 defs = document.createElementNS(ns, 'defs');
1997 svg.insertBefore(defs, svg.firstChild);
1998 }
1999 var clip = document.createElementNS(ns, 'clipPath');
2000 clip.setAttribute('id', id + '-clip');
2001 var use = document.createElementNS(ns, 'use');
2002 use.setAttribute('href', '#' + id);
2003 clip.appendChild(use);
2004 defs.appendChild(clip);
2005 }
2006 path.setAttribute('clip-path', 'url(#' + id + '-clip)');
2007 });
2008 return inner;
2009 }
2010 function bandLayer(data, style, each, prop) {
2011 var inside = [];
2012 var width = (style && style.weight) || 3;
2013 var layer = L.geoJSON(data, { style: style, onEachFeature: function(f, base) {
2014 if(each) { each(f, base); }
2015 var list = f.properties && f.properties[prop];
2016 var cols = Array.isArray(list)
2017 ? list.filter(function(c) { return typeof c === 'string' && /^#[0-9a-fA-F]{6}$/.test(c); }) : [];
2018 if(!cols.length || !base.setStyle) { return; }
2019 if(!(base instanceof L.Polygon)) {
2020 base.setStyle({ color: cols[0] });
2021 return;
2022 }
2023 base.setStyle({ color: cols[0], opacity: 0, weight: 2 * cols.length * width });
2024 for(var j = cols.length - 1; j >= 0; j--) {
2025 inside.push(bandInside(base, style || {}, cols[j], 2 * (j + 1) * width));
2026 }
2027 } });
2028 inside.forEach(function(l) { layer.addLayer(l); });
2029 return layer;
2030 }
2031 JS
2032  
2033 # _geojson_js: The JavaScript that draws the GeoJSON layers, and the layer
2034 # control when any of them has a name.
2035 # Purpose: Unnamed layers are drawn as before, one statement each. Named
2036 # layers are gathered by name into one L.layerGroup per name, in the
2037 # order the names first appear, so one checkbox shows or hides every
2038 # layer of that name; a group is on the map at first when any of its
2039 # layers has show on.
2040 # Entry: Arrayref of { data, opts } from add_geojson.
2041 # Exit: JavaScript text ('' when there are no layers). Named layers are
2042 # wrapped in a function so their variables stay out of the page's
2043 # global scope; only 'map' is read from it.
2044 # Notes: Leaflet sets a control's label with innerHTML, so the name is
2045 # HTML-escaped before it is made a JavaScript string. Values from a
2046 # config file or a clone skip add_geojson's checks, so a name that is
2047 # not a non-empty string is dropped here, and the layer drawn unnamed.
2048 sub _geojson_js
2049 245 ▶{
Subroutine _geojson_js: called CC=31 SCAR=34.3
2050 245 my $layers = shift;
2051  
2052 245 my $out = '';
2053 245 my (@names, %group_of, %shown, %key_of);
2054 245 my $named_bands = 0; # whether a named layer is banded
2055 245 for my $layer (@$layers) {
2056 65 my $json = _html_json($layer->{data});
2057 64 ▶ my $opts = $layer->{opts} || {};
Condition50%1/2
$layer->{'opts'} || {}
l!l
640
MC/DC0%0/1
$layer->{'opts'} || {}
$layer->{'opts'}
Truth table50%1/2
A
A= $layer->{'opts'}
Aresult
11
00
2058 64 my $style_js = '';
2059 64 my $popup_js = '';
2060 64 my $each_js = '';
2061 64 ▶ if(my $style = $opts->{style}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $style = $opts->{"style"}) 13 51 64
2062 13 $style_js = 'style: ' . _html_json($style) . ',';
2063 }
2064 64 ▶ if(my $prop = $opts->{popup}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $prop = $opts->{"popup"}) 7 57 64
2065 7 my $js_prop = _js_string($prop);
2066 7 $each_js = "function(f,l){ if(f.properties && f.properties['$js_prop']){ l.bindPopup(String(f.properties['$js_prop'])); } }";
2067 7 $popup_js = "onEachFeature: $each_js,";
2068 }
2069 64 my $js = "L.geoJSON($json, { $style_js $popup_js })";
2070 # A banded layer is drawn by bandLayer, which needs the style and
2071 # the popup function apart, to give them to its inner lines too
2072 64 my $bands = $opts->{bands};
2073 64 ▶ $bands = undef if ref($bands) || !length($bands // '');
Branch: 1 branch
BranchTrueFalseTotal
if ref $bands or not length($bands // "") 57 7 64
Condition100%5/5
ref $bands or not length($bands // "")
l!l&&r!l&&!r
1567
$bands // ""
l!l
756
MC/DC100%2/2
ref $bands or not length($bands // "")
ref $bands $bands
Truth table100%3/3
A or not(B)
A= ref $bandsB= $bands
ABresult
1X1
001
010
2074 64 ▶ if(defined $bands) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bands) 7 57 64
2075 7 ▶ $js = "bandLayer($json, " . ($opts->{style} ? _html_json($opts->{style}) : 'null')
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'style'} ? : 1 6 7
Condition100%2/2
$each_js || 'null'
l!l
16
MC/DC100%1/1
$each_js || 'null'
$each_js
Truth table100%2/2
A
A= $each_js
Aresult
11
00
2076 . ', ' . ($each_js || 'null') . ", '" . _js_string($bands) . "')";
2077 }
2078  
2079 64 my $name = $opts->{name};
2080 64 ▶ my $key = ref($opts->{key}) eq 'HASH' ? $opts->{key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $opts->{'key'} eq 'HASH' ? : 7 57 64
2081 64 ▶ if(!defined($name) || ref($name) || !length($name)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $name or ref $name or not length $name) 35 29 64
Condition83%5/6
not defined $name or ref $name or not length $name
l!l&&r!l&&!r
35029
not defined $name or ref $name
l!l&&r!l&&!r
34129
MC/DC66%2/3
not defined $name or ref $name or not length $name
not defined $name ref $name not length $name
Truth table75%3/4
not(A) or B or not(C)
A= not defined $nameB= ref $nameC= not length $name
ABCresult
1XX1
01X1
0011
0000
2082 35 ▶ if($key) {
Branch: 2 branches
BranchTrueFalseTotal
if ($key) { } 2 33 35
elsif (defined $bands) { } 4 29 33
2083 # Always drawn, so its key always shows
2084 2 ▶ $out .= "\t\t\t(function() {\n$LAYER_KEY_JS" . (defined($bands) ? $BAND_JS : '')
Branch: 1 branch
BranchTrueFalseTotal
defined $bands ? : 1 1 2
2085 . "\t\t\t\tlayerKey($js.addTo(map), " . _html_json($key) . ");\n\t\t\t})();\n";
2086 } elsif(defined $bands) {
2087 # Its functions are kept out of the page's scope
2088 4 $out .= "\t\t\t(function() {\n$BAND_JS\t\t\t\t$js.addTo(map);\n\t\t\t})();\n";
2089 } else {
2090 29 $out .= "\t\t\t$js.addTo(map);\n";
2091 }
2092 35 next;
2093 }
2094 29 ▶ $key_of{$name} //= $key if $key;
Branch: 1 branch
BranchTrueFalseTotal
if $key 5 24 29
Condition66%2/3
$key_of{$name} //= $key
l!l&&r!l&&!r
140
MC/DC0%0/2
$key_of{$name} //= $key
$key_of{$name} $key
Truth table66%2/3
A //= B
A= $key_of{$name}B= $key
ABresult
1X1
011
000
2095 29 ▶ $named_bands = 1 if defined $bands;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bands 2 27 29
2096 29 ▶ unless(exists $group_of{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $group_of{$name}) 25 4 29
2097 25 push @names, $name;
2098 25 $group_of{$name} = [];
2099 25 $shown{$name} = 0;
2100 }
2101 29 push @{$group_of{$name}}, $js;
2102 29 my $show = $opts->{show};
2103 29 ▶ $shown{$name} = 1 if !defined($show) || ($show && $show !~ /\A(?:false|no|off)\z/i);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $show or $show and not $show =~ /\A(?:false|no|off)\z/i 21 8 29
Condition100%6/6
not defined $show or $show and not $show =~ /\A(?:false|no|off)\z/i
l!l&&r!l&&!r
1838
$show and not $show =~ /\A(?:false|no|off)\z/i
!ll&&!rl&&r
353
MC/DC100%3/3
not defined $show or $show and not $show =~ /\A(?:false|no|off)\z/i
not defined $show $show not $show =~ /\A(?:false|no|off)\z/i
Truth table100%4/4
not(A) or B and not(C)
A= not defined $showB= $showC= not $show =~ /\A(?:false|no|off)\z/i
ABCresult
1XX1
0111
00X0
0100
2104 }
2105 244 ▶ return $out unless @names;
Branch: 1 branch
BranchTrueFalseTotal
unless @names 221 23 244
2106  
2107 23 $out .= "\t\t\t(function() {\n\t\t\t\tvar overlays = {};\n\t\t\t\tvar group;\n";
2108 23 ▶ $out .= $LAYER_KEY_JS if %key_of;
Branch: 1 branch
BranchTrueFalseTotal
if %key_of 4 19 23
2109 23 ▶ $out .= $BAND_JS if $named_bands;
Branch: 1 branch
BranchTrueFalseTotal
if $named_bands 2 21 23
2110 23 for my $name (@names) {
2111 25 my $label = _js_string(_html_attr($name));
2112 25 $out .= "\t\t\t\tgroup = L.layerGroup([" . join(', ', @{$group_of{$name}}) . "]);\n";
2113 25 ▶ $out .= "\t\t\t\tgroup.addTo(map);\n" if $shown{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $shown{$name} 18 7 25
2114 25 $out .= "\t\t\t\toverlays['$label'] = group;\n";
2115 25 ▶ $out .= "\t\t\t\tlayerKey(group, " . _html_json($key_of{$name}) . ");\n" if $key_of{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $key_of{$name} 4 21 25
2116 }
2117 23 $out .= "\t\t\t\tL.control.layers(null, overlays, { collapsed: false }).addTo(map);\n\t\t\t})();\n";
2118 23 return $out;
2119 }
2120  
2121 # _layer_key: Check add_geojson's key.
2122 # Purpose: A key is written into the page's script, so only checked text,
2123 # colours and a known corner may reach it.
2124 # Entry: The key option.
2125 # Exit: { entries => [ { label, colour } ], position, title? }, colours in
2126 # lower case; croaks naming what is wrong.
2127 sub _layer_key
2128 28 ▶{
Subroutine _layer_key: called CC=19 SCAR=29.5
2129 28 my $key = shift;
2130  
2131 28 ▶ croak 'add_geojson: key must be a hashref' unless ref($key) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $key eq "HASH" 2 26 28
2132 26 my $entries = $key->{entries};
2133 croak 'add_geojson: key entries must be a non-empty arrayref'
2134 26 ▶ unless ref($entries) eq 'ARRAY' && @{$entries};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entries eq "ARRAY" and @{$entries;} 4 22 26
Condition100%3/3
ref $entries eq "ARRAY" and @{$entries;}
!ll&&!rl&&r
2222
MC/DC100%2/2
ref $entries eq "ARRAY" and @{$entries;}
ref $entries eq "ARRAY" @{$entries;}
Truth table100%3/3
A and B
A= ref $entries eq "ARRAY"B= @{$entries;}
ABresult
0X0
100
111
2135  
2136 22 my @checked;
2137 22 for my $n (1 .. scalar(@{$entries})) {
2138 30 my $entry = $entries->[$n - 1];
2139 30 ▶ croak "add_geojson: key entry $n is not a hashref" unless ref($entry) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 2 28 30
2140 28 my ($label, $colour) = @{$entry}{qw(label colour)};
2141 28 ▶ croak "add_geojson: key entry $n: label is required"
Branch: 1 branch
BranchTrueFalseTotal
if not defined $label or ref $label or not length $label 2 26 28
Condition66%4/6
not defined $label or ref $label or not length $label
l!l&&r!l&&!r
2026
not defined $label or ref $label
l!l&&r!l&&!r
2026
MC/DC33%1/3
not defined $label or ref $label or not length $label
not defined $label ref $label not length $label
Truth table50%2/4
not(A) or B or not(C)
A= not defined $labelB= ref $labelC= not length $label
ABCresult
1XX1
01X1
0011
0000
2142 if !defined($label) || ref($label) || !length($label);
2143 26 ▶ croak "add_geojson: key entry $n: invalid colour: " . ($colour // 'undef')
Branch: 1 branch
BranchTrueFalseTotal
if not defined $colour or ref $colour or not $colour =~ /$HEX_COLOUR/ 6 20 26
Condition87%7/8
not defined $colour or ref $colour or not $colour =~ /$HEX_COLOUR/
l!l&&r!l&&!r
2420
not defined $colour or ref $colour
l!l&&r!l&&!r
2024
$colour // "undef"
l!l
42
MC/DC66%2/3
not defined $colour or ref $colour or not $colour =~ /$HEX_COLOUR/
not defined $colour ref $colour not $colour =~ /$HEX_COLOUR/
MC/DC100%1/1
$colour // "undef"
$colour
Truth table75%3/4
not(A) or B or not(C)
A= not defined $colourB= ref $colourC= not $colour =~ /$HEX_COLOUR/
ABCresult
1XX1
01X1
0011
0000
Truth table100%2/2
A
A= $colour
Aresult
11
00
2144 if !defined($colour) || ref($colour) || $colour !~ $HEX_COLOUR;
2145 20 push @checked, { label => "$label", colour => lc($colour) };
2146 }
2147  
2148 12 ▶ my $position = $key->{position} // $DEFAULT_KEY_POSITION;
Condition66%2/3
$key->{"position"} // $DEFAULT_KEY_POSITION
l!l&&r!l&&!r
390
MC/DC0%0/2
$key->{"position"} // $DEFAULT_KEY_POSITION
$key->{"position"} $DEFAULT_KEY_POSITION
Truth table66%2/3
A // B
A= $key->{"position"}B= $DEFAULT_KEY_POSITION
ABresult
1X1
011
000
2149 croak 'add_geojson: key position must be one of ' . join(', ', @LEGEND_POSITIONS)
2150 12 ▶ unless !ref($position) && grep { $_ eq $position } @LEGEND_POSITIONS;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $position and grep {$_ eq $position;} @LEGEND_POSITIONS 2 10 12
Condition66%2/3
not ref $position and grep {$_ eq $position;} @LEGEND_POSITIONS
!ll&&!rl&&r
0210
MC/DC50%1/2
not ref $position and grep {$_ eq $position;} @LEGEND_POSITIONS
not ref $position grep {$_ eq $position;} @LEGEND_POSITIONS
Truth table66%2/3
not(A) and B
A= not ref $positionB= grep {$_ eq $position;} @LEGEND_POSITIONS
ABresult
0X0
100
111
2151  
2152 10 my %out = (entries => \@checked, position => $position);
2153 10 ▶ if(defined(my $title = $key->{title})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $title = $key->{"title"})) 7 3 10
2154 7 ▶ croak 'add_geojson: key title must be text' if ref($title);
Branch: 1 branch
BranchTrueFalseTotal
if ref $title 2 5 7
2155 5 ▶ $out{title} = "$title" if length($title);
Branch: 1 branch
BranchTrueFalseTotal
if length $title 4 1 5
2156 }
2157 8 return \%out;
2158 }
2159  
2160 # _js_string: Escape a Perl string for safe embedding in a JS single-quoted literal.
2161 # Purpose: Prevent JS injection via user-supplied labels, URLs, or property names.
2162 # Entry: Any scalar (undef becomes '').
2163 # Exit: Escaped string safe for insertion between JS single quotes.
2164 sub _js_string
2165 832 ▶{
Subroutine _js_string: called CC=2 SCAR=6.9
2166 832 ▶ my $s = shift // '';
Condition100%2/2
shift() // ""
l!l
704128
MC/DC100%1/1
shift() // ""
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
2167 832 $s =~ s/\\/\\\\/g; # escape backslash first to avoid double-escaping
2168 832 $s =~ s/'/\\'/g; # escape our JS string delimiter
2169 832 $s =~ s/\r?\n/\\n/g; # newlines would break the JS string
2170 832 $s =~ s/\r/\\r/g; # a lone carriage return also ends a JS string
2171 832 $s =~ s|</|<\\/|g; # prevent </script> injection
2172 832 return $s;
2173 }
2174  
2175 # _html_attr: Escape a Perl string for safe embedding in a double-quoted HTML attribute.
2176 # Purpose: Stop a configured CDN URL from closing the attribute or the tag.
2177 # Entry: Any scalar (undef becomes '').
2178 # Exit: String with &, <, > and " replaced by entities.
2179 sub _html_attr
2180 1744 ▶{
Subroutine _html_attr: called CC=2 SCAR=6.9
2181 1744 ▶ my $s = shift // '';
Condition100%2/2
shift() // ""
l!l
17431
MC/DC100%1/1
shift() // ""
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
2182 1744 $s =~ s/&/&amp;/g; # escape ampersand first to avoid double-escaping
2183 1744 $s =~ s/</&lt;/g;
2184 1744 $s =~ s/>/&gt;/g;
2185 1744 $s =~ s/"/&quot;/g;
2186 1744 return $s;
2187 }
2188  
2189 # _css_length: Check a width or height before it is put into the <style> block.
2190 # Purpose: Values from a config file or a clone skip new()'s schema, so a value
2191 # such as '1px}</style><script>' could otherwise reach the page.
2192 # Entry: ($name, $value, $default) - name is used only in the warning.
2193 # Exit: $value when it is a CSS length; otherwise $default.
2194 # Side Effects: carp when a non-empty value is replaced.
2195 sub _css_length
2196 534 ▶{
Subroutine _css_length: called CC=4 SCAR=13.9
2197 534 my ($name, $value, $default) = @_;
2198  
2199 534 ▶ return $default unless defined($value) && length($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and length $value 4 530 534
Condition100%3/3
defined $value and length $value
!ll&&!rl&&r
13530
MC/DC100%2/2
defined $value and length $value
defined $value length $value
Truth table100%3/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
2200 530 ▶ return $value if $value =~ $CSS_LENGTH;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /$CSS_LENGTH/ 526 4 530
2201  
2202 4 carp "onload_render: invalid $name '$value', using $default";
2203 4 return $default;
2204 }
2205  
2206 # _positive_number: Return $value as text when it is a positive number.
2207 # Purpose: Heatmap options go straight into the JavaScript, so anything that
2208 # is not a plain number must not reach it. The check works on the
2209 # text form so it does not depend on the locale (see _num_val).
2210 # Entry: ($value, $default).
2211 # Exit: $value as a dot-decimal string, or $default when $value is missing,
2212 # not a plain decimal number, <= 0 or >= 1e6.
2213 sub _positive_number
2214 119 ▶{
Subroutine _positive_number: called CC=6 SCAR=17.9
2215 119 my ($value, $default) = @_;
2216  
2217 119 ▶ return $default unless defined($value) && !ref($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value 27 92 119
Condition100%3/3
defined $value and not ref $value
!ll&&!rl&&r
26192
MC/DC100%2/2
defined $value and not ref $value
defined $value not ref $value
Truth table100%3/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
2218  
2219 92 my $str = _num_str($value);
2220 92 $str =~ s/\A\s+|\s+\z//g;
2221 # Plain decimals only: rejects signs, exponents, 'Inf' and 'NaN'
2222 92 ▶ return $default unless $str =~ /\A(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $str =~ /\A(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)\z/ 18 74 92
2223  
2224 74 my $number = _num_val($str);
2225 74 ▶ return $default unless $number > 0 && $number < 1e6;
Branch: 1 branch
BranchTrueFalseTotal
unless $number > 0 and $number < 1000000 5 69 74
Condition100%3/3
$number > 0 and $number < 1000000
!ll&&!rl&&r
3269
MC/DC100%2/2
$number > 0 and $number < 1000000
$number > 0 $number < 1000000
Truth table100%3/3
A and B
A= $number > 0B= $number < 1000000
ABresult
0X0
100
111
2226 69 return _num_str($number);
2227 }
2228  
2229 # _num_str: Return a number as text with '.' as the decimal point.
2230 # Purpose: Perl should print numbers with a '.' whatever the locale, but some
2231 # builds (seen with Perl 5.38.0 on macOS) use the LC_NUMERIC decimal
2232 # point, so 51.5074 prints as '51,5074' under de_DE. That fails
2233 # _validate, and in JavaScript '[51,5074, -0,1278]' is four numbers.
2234 # Entry: Any scalar.
2235 # Exit: A value Perl holds as a number comes back as text with a '.'
2236 # decimal point; anything else (strings, undef, refs) is unchanged.
2237 sub _num_str
2238 6155 ▶{
Subroutine _num_str: called CC=8 SCAR=21.7
2239 6155 my $value = shift;
2240  
2241 6155 ▶ return $value if !defined($value) || ref($value);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or ref $value 6 6149 6155
Condition100%3/3
not defined $value or ref $value
l!l&&r!l&&!r
516149
MC/DC100%2/2
not defined $value or ref $value
not defined $value ref $value
Truth table100%3/3
not(A) or B
A= not defined $valueB= ref $value
ABresult
1X1
011
000
2242  
2243 # Only a value Perl holds as a number can have been printed with a locale
2244 # decimal point; a string such as '51,5' never gets these flags.
2245 6149 my $flags = B::svref_2object(\$value)->FLAGS;
2246 6149 ▶ return $value unless $flags & (B::SVf_IOK() | B::SVf_NOK());
Branch: 1 branch
BranchTrueFalseTotal
unless $flags & 768 4867 1282 6149
2247  
2248 1282 my $str = "$value";
2249 1282 ▶ my $radix = (localeconv() || {})->{decimal_point};
Condition50%1/2
localeconv() || {}
l!l
12820
MC/DC0%0/1
localeconv() || {}
localeconv()
Truth table50%1/2
A
A= localeconv()
Aresult
11
00
2250 1282 ▶ $str =~ s/\Q$radix\E/./ if defined($radix) && length($radix) && $radix ne '.';
Branch: 1 branch
BranchTrueFalseTotal
if defined $radix and length $radix and $radix ne "." 0 1282 1282
Condition33%2/6
defined $radix and length $radix and $radix ne "."
!ll&&!rl&&r
012820
defined $radix and length $radix
!ll&&!rl&&r
001282
MC/DC0%0/3
defined $radix and length $radix and $radix ne "."
defined $radix length $radix $radix ne "."
Truth table25%1/4
A and B and C
A= defined $radixB= length $radixC= $radix ne "."
ABCresult
0XX0
10X0
1100
1111
2251 1282 $str =~ tr/,/./; # Perl never groups digits, so a comma can only be a decimal point
2252 1282 return $str;
2253 }
2254  
2255 # _num_val: Convert a decimal string such as '-0.1278' to a number.
2256 # Purpose: The perls that print numbers with the locale's decimal point also
2257 # read them that way, so under de_DE '51.5074' + 0 is 51. Building
2258 # the value from its whole and fractional digit strings uses only
2259 # integer conversion, which no locale affects.
2260 # Entry: A number, or a string in the form _validate accepts.
2261 # Exit: The numeric value. Anything else falls back to Perl's own conversion.
2262 sub _num_val
2263 2981 ▶{
Subroutine _num_val: called CC=7 SCAR=19.5
2264 2981 my $str = _num_str(shift);
2265  
2266 2981 my ($sign, $whole, $frac) = $str =~ /\A(-?)([0-9]*)(?:\.([0-9]+))?\z/;
2267 2981 ▶ if(!defined($sign) || (!length($whole) && !defined($frac))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sign and length $whole || defined $frac) 2 2979 2981
Condition100%6/6
defined $sign and length $whole || defined $frac
!ll&&!rl&&r
112979
length $whole or defined $frac
l!l&&r!l&&!r
2964151
MC/DC100%3/3
defined $sign and length $whole || defined $frac
defined $sign length $whole defined $frac
Truth table100%4/4
A and B or C
A= defined $signB= length $wholeC= defined $frac
ABCresult
0XX0
1000
11X1
1011
2268 18 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
2269 2 return 0 + $str;
2270 }
2271  
2272 2979 ▶ my $value = length($whole) ? 0 + $whole : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $whole ? : 2964 15 2979
2273 2979 ▶ $value += $frac / (10 ** length($frac)) if defined($frac);
Branch: 1 branch
BranchTrueFalseTotal
if defined $frac 2641 338 2979
2274 2979 ▶ return $sign ? -$value : $value;
Branch: 1 branch
BranchTrueFalseTotal
$sign ? : 1248 1731 2979
2275 }
2276  
2277 =head1 LIMITATIONS
2278  
2279 =over 4
2280  
2281 =item * B<Per-marker removal>: Markers added via C<add_marker()> cannot yet be
2282 removed individually by clicking them. The "Clear search markers" button only
2283 removes markers added by the in-page Nominatim search box.
2284  
2285 =item * B<Clone validation>: The clone path (C<< $obj->new(%overrides) >>)
2286 bypasses the Params::Validate::Strict schema so subclasses and internal callers
2287 can merge arbitrary state. Callers are responsible for passing valid overrides.
2288  
2289 =item * B<Config-file params unvalidated>: Keys injected by
2290 L<Object::Configure> from a config file are not re-run through the schema, so
2291 a malformed config file can introduce invalid types at runtime.
2292 C<onload_render()> checks C<zoom>, C<max_zoom>, C<width> and C<height> again and
2293 HTML-escapes the CDN URLs, so a bad value cannot inject markup into the page.
2294  
2295 =item * B<One map per page>: The rendered HTML uses fixed element IDs
2296 (C<map>, C<search-box>, C<clear-search-button> and C<reset-button>), so two
2297 maps on the same page will clash.
2298  
2299 =item * B<Clustered circle markers>: With C<< cluster => 1 >>, circle markers
2300 are grouped with the pin markers, so at low zoom levels a cluster count is
2301 shown in place of the circles' sizes. Leave C<cluster> off for a bubble map
2302 whose sizes should always be visible.
2303  
2304 =item * B<Private-method encapsulation>: C<_fetch_coordinates>, C<_validate>,
2305 and C<_js_string> are named with a leading underscore by convention only.
2306 Using L<Sub::Private> in C<enforce> mode would make the contract explicit, but
2307 that module is not yet listed as a dependency to avoid breaking white-box tests
2308 in C<t/mock.t>.
2309  
2310 =item * B<Routing>: Turn-by-turn routing (Leaflet Routing Machine / OSRM) is
2311 explicitly out of scope for this module and will not be added here.
2312  
2313 =back
2314  
2315 =head1 AUTHOR
2316  
2317 Nigel Horne, C<< <njh at nigelhorne.com> >>
2318  
2319 =head1 BUGS
2320  
2321 Please report bugs at L<https://github.com/nigelhorne/HTML-OSM/issues>.
2322  
2323 =head1 SEE ALSO
2324  
2325 =over 4
2326  
2327 =item * L<https://wiki.openstreetmap.org/wiki/API>
2328  
2329 =item * L<HTML::GoogleMaps::V3> - the interface this module mirrors for compatibility.
2330  
2331 =item * L<https://leafletjs.com/>
2332  
2333 =item * L<Configure an Object at Runtime|Object::Configure>
2334  
2335 =item * L<Test Dashboard|https://nigelhorne.github.io/HTML-OSM/coverage/>
2336  
2337 =back
2338  
2339 =head1 SUPPORT
2340  
2341 This module is provided as-is without any warranty.
2342  
2343 Please report problems and ask questions at
2344 L<https://github.com/nigelhorne/HTML-OSM/issues>.
2345  
2346 You can find documentation for this module with the perldoc command.
2347  
2348 perldoc HTML::OSM
2349  
2350 You can also look for information at MetaCPAN:
2351 L<https://metacpan.org/dist/HTML-OSM>.
2352  
2353 =head2 TODO
2354  
2355 Allow per-marker removal via clicking on a marker.
2356  
2357 =encoding utf-8
2358  
2359 =head1 FORMAL SPECIFICATION
2360  
2361 =head2 new
2362  
2363 HTML_OSM
2364 coordinates : iseq (ℝ x ℝ x S x S x (S ∪ {∅}))
2365 zoom : Z
2366 cluster : B
2367 scale : B
2368 legend : iseq LegendEntry
2369 legend_position : {topright, topleft, bottomright, bottomleft}
2370 ----------------------------------------
2371 ZOOM_MIN <= zoom <= ZOOM_MAX
2372  
2373 LegendEntry
2374 label : S | label ≠ ''
2375 colour : HexColour
2376 radius : ℝ ∪ {∅} | radius = ∅ ∨ 0 < radius < 10^6
2377 group : S ∪ {∅}
2378  
2379 new ≙
2380 params? : Params
2381 osm! : HTML_OSM
2382 ----------------------------------------
2383 osm!.zoom = params?.zoom ∨ 12
2384 osm!.cluster = params?.cluster ∨ false
2385 osm!.scale = params?.scale ∨ false
2386 osm!.fit = params?.fit ∨ false
2387 osm!.legend_position = params?.legend_position ∨ topright
2388  
2389 =head2 add_marker
2390  
2391 AddMarker
2392 ΔHTML_OSM
2393 point? : (ℝ x ℝ) ∪ S ∪ GeoObject
2394 result! : {0, 1}
2395 -----------------------------------------
2396 result! = 1 ⟺ point? resolves to (lat, lon) ∈ ValidCoord
2397 result! = 1 ⟹ coordinates' = coordinates ⌢ ⟨(lat, lon, label, icon, group)⟩
2398  
2399 =head2 add_geojson
2400  
2401 AddGeoJSON
2402 ΔHTML_OSM
2403 data? : GeoJSONStruct ∪ S
2404 style? : StyleMap ∪ {∅}
2405 popup? : S ∪ {∅}
2406 name? : S ∪ {∅}
2407 show? : 𝔹 ∪ {∅}
2408 key? : LayerKey ∪ {∅}
2409 -----------------------------------------
2410 name? ≠ ∅ ⇒ name? ≠ ""
2411 key? ≠ ∅ ⇒ #key?.entries ≥ 1 ∧ key?.position ∈ Corner
2412 geojson' = geojson ⌢ ⟨{data, style, popup, name, show, key}⟩
2413  
2414 =head2 add_heatmap
2415  
2416 AddHeatmap
2417 ΔHTML_OSM
2418 points? : iseq (ℝ x ℝ x [0,1])
2419 -----------------------------------------
2420 heatmap_layers' = heatmap_layers ⌢ ⟨{points, radius, blur}⟩
2421  
2422 =head2 add_gpx
2423  
2424 AddGPX
2425 ΔHTML_OSM
2426 url? : S | url? ≠ ''
2427 -----------------------------------------
2428 gpx_tracks' = gpx_tracks ⌢ ⟨url?⟩
2429  
2430 =head2 add_choropleth
2431  
2432 AddChoropleth
2433 ΔHTML_OSM
2434 features? : iseq GeoFeature
2435 values? : S --> ℝ
2436 key? : S
2437 scale? : iseq S
2438 -----------------------------------------
2439 Let min = min(ran values?), max = max(ran values?) ∪ {min+1}
2440 ∀ k ∈ dom values? •
2441 color(k) = scale?[floor((values?(k)-min)/(max-min) * (#scale?-1))]
2442 choropleth_layers' = choropleth_layers ⌢ ⟨{features, values, colors, key}⟩
2443  
2444 =head2 center
2445  
2446 Center
2447 ΔHTML_OSM
2448 point? : (ℝ x ℝ) ∪ S ∪ GeoObject
2449 result! : {0, 1}
2450 -----------------------------------------
2451 result! = 1 ⟺ point? resolves to (lat, lon) ∈ ValidCoord
2452 result! = 1 ⟹ center' = (lat, lon)
2453  
2454 =head2 zoom
2455  
2456 Zoom
2457 ΔHTML_OSM
2458 zoom? : Z ∪ {∅}
2459 zoom! : Z
2460 -----------------------------------------
2461 zoom? ≠ ∅ ⟹ ZOOM_MIN <= zoom? <= ZOOM_MAX
2462 zoom! = (zoom? ≠ ∅ ∧ zoom' = zoom?) ∨ zoom
2463  
2464 =head2 onload_render
2465  
2466 OnloadRender
2467 HTML_OSM
2468 head! : S
2469 body! : S
2470 -----------------------------------------
2471 (#coordinates + #geojson + #heatmap_layers + #gpx_tracks + #choropleth_layers) > 0
2472 center ≠ ∅ ∨ ∃ valid ∈ coordinates • valid ∈ ValidCoord
2473 Let InView(b) = { m.group | m ∈ coordinates ∪ circle_markers • (m.lat, m.lon) ∈ b }
2474 fit ∧ center = ∅ ⟹ the initial view contains every (m.lat, m.lon), at zoom ≤ zoom
2475 ∀ bounds b reached by a move or zoom •
2476 listed(b) = ⟨ e ∈ legend | e.group = ∅ ∨ e.group ∈ InView(b) ⟩
2477  
2478 =head1 LICENSE AND COPYRIGHT
2479  
2480 Copyright 2025-2026 Nigel Horne.
2481  
2482 This program is released under the following licence: GPL2
2483 If you use it,
2484 please let me know.
2485  
2486 =cut
2487  
2488 18 1;
2489  
2490 __END__
↑ Summary