mapyta 0.8.0__tar.gz → 0.10.0.dev1__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 (73) hide show
  1. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/PKG-INFO +1 -1
  2. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/configuration.md +23 -0
  3. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/drawing.md +11 -1
  4. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/config.py +21 -1
  5. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/map.py +401 -14
  6. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/pyproject.toml +1 -1
  7. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_data.py +91 -0
  8. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_draw.py +206 -0
  9. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_map.py +128 -0
  10. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/uv.lock +1 -1
  11. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.github/workflows/docs-preview.yml +0 -0
  12. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.github/workflows/docs.yml +0 -0
  13. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.github/workflows/lint.yml +0 -0
  14. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.github/workflows/publish.yml +0 -0
  15. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.github/workflows/tests.yml +0 -0
  16. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.gitignore +0 -0
  17. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.pre-commit-config.yaml +0 -0
  18. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/.ruff.toml +0 -0
  19. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/LICENSE +0 -0
  20. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/README.md +0 -0
  21. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/.nav.yml +0 -0
  22. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_overrides/assets/images/favicon.ico +0 -0
  23. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_overrides/assets/images/logo-dark-mode.svg +0 -0
  24. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_overrides/assets/images/mapyta-logo-dark-mode.svg +0 -0
  25. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_overrides/assets/images/mapyta-logo-light-mode.svg +0 -0
  26. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_overrides/assets/javascripts/katex.js +0 -0
  27. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_overrides/assets/stylesheets/extra.css +0 -0
  28. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_overrides/main.html +0 -0
  29. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_scripts/__init__.py +0 -0
  30. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_scripts/generate_index.py +0 -0
  31. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/_scripts/generate_reference_pages.py +0 -0
  32. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/.nav.yml +0 -0
  33. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/advanced.md +0 -0
  34. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/animated.md +0 -0
  35. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/choropleth.md +0 -0
  36. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/clusters.md +0 -0
  37. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/coordinates.md +0 -0
  38. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/dataframe.md +0 -0
  39. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/export.md +0 -0
  40. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/faq.md +0 -0
  41. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/first-map.md +0 -0
  42. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/geodataframe.md +0 -0
  43. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/geometries.md +0 -0
  44. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/heatmaps.md +0 -0
  45. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/index.md +0 -0
  46. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/layers.md +0 -0
  47. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/markers.md +0 -0
  48. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/min-zoom.md +0 -0
  49. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/open-data.md +0 -0
  50. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/search.md +0 -0
  51. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/text-annotations.md +0 -0
  52. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/docs/tutorial/tooltips-popups.md +0 -0
  53. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/__init__.py +0 -0
  54. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/coordinates.py +0 -0
  55. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/dataframe.py +0 -0
  56. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/export.py +0 -0
  57. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/geojson.py +0 -0
  58. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/markdown.py +0 -0
  59. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/markers.py +0 -0
  60. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/mouse_position.py +0 -0
  61. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/style.py +0 -0
  62. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/mapyta/tiles.py +0 -0
  63. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/properdocs.yml +0 -0
  64. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/__init__.py +0 -0
  65. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/conftest.py +0 -0
  66. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_dataframe.py +0 -0
  67. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_export.py +0 -0
  68. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_geometry.py +0 -0
  69. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_layers.py +0 -0
  70. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_map_creation.py +0 -0
  71. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_markers.py +0 -0
  72. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_merge_and_chaining.py +0 -0
  73. {mapyta-0.8.0 → mapyta-0.10.0.dev1}/tests/test_utilities.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mapyta
3
- Version: 0.8.0
3
+ Version: 0.10.0.dev1
4
4
  Summary: Mapyta, open source python package for GIS mapping and visualization.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -39,6 +39,7 @@ print(m.to_html()) # markdown-exec: hide
39
39
  | `fullscreen` | `False` | Add fullscreen button |
40
40
  | `minimap` | `False` | Add inset minimap |
41
41
  | `measure_control` | `False` | Add distance/area measurement tool |
42
+ | `home_button` | `False` | Add a ⌂ reset-view button (top-right, above the measure control) that returns the map to its opening center/zoom |
42
43
  | `mouse_position` | `True` | Show cursor coordinates |
43
44
  | `mouse_position_crs` | `None` | CRS for the cursor readout, e.g. `"EPSG:28992"` for RD New. `None` shows WGS84 lat/lon. Ignored when `mouse_position` is `False`. |
44
45
 
@@ -129,6 +130,28 @@ m.add_tile_layer(name="cartodb_dark")
129
130
  m.add_layer_control(collapsed=False)
