mapyta 0.4.2__tar.gz → 0.5.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. {mapyta-0.4.2 → mapyta-0.5.1}/.gitignore +3 -0
  2. {mapyta-0.4.2 → mapyta-0.5.1}/PKG-INFO +1 -1
  3. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_scripts/generate_index.py +1 -1
  4. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_scripts/generate_reference_pages.py +2 -2
  5. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/min-zoom.md +23 -0
  6. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/map.py +125 -30
  7. mapyta-0.5.1/mapyta/markers.py +233 -0
  8. {mapyta-0.4.2 → mapyta-0.5.1}/pyproject.toml +1 -1
  9. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_layers.py +25 -0
  10. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_markers.py +357 -1
  11. mapyta-0.4.2/mapyta/markers.py +0 -173
  12. {mapyta-0.4.2 → mapyta-0.5.1}/.github/workflows/docs-preview.yml +0 -0
  13. {mapyta-0.4.2 → mapyta-0.5.1}/.github/workflows/docs.yml +0 -0
  14. {mapyta-0.4.2 → mapyta-0.5.1}/.github/workflows/lint.yml +0 -0
  15. {mapyta-0.4.2 → mapyta-0.5.1}/.github/workflows/publish.yml +0 -0
  16. {mapyta-0.4.2 → mapyta-0.5.1}/.github/workflows/tests.yml +0 -0
  17. {mapyta-0.4.2 → mapyta-0.5.1}/.pre-commit-config.yaml +0 -0
  18. {mapyta-0.4.2 → mapyta-0.5.1}/.ruff.toml +0 -0
  19. {mapyta-0.4.2 → mapyta-0.5.1}/LICENSE +0 -0
  20. {mapyta-0.4.2 → mapyta-0.5.1}/README.md +0 -0
  21. {mapyta-0.4.2 → mapyta-0.5.1}/docs/.nav.yml +0 -0
  22. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_overrides/assets/images/favicon.ico +0 -0
  23. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_overrides/assets/images/logo-dark-mode.svg +0 -0
  24. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_overrides/assets/images/mapyta-logo-dark-mode.svg +0 -0
  25. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_overrides/assets/images/mapyta-logo-light-mode.svg +0 -0
  26. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_overrides/assets/javascripts/katex.js +0 -0
  27. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_overrides/assets/stylesheets/extra.css +0 -0
  28. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_overrides/main.html +0 -0
  29. {mapyta-0.4.2 → mapyta-0.5.1}/docs/_scripts/__init__.py +0 -0
  30. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/.nav.yml +0 -0
  31. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/advanced.md +0 -0
  32. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/animated.md +0 -0
  33. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/choropleth.md +0 -0
  34. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/clusters.md +0 -0
  35. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/configuration.md +0 -0
  36. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/coordinates.md +0 -0
  37. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/dataframe.md +0 -0
  38. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/drawing.md +0 -0
  39. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/export.md +0 -0
  40. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/faq.md +0 -0
  41. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/first-map.md +0 -0
  42. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/geodataframe.md +0 -0
  43. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/geometries.md +0 -0
  44. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/heatmaps.md +0 -0
  45. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/index.md +0 -0
  46. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/layers.md +0 -0
  47. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/markers.md +0 -0
  48. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/open-data.md +0 -0
  49. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/text-annotations.md +0 -0
  50. {mapyta-0.4.2 → mapyta-0.5.1}/docs/tutorial/tooltips-popups.md +0 -0
  51. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/__init__.py +0 -0
  52. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/config.py +0 -0
  53. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/coordinates.py +0 -0
  54. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/dataframe.py +0 -0
  55. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/export.py +0 -0
  56. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/geojson.py +0 -0
  57. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/markdown.py +0 -0
  58. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/style.py +0 -0
  59. {mapyta-0.4.2 → mapyta-0.5.1}/mapyta/tiles.py +0 -0
  60. {mapyta-0.4.2 → mapyta-0.5.1}/properdocs.yml +0 -0
  61. {mapyta-0.4.2 → mapyta-0.5.1}/tests/__init__.py +0 -0
  62. {mapyta-0.4.2 → mapyta-0.5.1}/tests/conftest.py +0 -0
  63. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_data.py +0 -0
  64. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_dataframe.py +0 -0
  65. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_draw.py +0 -0
  66. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_export.py +0 -0
  67. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_geometry.py +0 -0
  68. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_map.py +0 -0
  69. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_map_creation.py +0 -0
  70. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_merge_and_chaining.py +0 -0
  71. {mapyta-0.4.2 → mapyta-0.5.1}/tests/test_utilities.py +0 -0
  72. {mapyta-0.4.2 → mapyta-0.5.1}/uv.lock +0 -0
