blib/lib/HTML/OSM.pm

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