130
131
  ```
131
132
 
133
+ ## Reset-view button
134
+
135
+ Adding `home_button=True` gives the user a ⌂ button back to the map's opening view — the `center`/`zoom_start` you set,
136
+ or the data bounds Mapyta auto-fitted.
137
+
138
+ ```python exec="true" html="true" source="tabbed-right"
139
+ from shapely.geometry import Point
140
+ from mapyta import Map, MapConfig
141
+
142
+ m = Map(
143
+ center=(52.090, 5.121),
144
+ title="Reset view",
145
+ config=MapConfig(zoom_start=14, home_button=True, measure_control=True),
146
+ )
147
+ m.add_point(Point(5.1213, 52.0908), marker="📍", tooltip="**Dom Tower**")
148
+
149
+ m.to_html("home_button.html")
150
+ print(m.to_html()) # markdown-exec: hide
151
+ ```
152
+
153
+ The button renders at the top-right, above the measure control when both are enabled.
154
+
132
155
  ## Cursor coordinates in a projected CRS
133
156
 
134
157
  By default the bottom-left readout shows the cursor position as WGS84 latitude/longitude. Set `mouse_position_crs` to
@@ -23,6 +23,13 @@ Use the toolbar in the **top-left corner** of the map to draw:
23
23
  - Click on the map to add points; double-click to finish a shape
24
24
  - Click **Submit** (bottom-right) to download a GeoJSON file with all drawn shapes
25
25
 
26
+ When editing is enabled (the default, `edit=True`), there is **no global edit/delete toolbar** — editing and deleting both happen per shape, in place:
27
+
28
+ - **Edit:** click any drawn shape to edit its vertices in place — drag the vertices to reshape it, drag a midpoint marker to add one. Click empty map space to stop editing.
29
+ - **Delete:** while a shape is being edited, a **trashbin icon** appears at its last point. Click it and confirm in the small in-map popup to delete that single shape. Or, as a shortcut, press the **Delete** key to remove the shape you're editing immediately (no confirmation).
30
+
31
+ Set `edit=False` to make drawn shapes inert (no in-place editing, no trashbin). The confirmation popup text is configurable via `delete_confirm_message`, `delete_confirm_yes`, and `delete_confirm_no` (English by default) — pass your own strings for other languages.
32
+
26
33
  ## Custom tools
27
34
 
28
35
  Pick only the tools you need:
@@ -80,4 +87,7 @@ This generates `window["myGlobalHandler"](geojson)`.
80
87
  | `position` | `"topleft"` | Toolbar position |
81
88
  | `submit_label` | `"Submit"` | Submit button text |
82
89
  | `draw_style` | `None` | `shapeOptions` override |
83
- | `edit` | `True` | Enable edit/delete controls |
90
+ | `edit` | `True` | Per-shape in-place editing + trashbin delete (no global toolbar) |
91
+ | `delete_confirm_message` | `"Delete this shape?"` | Text in the delete confirmation popup |
92
+ | `delete_confirm_yes` | `"Delete"` | Confirm (delete) button label |
93
+ | `delete_confirm_no` | `"Cancel"` | Cancel button label |
@@ -173,6 +173,11 @@ class MapConfig:
173
173
  Add minimap inset.
174
174
  measure_control : bool
175
175
  Add measure tool.
176
+ home_button : bool
177
+ Add a reset-view button (⌂) that returns the map to its opening
178
+ center and zoom — the explicit ``center`` and ``zoom_start`` when
179
+ given, otherwise the auto-fitted data bounds. Rendered at the
180
+ top-right, above the measure control when both are enabled.
176
181
  mouse_position : bool
177
182
  Show cursor coordinates.
178
183
  mouse_position_crs : str | None
@@ -193,6 +198,7 @@ class MapConfig:
193
198
  fullscreen: bool = False
194
199
  minimap: bool = False
195
200
  measure_control: bool = False
201
+ home_button: bool = False
196
202
  mouse_position: bool = True
197
203
  mouse_position_crs: str | None = None
198
204
 
@@ -233,7 +239,18 @@ class DrawConfig:
233
239
  draw_style : dict[str, Any] | None
234
240
  ``shapeOptions`` override for drawn shapes.
235
241
  edit : bool
236
- Whether edit/delete controls are active.
242
+ Whether per-shape editing/deletion is active. When ``True``, clicking a
243
+ drawn shape makes its vertices editable in place (click empty map space
244
+ to stop editing) and shows a trashbin at its last vertex; clicking the
245
+ trashbin and confirming deletes that shape. No global edit/delete
246
+ toolbar buttons are rendered. When ``False``, clicking a shape stays
247
+ inert.
248
+ delete_confirm_message : str
249
+ Text shown in the in-map deletion confirmation popup.
250
+ delete_confirm_yes : str
251
+ Label of the confirm (delete) button in that popup.
252
+ delete_confirm_no : str
253
+ Label of the cancel button in that popup.
237
254
  """
238
255
 
239
256
  tools: list[DrawTool] = field(default_factory=lambda: ["polyline", "polygon", "marker"])
@@ -242,3 +259,6 @@ class DrawConfig:
242
259
  submit_label: str = "Submit"
243
260
  draw_style: dict[str, Any] | None = None
244
261
  edit: bool = True
262
+ delete_confirm_message: str = "Delete this shape?"
263
+ delete_confirm_yes: str = "Delete"
264
+ delete_confirm_no: str = "Cancel"
@@ -35,6 +35,8 @@ import branca.colormap as cm
35
35
  import folium
36
36
  import folium.features
37
37
  import folium.plugins
38
+ from branca.element import MacroElement
39
+ from folium.template import Template
38
40
  from shapely.geometry import (
39
41
  LinearRing,
40
42
  LineString,
@@ -71,6 +73,72 @@ LEAFLET_DRAW_CSS = "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/le
71
73
  LEAFLET_DRAW_JS = "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"
72
74
  VALID_DRAW_TOOLS = frozenset({"marker", "polyline", "polygon", "rectangle", "circle"})
73
75
 
76
+ # Normalise the size of every corner control button. Leaflet renders the layer
77
+ # and measure toggles at 36px (44px on touch), while the zoom, draw, home and
78
+ # fullscreen buttons sit at 26px (30px on touch). Shrink the two odd ones out so
79
+ # every control button matches. ``!important`` is required because the plugin
80
+ # rules ship from CDNs at equal-or-higher specificity.
81
+ CONTROL_SIZE_CSS = (
82
+ "<style>"
83
+ ".leaflet-control-layers-toggle,"
84
+ ".leaflet-control-measure .leaflet-control-measure-toggle{"
85
+ "width:26px!important;height:26px!important;background-size:16px 16px!important;}"
86
+ ".leaflet-touch .leaflet-control-layers-toggle,"
87
+ ".leaflet-touch .leaflet-control-measure .leaflet-control-measure-toggle{"
88
+ "width:30px!important;height:30px!important;background-size:18px 18px!important;}"
89
+ "</style>"
90
+ )
91
+
92
+
93
+ class _HomeButtonControl(MacroElement):
94
+ """A reset-view button rendered in the map's main script block.
95
+
96
+ Unlike a post-construction injected ``<script>``, this control's
97
+ ``addTo`` runs inline with Folium's map setup. Adding it to the map
98
+ *before* the other plugin controls means Leaflet stacks it on top of
99
+ its corner (e.g. above the measure control), with no DOM reordering.
100
+
101
+ The opening view is captured on ``DOMContentLoaded`` — after Folium's
102
+ synchronous ``fitBounds`` / ``setView`` has run — and stashed on the map
103
+ as ``_mapytaHome``, so a single button restores the correct view whether
104
+ it came from an explicit ``center`` or from auto-fitted data bounds.
105
+ """
106
+
107
+ _template = Template(
108
+ "{% macro script(this, kwargs) %}\n"
109
+ " var {{ this.get_name() }} = L.control({position: {{ this.position|tojson }}});\n"
110
+ " {{ this.get_name() }}.onAdd = function() {\n"
111
+ " var div = L.DomUtil.create('div', 'leaflet-bar');\n"
112
+ " var btn = L.DomUtil.create('a', '', div);\n"
113
+ " btn.href = '#';\n"
114
+ " btn.title = {{ this.title|tojson }};\n"
115
+ " btn.innerHTML = '\\u2302';\n"
116
+ " btn.style.cssText = 'font-size:18px;text-align:center;line-height:26px;cursor:pointer;';\n"
117
+ " btn.onclick = function(e) {\n"
118
+ " e.preventDefault();\n"
119
+ " e.stopPropagation();\n"
120
+ " var home = {{ this._parent.get_name() }}._mapytaHome;\n"
121
+ " if (home) { {{ this._parent.get_name() }}.setView(home.center, home.zoom); }\n"
122
+ " };\n"
123
+ " L.DomEvent.disableClickPropagation(div);\n"
124
+ " return div;\n"
125
+ " };\n"
126
+ " {{ this.get_name() }}.addTo({{ this._parent.get_name() }});\n"
127
+ " document.addEventListener('DOMContentLoaded', function() {\n"
128
+ " {{ this._parent.get_name() }}._mapytaHome = {\n"
129
+ " center: {{ this._parent.get_name() }}.getCenter(),\n"
130
+ " zoom: {{ this._parent.get_name() }}.getZoom()\n"
131
+ " };\n"
132
+ " });\n"
133
+ "{% endmacro %}"
134
+ )
135
+
136
+ def __init__(self, position: str = "topright", title: str = "Reset view") -> None:
137
+ super().__init__()
138
+ self._name = "HomeButtonControl"
139
+ self.position = position
140
+ self.title = title
141
+
74
142
 
75
143
  class Map:
76
144
  """Interactive map builder backed by Folium and OpenStreetMap tiles.
@@ -207,6 +275,7 @@ class Map:
207
275
  ).add_to(fmap)
208
276
 
209
277
  fmap.get_root().header.add_child(folium.Element('<meta name="referrer" content="origin">')) # ty: ignore[unresolved-attribute]
278
+ fmap.get_root().header.add_child(folium.Element(CONTROL_SIZE_CSS)) # ty: ignore[unresolved-attribute]
210
279
 
211
280
  # Title overlay
212
281
  if self._title:
@@ -220,6 +289,10 @@ class Map:
220
289
  fmap.get_root().html.add_child(folium.Element(title_html)) # ty: ignore[unresolved-attribute]
221
290
 
222
291
  # Optional plugins
292
+ # Added first so its control sits at the top of its corner — Leaflet stacks
293
+ # same-corner controls in add order, so this lands above the measure control.
294
+ if cfg.home_button:
295
+ _HomeButtonControl(position="topright", title="Reset view").add_to(fmap)
223
296
  if cfg.fullscreen:
224
297
  folium.plugins.Fullscreen().add_to(fmap)
225
298
  if cfg.minimap:
@@ -379,6 +452,9 @@ class Map:
379
452
  submit_label: str = "Submit",
380
453
  draw_style: dict[str, Any] | None = None,
381
454
  edit: bool = True,
455
+ delete_confirm_message: str = "Delete this shape?",
456
+ delete_confirm_yes: str = "Delete",
457
+ delete_confirm_no: str = "Cancel",
382
458
  ) -> Self:
383
459
  """Enable drawing controls on the map.
384
460
 
@@ -400,7 +476,18 @@ class Map:
400
476
  draw_style : dict[str, Any] | None
401
477
  ``shapeOptions`` override for drawn shapes.
402
478
  edit : bool
403
- Whether edit/delete controls are active.
479
+ Whether per-shape editing/deletion is active. When ``True``,
480
+ clicking a drawn shape makes its vertices editable in place (click
481
+ empty map space to stop editing) and shows a trashbin at its last
482
+ vertex; clicking the trashbin and confirming deletes that shape.
483
+ No global edit/delete toolbar buttons are rendered. When ``False``,
484
+ clicking a shape stays inert.
485
+ delete_confirm_message : str
486
+ Text shown in the in-map deletion confirmation popup.
487
+ delete_confirm_yes : str
488
+ Label of the confirm (delete) button in that popup.
489
+ delete_confirm_no : str
490
+ Label of the cancel button in that popup.
404
491
 
405
492
  Returns
406
493
  -------
@@ -426,6 +513,9 @@ class Map:
426
513
  submit_label=submit_label,
427
514
  draw_style=draw_style,
428
515
  edit=edit,
516
+ delete_confirm_message=delete_confirm_message,
517
+ delete_confirm_yes=delete_confirm_yes,
518
+ delete_confirm_no=delete_confirm_no,
429
519
  )
430
520
  self._draw_injected = False
431
521
  return self
@@ -444,7 +534,15 @@ class Map:
444
534
  elif cfg.draw_style:
445
535
  draw_options[tool] = {"shapeOptions": cfg.draw_style}
446
536
 
447
- edit_options: dict[str, Any] = {"remove": cfg.edit}
537
+ # Disable both edit-toolbar modes explicitly. Leaflet.draw's EditToolbar
538
+ # prototype defaults ``edit`` to a truthy object, so omitting the key would
539
+ # still render the pencil button — only an explicit ``false`` shadows it.
540
+ # With both modes off, ``L.Toolbar.addToolbar`` early-returns (no buttons),
541
+ # so no edit/delete toolbar appears. folium still wires
542
+ # ``options.edit.featureGroup = drawnItems`` and adds drawn shapes via
543
+ # ``draw:created``, so click-to-edit (and the per-shape trashbin) stays
544
+ # intact. Per-shape editing/deletion replaces the global toolbar buttons.
545
+ edit_options: dict[str, Any] = {"edit": False, "remove": False}
448
546
 
449
547
  # Folium's built-in Draw plugin loads leaflet.draw CSS/JS via JSCSSMixin
450
548
  # (placed in <head>), guaranteeing correct load order in both standalone
@@ -477,6 +575,7 @@ class Map:
477
575
  assert cfg is not None
478
576
 
479
577
  callback_js = self._build_draw_callback_js()
578
+ click_edit_js = self._build_click_to_edit_js() if cfg.edit else ""
480
579
 
481
580
  return (
482
581
  "<script>\n"
@@ -485,6 +584,7 @@ class Map:
485
584
  f" var drawnItems = window['{drawn_items_var}'];\n"
486
585
  " if (!map || !drawnItems) return;\n"
487
586
  "\n"
587
+ f"{click_edit_js}"
488
588
  " var submitControl = L.control({position: 'bottomright'});\n"
489
589
  " submitControl.onAdd = function() {\n"
490
590
  " var div = L.DomUtil.create('div', 'leaflet-bar');\n"
@@ -508,6 +608,187 @@ class Map:
508
608
  "</script>"
509
609
  )
510
610
 
611
+ def _build_click_to_edit_js(self) -> str:
612
+ """Build the click-to-edit + per-shape trashbin ``<script>`` fragment.
613
+
614
+ Leaflet.draw only exposes vertex editing through the toolbar pencil,
615
+ which toggles *every* shape at once and needs an explicit Save, and
616
+ deletion through a global trashcan button. mapyta hides both (see
617
+ ``_inject_draw_plugin``) in favour of per-shape, in-place interaction:
618
+
619
+ - **Edit:** drawn shapes are interactive (the cursor turns into a
620
+ pointer on hover), so users reasonably expect clicking one to edit
621
+ it. ``ddEnableClickEdit`` binds a per-layer ``click`` handler that
622
+ calls the layer's Leaflet.draw ``editing.enable()`` so a single shape
623
+ becomes editable in place (drag vertices, add midpoints); clicking
624
+ empty map space disables editing again. It is wired to every layer
625
+ already in ``drawnItems`` and, via ``layeradd``, to any added later —
626
+ whether drawn by the user or pre-seeded programmatically.
627
+ - **Delete:** while a shape is being edited, ``ddAddTrash`` drops a small
628
+ trashbin marker at its last vertex. Clicking it opens an in-map
629
+ Leaflet popup (``ddConfirmDelete``) with Delete/Cancel buttons;
630
+ confirming calls ``ddDeleteLine`` which removes that single shape. A
631
+ DOM popup is used rather than ``window.confirm()`` because the latter
632
+ is silently dropped inside sandboxed iframe embeds. As a shortcut,
633
+ pressing the keyboard **Delete** key removes the shape currently being
634
+ edited immediately, without the confirmation popup (ignored while a
635
+ form field is focused).
636
+
637
+ Only emitted when ``edit`` is enabled; if the caller turned edit
638
+ controls off, clicking a shape stays inert and no trashbin appears.
639
+
640
+ Leaflet.draw's vertex-edit ``addHooks`` reads ``layer.options.editing``
641
+ and ``layer.options.original`` unconditionally; its own edit toolbar
642
+ seeds both in ``_enableLayerEdit`` before calling ``editing.enable()``.
643
+ We enable editing directly (bypassing that toolbar), so we must seed
644
+ them ourselves — otherwise ``addHooks`` throws
645
+ ``Cannot read properties of undefined (reading 'className')`` on the SVG
646
+ renderer and no vertex handles appear. Seeded in the same order
647
+ Leaflet.draw uses (``original`` snapshots the live style first).
648
+
649
+ User-facing strings (the confirm message and button labels) are encoded
650
+ with :func:`json.dumps` so they become safe JS string literals.
651
+ """
652
+ cfg = self._draw_config
653
+ assert cfg is not None
654
+
655
+ # Inline SVG trash glyph (no font dependency), inside a white rounded
656
+ # badge for contrast against any basemap. json.dumps turns the whole
657
+ # markup into a safe JS string literal for L.divIcon's ``html`` option.
658
+ trash_html = (
659
+ '<div style="background:#fff;border:1px solid #ccc;border-radius:4px;'
660
+ "width:22px;height:22px;display:flex;align-items:center;justify-content:center;"
661
+ 'box-shadow:0 1px 4px rgba(0,0,0,0.3);color:#d11;cursor:pointer;">'
662
+ "<svg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' "
663
+ "fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' "
664
+ "stroke-linejoin='round'><polyline points='3 6 5 6 21 6'></polyline>"
665
+ "<path d='M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'></path>"
666
+ "<line x1='10' y1='11' x2='10' y2='17'></line>"
667
+ "<line x1='14' y1='11' x2='14' y2='17'></line></svg></div>"
668
+ )
669
+ trash_html_js = json.dumps(trash_html)
670
+ confirm_msg_js = json.dumps(cfg.delete_confirm_message)
671
+ confirm_yes_js = json.dumps(cfg.delete_confirm_yes)
672
+ confirm_no_js = json.dumps(cfg.delete_confirm_no)
673
+
674
+ return (
675
+ f" var ddTrashHtml = {trash_html_js};\n"
676
+ f" var ddDeleteMsg = {confirm_msg_js};\n"
677
+ f" var ddDeleteYes = {confirm_yes_js};\n"
678
+ f" var ddDeleteNo = {confirm_no_js};\n"
679
+ # Most recently focused (clicked-to-edit) layer; target of the
680
+ # keyboard Delete shortcut. Cleared when editing stops or it is
681
+ # deleted.
682
+ " var ddActiveLayer = null;\n"
683
+ # Last vertex of a shape, or null for layers we don't support
684
+ # (markers have no getLatLngs; polygons/rectangles nest one ring).
685
+ " function ddLastVertex(layer) {\n"
686
+ " if (!layer.getLatLngs) return null;\n"
687
+ " var lls = layer.getLatLngs();\n"
688
+ " if (!lls || !lls.length) return null;\n"
689
+ " var last = lls[lls.length - 1];\n"
690
+ " if (Array.isArray(last)) {\n"
691
+ " if (!last.length) return null;\n"
692
+ " last = last[last.length - 1];\n"
693
+ " }\n"
694
+ " if (!last || typeof last.lat !== 'number') return null;\n"
695
+ " return last;\n"
696
+ " }\n"
697
+ " function ddRemoveTrash(layer) {\n"
698
+ " if (layer._ddTrash) { map.removeLayer(layer._ddTrash); layer._ddTrash = null; }\n"
699
+ " }\n"
700
+ " function ddAddTrash(layer) {\n"
701
+ " if (layer._ddTrash) return;\n"
702
+ " var last = ddLastVertex(layer);\n"
703
+ " if (!last) return;\n"
704
+ " var trash = L.marker(last, {\n"
705
+ " icon: L.divIcon({className: 'dd-trash-icon', html: ddTrashHtml, iconSize: [22, 22], iconAnchor: [-6, 28]}),\n"
706
+ " interactive: true, keyboard: false, zIndexOffset: 1000\n"
707
+ " }).addTo(map);\n"
708
+ " layer._ddTrash = trash;\n"
709
+ " trash.on('click', function(e) {\n"
710
+ " L.DomEvent.stopPropagation(e);\n"
711
+ " ddConfirmDelete(layer, trash.getLatLng());\n"
712
+ " });\n"
713
+ # Keep the trashbin pinned to the last vertex while it moves. The
714
+ # layer fires 'edit' on each vertex drag-end (PolyVerticesEdit
715
+ # ._fireEdit); 'editdrag' is bound too in case the build re-fires it.
716
+ # Bind once per layer: ddAddTrash runs again on every re-edit and
717
+ # this handler outlives the trash marker (it null-checks
718
+ # layer._ddTrash), so re-binding would stack duplicate listeners.
719
+ " if (!layer._ddPinBound) {\n"
720
+ " layer._ddPinBound = true;\n"
721
+ " layer.on('edit editdrag', function() {\n"
722
+ " var nl = ddLastVertex(layer);\n"
723
+ " if (nl && layer._ddTrash) { layer._ddTrash.setLatLng(nl); }\n"
724
+ " });\n"
725
+ " }\n"
726
+ " }\n"
727
+ " function ddConfirmDelete(layer, latlng) {\n"
728
+ " var box = L.DomUtil.create('div', 'dd-delete-confirm');\n"
729
+ " var msg = L.DomUtil.create('div', '', box);\n"
730
+ " msg.innerHTML = ddDeleteMsg;\n"
731
+ " msg.style.cssText = 'margin-bottom:8px;font-size:13px;';\n"
732
+ " var del = L.DomUtil.create('a', '', box);\n"
733
+ " del.href = '#'; del.innerHTML = ddDeleteYes;\n"
734
+ " del.style.cssText = 'display:inline-block;padding:4px 10px;margin-right:6px;background:#d11;' +\n"
735
+ " 'color:#fff;text-decoration:none;font-weight:bold;font-size:12px;border-radius:3px;cursor:pointer;';\n"
736
+ " var cancel = L.DomUtil.create('a', '', box);\n"
737
+ " cancel.href = '#'; cancel.innerHTML = ddDeleteNo;\n"
738
+ " cancel.style.cssText = 'display:inline-block;padding:4px 10px;background:#eee;color:#333;' +\n"
739
+ " 'text-decoration:none;font-size:12px;border-radius:3px;cursor:pointer;';\n"
740
+ " L.DomEvent.disableClickPropagation(box);\n"
741
+ " del.onclick = function(e) { e.preventDefault(); ddDeleteLine(layer); map.closePopup(); };\n"
742
+ " cancel.onclick = function(e) { e.preventDefault(); map.closePopup(); };\n"
743
+ " L.popup({closeButton: false, className: 'dd-delete-confirm'}).setLatLng(latlng).setContent(box).openOn(map);\n"
744
+ " }\n"
745
+ " function ddDeleteLine(layer) {\n"
746
+ " if (layer.editing && layer.editing.enabled()) { layer.editing.disable(); }\n"
747
+ " ddRemoveTrash(layer);\n"
748
+ " drawnItems.removeLayer(layer);\n"
749
+ " if (ddActiveLayer === layer) { ddActiveLayer = null; }\n"
750
+ " }\n"
751
+ " function ddEnableClickEdit(layer) {\n"
752
+ " if (!layer || !layer.editing) return;\n"
753
+ " layer.on('click', function(e) {\n"
754
+ " L.DomEvent.stopPropagation(e);\n"
755
+ " if (!layer.editing.enabled()) {\n"
756
+ " if (layer.options) {\n"
757
+ " if (!layer.options.original) { layer.options.original = L.extend({}, layer.options); }\n"
758
+ " if (!layer.options.editing) { layer.options.editing = {}; }\n"
759
+ " }\n"
760
+ " layer.editing.enable();\n"
761
+ " ddAddTrash(layer);\n"
762
+ " }\n"
763
+ " ddActiveLayer = layer;\n"
764
+ " });\n"
765
+ " }\n"
766
+ " drawnItems.eachLayer(ddEnableClickEdit);\n"
767
+ " drawnItems.on('layeradd', function(e) { ddEnableClickEdit(e.layer); });\n"
768
+ " map.on('click', function() {\n"
769
+ " drawnItems.eachLayer(function(layer) {\n"
770
+ " if (layer.editing && layer.editing.enabled()) {\n"
771
+ " layer.editing.disable();\n"
772
+ " ddRemoveTrash(layer);\n"
773
+ " }\n"
774
+ " });\n"
775
+ " ddActiveLayer = null;\n"
776
+ " });\n"
777
+ # Keyboard shortcut: pressing Delete while a shape is being edited
778
+ # removes it immediately, bypassing the trashbin's confirmation
779
+ # popup. Ignored while typing in a form field. Other interactions
780
+ # (click-to-edit, trashbin + confirm) are unaffected.
781
+ " document.addEventListener('keydown', function(e) {\n"
782
+ " if (e.key !== 'Delete') return;\n"
783
+ " var t = e.target;\n"
784
+ " if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;\n"
785
+ " if (ddActiveLayer && ddActiveLayer.editing && ddActiveLayer.editing.enabled()) {\n"
786
+ " ddDeleteLine(ddActiveLayer);\n"
787
+ " }\n"
788
+ " });\n"
789
+ "\n"
790
+ )
791
+
511
792
  def _build_draw_callback_js(self) -> str:
512
793
  """Build the JavaScript callback for the submit button."""
513
794
  cfg = self._draw_config
@@ -1196,19 +1477,127 @@ class Map:
1196
1477
  -------
1197
1478
  branca.colormap.LinearColormap
1198
1479
  """
1480
+ return cm.LinearColormap(colors=self._resolve_colors(colors), vmin=vmin, vmax=vmax, caption=caption)
1481
+
1482
+ def _resolve_colors(self, colors: list[str] | str | None) -> list[str]:
1483
+ """Resolve a palette name, explicit color list, or ``None`` to a concrete low→high ramp.
1484
+
1485
+ Parameters
1486
+ ----------
1487
+ colors : list[str] | str | None
1488
+ Palette name (e.g. ``"blues"``), list of hex colors, or ``None`` for the
1489
+ default palette.
1490
+
1491
+ Returns
1492
+ -------
1493
+ list[str]
1494
+ The resolved low→high color ramp.
1495
+
1496
+ Raises
1497
+ ------
1498
+ ValueError
1499
+ If ``colors`` names an unknown palette or is an empty list.
1500
+ """
1199
1501
  if isinstance(colors, str):
1200
1502
  palette = PALETTES.get(colors)
1201
1503
  if palette is None:
1202
1504
  valid = ", ".join(f'"{k}"' for k in sorted(PALETTES))
1203
1505
  raise ValueError(f"Unknown palette {colors!r}. Available palettes: {valid}")
1204
- color_list = palette
1205
- elif colors is not None:
1506
+ return palette
1507
+ if colors is not None:
1206
1508
  if not colors:
1207
1509
  raise ValueError("colors list must not be empty")
1208
- color_list = colors
1209
- else:
1210
- color_list = PALETTES["ylrd"]
1211
- return cm.LinearColormap(colors=color_list, vmin=vmin, vmax=vmax, caption=caption)
1510
+ return colors
1511
+ return PALETTES["ylrd"]
1512
+
1513
+ def _register_colormap(self, colormap: cm.LinearColormap | cm.StepColormap) -> None:
1514
+ """Add ``colormap`` to the folium map and track it so legends merge correctly."""
1515
+ colormap.add_to(self._map)
1516
+ self._colormaps.append(colormap)
1517
+
1518
+ def add_colorbar(
1519
+ self,
1520
+ colors: list[str] | str | None,
1521
+ vmin: float,
1522
+ vmax: float,
1523
+ legend_name: str,
1524
+ ) -> cm.LinearColormap:
1525
+ """Add a standalone color-scale legend (colorbar) to the map.
1526
+
1527
+ Unlike :meth:`add_choropleth` and :meth:`from_geodataframe`, this adds a
1528
+ legend on its own — for maps whose features are coloured by hand (e.g.
1529
+ :meth:`add_circle` / :meth:`add_point` with per-feature styles). The
1530
+ returned colormap is callable: ``colormap(value)`` yields the hex colour
1531
+ for ``value``, so callers colour their own features consistently with
1532
+ the legend without rebuilding the scale.
1533
+
1534
+ The legend is a readable HTML ``<div>`` pinned to the bottom-right of the
1535
+ map (a horizontal gradient bar with the ``legend_name`` above and evenly
1536
+ spaced value ticks below), rather than branca's default SVG colorbar. Two
1537
+ consequences follow: ``legend_name`` may contain inline HTML such as
1538
+ ``<sub>``/``<sup>`` (rendered, not shown literally), and the legend sits
1539
+ clear of the top-centre :paramref:`title` instead of overlapping it.
1540
+
1541
+ Parameters
1542
+ ----------
1543
+ colors : list[str] | str | None
1544
+ Palette name (e.g. ``"blues"``), list of hex colors, or ``None`` for
1545
+ the default palette. Same handling as :meth:`add_choropleth`.
1546
+ vmin, vmax : float
1547
+ Color scale range.
1548
+ legend_name : str
1549
+ Legend label. May contain inline HTML (e.g. ``"R<sub>c;cal</sub>"``).
1550
+
1551
+ Returns
1552
+ -------
1553
+ branca.colormap.LinearColormap
1554
+ The colormap added to the map. Call it with a value to get a colour.
1555
+ """
1556
+ color_list = self._resolve_colors(colors)
1557
+ colormap = cm.LinearColormap(colors=color_list, vmin=vmin, vmax=vmax, caption=legend_name)
1558
+ # Track the colormap (for merge), but render our own HTML legend rather than
1559
+ # branca's SVG colorbar via ``_register_colormap`` — see the method docstring.
1560
+ self._colormaps.append(colormap)
1561
+ self._add_html_colorbar(colors=color_list, vmin=vmin, vmax=vmax, legend_name=legend_name)
1562
+ return colormap
1563
+
1564
+ @staticmethod
1565
+ def _format_legend_value(value: float) -> str:
1566
+ """Format a colorbar tick: a thousands-separated integer, else two decimals."""
1567
+ rounded = round(value, 2)
1568
+ if rounded.is_integer():
1569
+ return f"{int(rounded):,}"
1570
+ return f"{rounded:,.2f}"
1571
+
1572
+ def _add_html_colorbar(self, colors: list[str], vmin: float, vmax: float, legend_name: str) -> None:
1573
+ """Render the HTML colorbar legend (gradient bar + caption + ticks) bottom-right.
1574
+
1575
+ Parameters
1576
+ ----------
1577
+ colors : list[str]
1578
+ The resolved low→high color ramp. Always holds at least two colours
1579
+ (branca's ``LinearColormap`` rejects fewer in :meth:`add_colorbar`).
1580
+ vmin, vmax : float
1581
+ Color scale range, used for the five evenly spaced value ticks.
1582
+ legend_name : str
1583
+ Legend label; inline HTML is preserved (e.g. ``<sub>``).
1584
+ """
1585
+ last = len(colors) - 1
1586
+ stops = ", ".join(f"{color} {index / last * 100:.0f}%" for index, color in enumerate(colors))
1587
+ gradient = f"linear-gradient(to right, {stops})"
1588
+ tick_count = 5
1589
+ ticks = "".join(f"<span>{self._format_legend_value(vmin + (vmax - vmin) * step / (tick_count - 1))}</span>" for step in range(tick_count))
1590
+ legend_html = (
1591
+ '<div style="position:fixed;bottom:14px;right:14px;'
1592
+ "z-index:1000;background:rgba(255,255,255,0.92);padding:6px 12px;border-radius:6px;"
1593
+ "box-shadow:0 2px 6px rgba(0,0,0,0.3);font-family:Arial,sans-serif;font-size:12px;"
1594
+ 'color:#333;pointer-events:none;">'
1595
+ f'<div style="text-align:center;font-weight:bold;margin-bottom:4px;">{legend_name}</div>'
1596
+ f'<div style="width:260px;height:12px;border-radius:2px;background:{gradient};"></div>'
1597
+ f'<div style="display:flex;justify-content:space-between;margin-top:3px;">{ticks}</div>'
1598
+ "</div>"
1599
+ )
1600
+ self._map.get_root().html.add_child(folium.Element(legend_html)) # ty: ignore[unresolved-attribute]
1212
1601
 
1213
1602
  def add_choropleth( # noqa: C901, PLR0913, PLR0912, PLR0915
1214
1603
  self,
@@ -1372,8 +1761,7 @@ class Map:
1372
1761
  tooltip=tooltip,
1373
1762
  )
1374
1763
  layer.add_to(self._target())
1375
- colormap.add_to(self._map)
1376
- self._colormaps.append(colormap)
1764
+ self._register_colormap(colormap)
1377
1765
 
1378
1766
  try:
1379
1767
  layer_bounds = layer.get_bounds()
@@ -2023,8 +2411,7 @@ class Map:
2023
2411
  vmax=vmax,
2024
2412
  caption=legend_name or color_column,
2025
2413
  )
2026
- colormap.add_to(m._map)
2027
- m._colormaps.append(colormap)
2414
+ m._register_colormap(colormap)
2028
2415
 
2029
2416
  # Iterate rows
2030
2417
  for idx, row in gdf.iterrows():
@@ -2377,7 +2764,7 @@ class Map:
2377
2764
  self._ensure_rendered()
2378
2765
  return self._map._repr_html_()
2379
2766
 
2380
- def _get_standalone_html(self) -> str:
2767
+ def get_standalone_html(self) -> str:
2381
2768
  """Render map to a full standalone HTML document."""
2382
2769
  self._ensure_rendered()
2383
2770
  return self._map.get_root().render()
@@ -2409,7 +2796,7 @@ class Map:
2409
2796
  if path is None:
2410
2797
  return self._get_html()
2411
2798
  out = Path(path)
2412
- out.write_text(self._get_standalone_html(), encoding="utf-8")
2799
+ out.write_text(self.get_standalone_html(), encoding="utf-8")
2413
2800
  if open_in_browser:
2414
2801
  webbrowser.open(out.resolve().as_uri())
2415
2802
  return out
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mapyta"
3
- version = "0.8.0"
3
+ version = "0.10.0.dev1"
4
4
  description = "Mapyta, open source python package for GIS mapping and visualization."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"