@@ -15,3 +15,6 @@ venv
15
15
  # Test coverage
16
16
  .coverage
17
17
  htmlcov/
18
+
19
+ # Local Claude Code settings
20
+ .claude/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mapyta
3
- Version: 0.4.2
3
+ Version: 0.5.1
4
4
  Summary: Mapyta, open source python package for GIS mapping and visualization.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -3,7 +3,7 @@
3
3
  import re
4
4
  from pathlib import Path
5
5
 
6
- import mkdocs_gen_files
6
+ import mkdocs_gen_files # ty: ignore[unresolved-import]
7
7
 
8
8
  root = Path(__file__).parents[2]
9
9
  readme_file = root / "README.md"
@@ -4,8 +4,8 @@ import logging
4
4
  import sys
5
5
  from pathlib import Path
6
6
 
7
- import mkdocs_gen_files
8
- from natsort import natsorted
7
+ import mkdocs_gen_files # ty: ignore[unresolved-import]
8
+ from natsort import natsorted # ty: ignore[unresolved-import]
9
9
 
10
10
  log = logging.getLogger(f"mkdocs.plugins.{__name__}")
11
11
 
@@ -76,6 +76,29 @@ The check also runs once on load, so layers start hidden if the initial zoom is
76
76
  | `0` | Always visible (treated the same as `None`) |
77
77
  | `13` | Hidden below zoom 13, visible at 13 and above |
78
78
 
79
+ ## Hiding only the caption
80
+
81
+ On `add_point`, you can hide the caption text while keeping the marker icon visible. Pass `min_zoom_caption` to set a separate zoom threshold for the caption:
82
+
83
+ ```python exec="true" html="true" source="tabbed-right"
84
+ from shapely.geometry import Point
85
+ from mapyta import Map, MapConfig
86
+
87
+ m = Map(center=(52.090, 5.120), config=MapConfig(zoom_start=12))
88
+
89
+ # Icon is always visible; the "Dom Tower" label appears only from zoom 15
90
+ m.add_point(
91
+ Point(5.1213, 52.0908),
92
+ marker="🏛️",
93
+ caption="Dom Tower",
94
+ min_zoom_caption=15,
95
+ )
96
+
97
+ print(m.to_html()) # markdown-exec: hide
98
+ ```
99
+
100
+ `min_zoom_caption` is independent of `min_zoom`: if you set both, the icon uses `min_zoom` and the caption uses `min_zoom_caption`. `min_zoom_caption` is ignored when `caption` is not set.
101
+
79
102
  ## Combining with feature groups
80
103
 
81
104
  `min_zoom` and feature groups are independent. A layer can belong to a group *and* have a zoom threshold. The group toggle controls whether the layer is in the map at all; `min_zoom` controls whether it is rendered at the current zoom within that group.
@@ -24,8 +24,10 @@ import io
24
24
  import json
25
25
  import math
26
26
  import tempfile
27
+ import uuid
27
28
  import warnings
28
29
  import webbrowser
30
+ from collections.abc import Mapping
29
31
  from pathlib import Path
30
32
  from typing import Any, Self, cast, overload
31
33
 
@@ -52,7 +54,15 @@ from mapyta.coordinates import transform_geometry
52
54
  from mapyta.export import capture_screenshot
53
55
  from mapyta.geojson import load_geojson_input
54
56
  from mapyta.markdown import RawHTML, markdown_to_html
55
- from mapyta.markers import DEFAULT_CAPTION_CSS, DEFAULT_MARKER_CAPTION_CSS, build_icon_marker, build_text_marker, classify_marker, css_to_style
57
+ from mapyta.markers import (
58
+ DEFAULT_CAPTION_CSS,
59
+ DEFAULT_MARKER_CAPTION_CSS,
60
+ build_icon_marker,
61
+ build_text_marker,
62
+ classify_marker,
63
+ css_to_style,
64
+ px_to_int,
65
+ )
56
66
  from mapyta.style import PALETTES, resolve_style
57
67
  from mapyta.tiles import TILE_PROVIDERS
58
68
 
@@ -99,6 +109,7 @@ class Map:
99
109
  self._active_group: folium.FeatureGroup | folium.Map = self._map
100
110
  self._colormaps: list[cm.LinearColormap | cm.StepColormap] = []
101
111
  self._zoom_controlled_markers: list[dict[str, Any]] = []
112
+ self._zoom_controlled_captions: list[dict[str, Any]] = []
102
113
  self._zoom_js_injected: bool = False
103
114
  self._draw_config: DrawConfig | None = None
104
115
  self._draw_injected: bool = False
@@ -203,7 +214,7 @@ class Map:
203
214
  f'font-weight:bold;box-shadow:0 2px 6px rgba(0,0,0,0.3);pointer-events:none;">'
204
215
  f"{self._title}</div>"
205
216
  )
206
- fmap.get_root().html.add_child(folium.Element(title_html)) # type: ignore[union-attr]
217
+ fmap.get_root().html.add_child(folium.Element(title_html)) # ty: ignore[unresolved-attribute]
207
218
 
208
219
  # Optional plugins
209
220
  if cfg.fullscreen:
@@ -244,7 +255,7 @@ class Map:
244
255
  return None
245
256
  ps = resolve_style(popup_style, PopupStyle) or PopupStyle()
246
257
  html = popup if isinstance(popup, RawHTML) else markdown_to_html(popup)
247
- iframe = folium.IFrame(html, width=ps.width, height=ps.height) # type: ignore[arg-type]
258
+ iframe = folium.IFrame(html, width=ps.width, height=ps.height) # ty: ignore[invalid-argument-type]
248
259
  return folium.Popup(iframe, max_width=ps.max_width)
249
260
 
250
261
  def _target(self) -> folium.FeatureGroup | folium.Map:
@@ -444,7 +455,7 @@ class Map:
444
455
  # Submit button: runs after DOMContentLoaded (after Folium's <script> block).
445
456
  map_var = self._map.get_name()
446
457
  drawn_items_var = f"drawnItems_{draw_plugin.get_name()}"
447
- self._map.get_root().html.add_child( # type: ignore[union-attr]
458
+ self._map.get_root().html.add_child( # ty: ignore[unresolved-attribute]
448
459
  folium.Element(self._build_draw_script(map_var, drawn_items_var))
449
460
  )
450
461
  self._draw_injected = True
@@ -552,7 +563,7 @@ class Map:
552
563
  # Adding geometries
553
564
  # ------------------------------------------------------------------
554
565
 
555
- def add_point(
566
+ def add_point( # noqa: PLR0913
556
567
  self,
557
568
  point: Point,
558
569
  marker: str | None = None,
@@ -564,6 +575,7 @@ class Map:
564
575
  tooltip_style: TooltipStyle | dict[str, Any] | None = None,
565
576
  popup_style: PopupStyle | dict[str, Any] | None = None,
566
577
  min_zoom: int | None = None,
578
+ min_zoom_caption: int | None = None,
567
579
  ) -> Self:
568
580
  """Add a location marker.
569
581
 
@@ -599,6 +611,15 @@ class Map:
599
611
  min_zoom : int | None
600
612
  Minimum zoom level at which the marker is visible.
601
613
  ``None`` or ``0`` means always visible.
614
+ min_zoom_caption : int | None
615
+ Minimum zoom level at which the caption is visible. Works like
616
+ ``min_zoom`` but applies only to the caption text — the marker
617
+ icon itself remains visible. ``None`` or ``0`` means always
618
+ visible. Ignored when ``caption`` is not set. Note: caption
619
+ visibility is also bounded below by ``min_zoom`` — the caption
620
+ lives inside the marker's DivIcon DOM, which is removed when
621
+ the marker is hidden, so setting ``min_zoom_caption`` lower
622
+ than ``min_zoom`` does not reveal the caption at those zooms.
602
623
 
603
624
  Returns
604
625
  -------
@@ -611,13 +632,17 @@ class Map:
611
632
  css = marker_style or {}
612
633
  cap_css = {**DEFAULT_MARKER_CAPTION_CSS, **(caption_style or {})}
613
634
 
635
+ caption_id: str | None = None
636
+ if caption is not None and min_zoom_caption is not None and min_zoom_caption > 0:
637
+ caption_id = f"caption_{uuid.uuid4().hex[:15]}"
638
+
614
639
  kind = classify_marker(marker) if marker else "icon_name"
615
640
  if kind == "emoji":
616
641
  assert marker is not None # guarded by classify_marker above
617
- icon = build_text_marker(marker, css, caption, cap_css)
642
+ icon = build_text_marker(marker, css, caption, cap_css, caption_id)
618
643
  else:
619
644
  icon_name = marker or "arrow-down"
620
- icon = build_icon_marker(icon_name, css, caption, cap_css)
645
+ icon = build_icon_marker(icon_name, css, caption, cap_css, caption_id)
621
646
 
622
647
  m = folium.Marker(
623
648
  location=[lat, lon],
@@ -627,7 +652,15 @@ class Map:
627
652
  )
628
653
  m.add_to(self._target())
629
654
  self._record_feature(
630
- point, {"marker": marker, "caption": caption, "tooltip": self._raw_text(tooltip), "popup": self._raw_text(popup), "min_zoom": min_zoom}
655
+ point,
656
+ {
657
+ "marker": marker,
658
+ "caption": caption,
659
+ "tooltip": self._raw_text(tooltip),
660
+ "popup": self._raw_text(popup),
661
+ "min_zoom": min_zoom,
662
+ "min_zoom_caption": min_zoom_caption,
663
+ },
631
664
  )
632
665
 
633
666
  if min_zoom is not None and min_zoom > 0:
@@ -638,6 +671,15 @@ class Map:
638
671
  }
639
672
  )
640
673
 
674
+ if caption_id is not None:
675
+ assert min_zoom_caption is not None # guarded above
676
+ self._zoom_controlled_captions.append(
677
+ {
678
+ "caption_id": caption_id,
679
+ "min_zoom": min_zoom_caption,
680
+ }
681
+ )
682
+
641
683
  return self
642
684
 
643
685
  def add_circle(
@@ -1167,7 +1209,7 @@ class Map:
1167
1209
  geojson_data: dict | str | Path,
1168
1210
  value_column: str,
1169
1211
  key_on: str,
1170
- values: dict[str, float | str] | None = None,
1212
+ values: Mapping[str, float | str] | None = None,
1171
1213
  vmin: float | None = None,
1172
1214
  vmax: float | None = None,
1173
1215
  legend_name: str | None = None,
@@ -1225,7 +1267,7 @@ class Map:
1225
1267
 
1226
1268
  # Extract values if not provided
1227
1269
  if values is None:
1228
- values = {}
1270
+ extracted: dict[str, float | str] = {}
1229
1271
  key_parts = key_on.split(".")
1230
1272
  for feat in geojson_data.get("features", []):
1231
1273
  obj = feat
@@ -1234,7 +1276,8 @@ class Map:
1234
1276
  key = obj if isinstance(obj, str) else str(obj)
1235
1277
  raw_val = feat.get("properties", {}).get(value_column)
1236
1278
  if raw_val is not None:
1237
- values[key] = raw_val
1279
+ extracted[key] = raw_val
1280
+ values = extracted
1238
1281
 
1239
1282
  # Determine if categorical
1240
1283
  raw_vals = list(values.values())
@@ -1374,7 +1417,7 @@ class Map:
1374
1417
  else:
1375
1418
  heat_data.append(list(p[:3]))
1376
1419
  self._bounds.append((p[0], p[1]))
1377
- self._record_feature(Point(p[1], p[0]), {"intensity": p[2]}) # type: ignore[index]
1420
+ self._record_feature(Point(p[1], p[0]), {"intensity": p[2]}) # ty: ignore[index-out-of-bounds]
1378
1421
 
1379
1422
  kwargs: dict[str, Any] = {
1380
1423
  "radius": hs.radius,
@@ -1548,7 +1591,7 @@ class Map:
1548
1591
  step_points.append([pt.y, pt.x])
1549
1592
  elif len(p) == 3:
1550
1593
  self._bounds.append((p[0], p[1]))
1551
- step_points.append([p[0], p[1], p[2]]) # type: ignore[index]
1594
+ step_points.append([p[0], p[1], p[2]]) # ty: ignore[index-out-of-bounds]
1552
1595
  else:
1553
1596
  self._bounds.append((p[0], p[1]))
1554
1597
  step_points.append([p[0], p[1]])
@@ -1679,6 +1722,7 @@ class Map:
1679
1722
  captions: list[str] | None = None,
1680
1723
  caption_style: dict[str, str] | None = None,
1681
1724
  tooltip_style: TooltipStyle | dict[str, Any] | None = None,
1725
+ min_zoom_caption: int | None = None,
1682
1726
  ) -> Self:
1683
1727
  """Add clustered markers that group at low zoom.
1684
1728
 
@@ -1706,6 +1750,15 @@ class Map:
1706
1750
  CSS property overrides for ``captions``.
1707
1751
  tooltip_style : TooltipStyle | dict[str, Any] | None
1708
1752
  Tooltip appearance (font size, width, etc.).
1753
+ min_zoom_caption : int | None
1754
+ Minimum zoom level at which captions are visible. Applies only
1755
+ to the caption text — the marker icons remain visible. ``None``
1756
+ or ``0`` means always visible. Ignored for entries without a
1757
+ caption. Note: caption visibility is also bounded below by
1758
+ each entry's ``min_zoom`` — the caption lives inside the
1759
+ marker's DivIcon DOM, which is removed when the marker is
1760
+ hidden, so setting ``min_zoom_caption`` lower than ``min_zoom``
1761
+ does not reveal the caption at those zooms.
1709
1762
 
1710
1763
  Returns
1711
1764
  -------
@@ -1714,6 +1767,7 @@ class Map:
1714
1767
  css = marker_style or {}
1715
1768
  cap_css = {**DEFAULT_MARKER_CAPTION_CSS, **(caption_style or {})}
1716
1769
  cluster = folium.plugins.MarkerCluster(name=name)
1770
+ track_captions = min_zoom_caption is not None and min_zoom_caption > 0
1717
1771
 
1718
1772
  for i, point in enumerate(points):
1719
1773
  pt = cast(Point, self._transform(point))
@@ -1725,13 +1779,17 @@ class Map:
1725
1779
  popup = popups[i] if popups and i < len(popups) else None
1726
1780
  txt = captions[i] if captions and i < len(captions) else None
1727
1781
 
1782
+ caption_id: str | None = None
1783
+ if txt is not None and track_captions:
1784
+ caption_id = f"caption_{uuid.uuid4().hex[:15]}"
1785
+
1728
1786
  kind = classify_marker(label) if label else "icon_name"
1729
1787
  if kind == "emoji":
1730
1788
  assert label is not None # guarded by classify_marker above
1731
- icon = build_text_marker(label, css, txt, cap_css)
1789
+ icon = build_text_marker(label, css, txt, cap_css, caption_id)
1732
1790
  else:
1733
1791
  icon_name = label or "arrow-down"
1734
- icon = build_icon_marker(icon_name, css, txt, cap_css)
1792
+ icon = build_icon_marker(icon_name, css, txt, cap_css, caption_id)
1735
1793
 
1736
1794
  folium.Marker(
1737
1795
  location=[lat, lon],
@@ -1739,7 +1797,26 @@ class Map:
1739
1797
  tooltip=self._make_tooltip(tip, tooltip_style),
1740
1798
  popup=self._make_popup(popup, popup_style),
1741
1799
  ).add_to(cluster)
1742
- self._record_feature(pt, {"marker": label, "caption": txt, "tooltip": tip, "popup": popup, "min_zoom": min_zoom})
1800
+ self._record_feature(
1801
+ pt,
1802
+ {
1803
+ "marker": label,
1804
+ "caption": txt,
1805
+ "tooltip": tip,
1806
+ "popup": popup,
1807
+ "min_zoom": min_zoom,
1808
+ "min_zoom_caption": min_zoom_caption,
1809
+ },
1810
+ )
1811
+
1812
+ if caption_id is not None:
1813
+ assert min_zoom_caption is not None # guarded by track_captions above
1814
+ self._zoom_controlled_captions.append(
1815
+ {
1816
+ "caption_id": caption_id,
1817
+ "min_zoom": min_zoom_caption,
1818
+ }
1819
+ )
1743
1820
 
1744
1821
  cluster.add_to(self._target())
1745
1822
  if min_zoom is not None and min_zoom > 0:
@@ -1801,16 +1878,23 @@ class Map:
1801
1878
  self._bounds.append((lat, lon))
1802
1879
 
1803
1880
  css_str = css_to_style(merged)
1804
- # Estimate icon size from text length and font size so the anchor
1805
- # centers the marker on the coordinate and Leaflet doesn't render a
1806
- # phantom shadow from a zero-sized container.
1807
- fs = int(merged.get("font-size", "12px").replace("px", ""))
1808
- est_w = max(len(text) * fs * 0.65 + 16, 20)
1809
- est_h = fs + 12
1881
+ # icon_size is a small fixed box around the anchor (depends on
1882
+ # font-size only, not on text length). The text is absolutely
1883
+ # centered on the anchor and overflows via overflow:visible, so
1884
+ # long labels render fully without widening the Leaflet icon box.
1885
+ fs = px_to_int(merged.get("font-size", "12px"), 12)
1886
+ w = fs + 10
1887
+ h = fs + 10
1888
+ html = (
1889
+ f'<div style="position:relative;width:{w}px;height:{h}px;overflow:visible;">'
1890
+ f'<div style="position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);'
1891
+ f'white-space:nowrap;{css_str}">{text}</div>'
1892
+ f"</div>"
1893
+ )
1810
1894
  icon = folium.DivIcon(
1811
- html=f'<div style="{css_str}">{text}</div>',
1812
- icon_size="100%", # type: ignore[arg-type] # Let CSS control sizing
1813
- icon_anchor=(int(est_w // 2), int(est_h // 2)),
1895
+ html=html,
1896
+ icon_size=(w, h),
1897
+ icon_anchor=(w // 2, h // 2),
1814
1898
  class_name="",
1815
1899
  )
1816
1900
  marker = folium.Marker(
@@ -2130,6 +2214,7 @@ class Map:
2130
2214
  result._feature_groups.update(other._feature_groups)
2131
2215
  result._colormaps.extend(other._colormaps)
2132
2216
  result._zoom_controlled_markers.extend(other._zoom_controlled_markers)
2217
+ result._zoom_controlled_captions.extend(other._zoom_controlled_captions)
2133
2218
  return result
2134
2219
 
2135
2220
  # ------------------------------------------------------------------
@@ -2142,15 +2227,17 @@ class Map:
2142
2227
  return self._map
2143
2228
 
2144
2229
  def _generate_zoom_javascript(self) -> str:
2145
- """Generate JavaScript for zoom-dependent marker visibility.
2230
+ """Generate JavaScript for zoom-dependent marker and caption visibility.
2146
2231
 
2147
2232
  Returns
2148
2233
  -------
2149
2234
  str
2150
- A ``<script>`` block that toggles marker visibility based on zoom.
2235
+ A ``<script>`` block that toggles marker and caption visibility
2236
+ based on the current zoom level.
2151
2237
  """
2152
2238
  ids = ", ".join(f'"{m["var_name"]}"' for m in self._zoom_controlled_markers)
2153
2239
  marker_config = ", ".join(f'{{id: "{m["var_name"]}", minZoom: {m["min_zoom"]}}}' for m in self._zoom_controlled_markers)
2240
+ caption_config = ", ".join(f'{{id: "{c["caption_id"]}", minZoom: {c["min_zoom"]}}}' for c in self._zoom_controlled_captions)
2154
2241
  return (
2155
2242
  "<script>\n"
2156
2243
  "document.addEventListener('DOMContentLoaded', function() {\n"
@@ -2166,6 +2253,7 @@ class Map:
2166
2253
  " clearInterval(checkInterval);\n"
2167
2254
  " var map = window[mapContainer.id];\n"
2168
2255
  " var configs = [" + marker_config + "];\n"
2256
+ " var captions = [" + caption_config + "];\n"
2169
2257
  " function update() {\n"
2170
2258
  " var z = map.getZoom();\n"
2171
2259
  " configs.forEach(function(c) {\n"
@@ -2174,6 +2262,13 @@ class Map:
2174
2262
  " if (z >= c.minZoom) { el.addTo(map); }\n"
2175
2263
  " else { map.removeLayer(el); }\n"
2176
2264
  " });\n"
2265
+ # Re-query captions on each update — the DivIcon DOM is recreated when
2266
+ # a marker is re-added to the map, so any prior display toggle is lost.
2267
+ " captions.forEach(function(c) {\n"
2268
+ " var el = document.getElementById(c.id);\n"
2269
+ " if (!el) { return; }\n"
2270
+ " el.style.display = z >= c.minZoom ? '' : 'none';\n"
2271
+ " });\n"
2177
2272
  " }\n"
2178
2273
  " map.on('zoomend', update);\n"
2179
2274
  " update();\n"
@@ -2187,8 +2282,8 @@ class Map:
2187
2282
  """Fit bounds and inject zoom JS / draw plugin / export button (idempotent)."""
2188
2283
  if not self._center:
2189
2284
  self._fit_bounds()
2190
- if self._zoom_controlled_markers and not self._zoom_js_injected:
2191
- self._map.get_root().html.add_child(folium.Element(self._generate_zoom_javascript())) # type: ignore[union-attr]
2285
+ if (self._zoom_controlled_markers or self._zoom_controlled_captions) and not self._zoom_js_injected:
2286
+ self._map.get_root().html.add_child(folium.Element(self._generate_zoom_javascript())) # ty: ignore[unresolved-attribute]
2192
2287
  self._zoom_js_injected = True
2193
2288
  if self._draw_config and not self._draw_injected:
2194
2289
  self._inject_draw_plugin()
@@ -2337,7 +2432,7 @@ class Map:
2337
2432
  "});\n"
2338
2433
  "</script>\n"
2339
2434
  )
2340
- self._map.get_root().html.add_child(folium.Element(script)) # type: ignore[union-attr]
2435
+ self._map.get_root().html.add_child(folium.Element(script)) # ty: ignore[unresolved-attribute]
2341
2436
 
2342
2437
  @overload
2343
2438
  def to_image(
@@ -0,0 +1,233 @@
1
+ """Marker building utilities."""
2
+
3
+ from typing import Literal
4
+
5
+ import folium
6
+
7
+ # Default CSS for marker styles
8
+ DEFAULT_ICON_CSS: dict[str, str] = {
9
+ "font-size": "20px",
10
+ "color": "#002855",
11
+ }
12
+
13
+ DEFAULT_TEXT_CSS: dict[str, str] = {
14
+ "font-size": "16px",
15
+ "color": "black",
16
+ }
17
+
18
+ DEFAULT_CAPTION_CSS: dict[str, str] = {
19
+ "font-size": "12px",
20
+ "font-family": "Arial, sans-serif",
21
+ "color": "#333333",
22
+ "font-weight": "bold",
23
+ "background-color": "rgba(255,255,255,0.8)",
24
+ "border": "1px solid #cccccc",
25
+ "padding": "2px 6px",
26
+ "white-space": "nowrap",
27
+ "text-align": "center",
28
+ }
29
+
30
+ # Caption style when used under a marker (transparent background, no border)
31
+ DEFAULT_MARKER_CAPTION_CSS: dict[str, str] = {
32
+ **DEFAULT_CAPTION_CSS,
33
+ "background-color": "transparent",
34
+ "border": "none",
35
+ }
36
+
37
+
38
+ def css_to_style(css: dict[str, str]) -> str:
39
+ """Convert a CSS property dict to an inline style string."""
40
+ return ";".join(f"{k}:{v}" for k, v in css.items())
41
+
42
+
43
+ def px_to_int(value: str, default: int) -> int:
44
+ """Convert a CSS length string like ``"12px"`` or ``"12.5px"`` to an int.
45
+
46
+ Falls back to ``default`` for non-``px`` units (``"1em"``, ``"medium"``)
47
+ and malformed values so icon size estimation never raises.
48
+ """
49
+ try:
50
+ return int(float(value.strip().removesuffix("px")))
51
+ except (ValueError, AttributeError):
52
+ return default
53
+
54
+
55
+ def classify_marker(s: str) -> Literal["emoji", "icon_class", "icon_name"]:
56
+ """Classify a marker string.
57
+
58
+ Returns
59
+ -------
60
+ "emoji"
61
+ Non-ASCII content (emojis, unicode symbols) → render as text.
62
+ "icon_class"
63
+ Full CSS class string containing a space (e.g. ``"fa fa-home"``) → use as-is.
64
+ "icon_name"
65
+ Bare icon name (e.g. ``"home"``, ``"fa-arrow-right"``) → auto-prefix.
66
+ """
67
+ if not s or not all(c.isascii() for c in s):
68
+ return "emoji"
69
+ if " " in s:
70
+ return "icon_class"
71
+ return "icon_name"
72
+
73
+
74
+ def _absolute_caption_html(
75
+ text: str,
76
+ css: dict[str, str],
77
+ top_px: int,
78
+ element_id: str | None = None,
79
+ ) -> str:
80
+ """Build a caption pinned to the horizontal center of its parent.
81
+
82
+ The caption is rendered as an absolutely-positioned ``<div>`` so its
83
+ own midpoint is anchored at ``left:50%`` of the parent, regardless of
84
+ how wide the caption text grows. The caller is responsible for
85
+ giving the parent ``position:relative`` and ``overflow:visible``.
86
+
87
+ Parameters
88
+ ----------
89
+ text : str
90
+ Caption text.
91
+ css : dict[str, str]
92
+ CSS property overrides merged onto :data:`DEFAULT_CAPTION_CSS`.
93
+ top_px : int
94
+ Vertical offset, in pixels, from the parent's top edge to the
95
+ caption's top edge. Typically the glyph height plus a small gap.
96
+ element_id : str | None
97
+ Optional DOM ``id`` on the caption ``<div>``, used by
98
+ zoom-dependent visibility JS to target the caption independently
99
+ of its marker.
100
+
101
+ Returns
102
+ -------
103
+ str
104
+ HTML ``<div>`` string.
105
+ """
106
+ merged = {
107
+ **DEFAULT_CAPTION_CSS,
108
+ **css,
109
+ "position": "absolute",
110
+ "left": "50%",
111
+ "top": f"{top_px}px",
112
+ "transform": "translateX(-50%)",
113
+ }
114
+ # When zoom-gated (element_id set), start hidden so the caption doesn't
115
+ # flash before the zoom JS runs its first visibility check.
116
+ if element_id:
117
+ merged["display"] = "none"
118
+ id_attr = f' id="{element_id}"' if element_id else ""
119
+ return f'<div{id_attr} style="{css_to_style(merged)}">{text}</div>'
120
+
121
+
122
+ def _marker_wrapper_html(inner_html: str, width: int, height: int) -> str:
123
+ """Build the flex-centred outer wrapper shared by both marker builders.
124
+
125
+ Sized to match the DivIcon's ``icon_size`` and uses flex centring so the
126
+ glyph's visual centre coincides with ``icon_anchor`` regardless of the
127
+ FontAwesome viewBox aspect ratio (e.g. ``fa-xmark`` is 0.75em wide).
128
+ Captions are nested inside this wrapper (not siblings) so click/hover
129
+ events bubble up to the Leaflet marker even though they render outside
130
+ ``icon_size`` via ``overflow:visible``.
131
+ """
132
+ return (
133
+ f'<div style="position:relative;display:flex;align-items:center;'
134
+ f"justify-content:center;width:{width}px;height:{height}px;"
135
+ f'overflow:visible;line-height:1;">{inner_html}</div>'
136
+ )
137
+
138
+
139
+ def build_icon_marker(
140
+ icon: str,
141
+ css: dict[str, str],
142
+ caption: str | None,
143
+ caption_css: dict[str, str],
144
+ caption_id: str | None = None,
145
+ ) -> folium.DivIcon:
146
+ """Build an icon-based DivIcon marker with optional caption.
147
+
148
+ Parameters
149
+ ----------
150
+ icon : str
151
+ Icon name or full CSS class string. Strings containing a space
152
+ (e.g. ``"fa-solid fa-house"``) are used verbatim. Bare names
153
+ starting with ``"fa-"`` get an ``"fa-solid"`` prefix; other bare
154
+ names (e.g. ``"home"``) get a ``"glyphicon"`` prefix.
155
+ css : dict[str, str]
156
+ CSS property overrides for the icon element.
157
+ caption : str | None
158
+ Optional caption text below the icon.
159
+ caption_css : dict[str, str]
160
+ CSS property overrides for the caption.
161
+ caption_id : str | None
162
+ Optional DOM ``id`` on the caption ``<div>``, used by zoom-dependent
163
+ visibility JS to target the caption independently of its marker.
164
+
165
+ Returns
166
+ -------
167
+ folium.DivIcon
168
+ """
169
+ merged = {**DEFAULT_ICON_CSS, **css}
170
+ style_str = css_to_style(merged)
171
+ # Full CSS class string (contains a space) → use as-is
172
+ # Bare name starting with "fa-" → FontAwesome 6 (fa-solid prefix)
173
+ # Other bare name → Glyphicon
174
+ if " " in icon:
175
+ icon_class = icon
176
+ elif icon.startswith("fa-"):
177
+ icon_class = f"fa-solid {icon}"
178
+ else:
179
+ icon_class = f"glyphicon glyphicon-{icon}"
180
+ fs = px_to_int(merged.get("font-size", "20px"), 20)
181
+ glyph_html = f'<i class="{icon_class}" style="{style_str};line-height:1;vertical-align:top;"></i>'
182
+ caption_html = _absolute_caption_html(caption, caption_css, top_px=fs + 2, element_id=caption_id) if caption else ""
183
+ w = fs
184
+ h = fs
185
+ html = _marker_wrapper_html(f"{glyph_html}{caption_html}", w, h)
186
+ return folium.DivIcon(
187
+ html=html,
188
+ icon_size=(w, h),
189
+ icon_anchor=(w // 2, h // 2),
190
+ )
191
+
192
+
193
+ def build_text_marker(
194
+ text: str,
195
+ css: dict[str, str],
196
+ caption: str | None,
197
+ caption_css: dict[str, str],
198
+ caption_id: str | None = None,
199
+ ) -> folium.DivIcon:
200
+ """Build a text/emoji DivIcon marker with optional caption.
201
+
202
+ Parameters
203
+ ----------
204
+ text : str
205
+ The actual text/emoji to render.
206
+ css : dict[str, str]
207
+ CSS property overrides for the text element.
208
+ caption : str | None
209
+ Optional caption text below the text.
210
+ caption_css : dict[str, str]
211
+ CSS property overrides for the caption.
212
+ caption_id : str | None
213
+ Optional DOM ``id`` on the caption ``<div>``, used by zoom-dependent
214
+ visibility JS to target the caption independently of its marker.
215
+
216
+ Returns
217
+ -------
218
+ folium.DivIcon
219
+ A DivIcon rendering the text and optional caption.
220
+ """
221
+ merged = {**DEFAULT_TEXT_CSS, **css}
222
+ style_str = css_to_style(merged) + ";text-align:center;line-height:1"
223
+ fs = px_to_int(merged.get("font-size", "16px"), 16)
224
+ glyph_html = f'<div style="{style_str}">{text}</div>'
225
+ caption_html = _absolute_caption_html(caption, caption_css, top_px=fs + 2, element_id=caption_id) if caption else ""
226
+ w = fs + 10
227
+ h = fs + 10
228
+ html = _marker_wrapper_html(f"{glyph_html}{caption_html}", w, h)
229
+ return folium.DivIcon(
230
+ html=html,
231
+ icon_size=(w, h),
232
+ icon_anchor=(w // 2, h // 2),
233
+ )
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mapyta"
3
- version = "0.4.2"
3
+ version = "0.5.1"
4
4
  description = "Mapyta, open source python package for GIS mapping and visualization."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"