diff --git a/README.md b/README.md index 735041c6..c2ff46a7 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,7 @@ python -m unittest tests.test_anymap -v - ✅ OpenLayers backend - ✅ DeckGL backend - ✅ KeplerGL backend +- ✅ Plotly Dash backend - 🔲 Cesium backend - 🔲 Potree backend diff --git a/anymap/__init__.py b/anymap/__init__.py index d1641727..3638d4e2 100644 --- a/anymap/__init__.py +++ b/anymap/__init__.py @@ -13,6 +13,7 @@ from .leaflet import LeafletMap from .openlayers import OpenLayersMap from .keplergl import KeplerGLMap +from .dash import DashMap from .compare import MapCompare from .utils import download_file @@ -30,5 +31,6 @@ "LeafletMap", "OpenLayersMap", "KeplerGLMap", + "DashMap", "MapCompare", ] diff --git a/anymap/anymap.py b/anymap/anymap.py index fd18d573..90e9e6e8 100644 --- a/anymap/anymap.py +++ b/anymap/anymap.py @@ -21,6 +21,7 @@ from .cesium import CesiumMap from .potree import PotreeMap from .deckgl import DeckGLMap +from .dash import DashMap from .compare import MapCompare # Make all classes available when importing from this module @@ -31,5 +32,6 @@ "CesiumMap", "PotreeMap", "DeckGLMap", + "DashMap", "MapCompare", ] diff --git a/anymap/dash.py b/anymap/dash.py new file mode 100644 index 00000000..ab409f0d --- /dev/null +++ b/anymap/dash.py @@ -0,0 +1,290 @@ +"""Plotly Dash implementation of the map widget. + +This module provides the DashMap class which implements an interactive map +widget with Plotly Dash integration and MapLibre GL JS rendering. +""" + +import pathlib +import traitlets +from typing import Dict, List, Any, Optional, Union, Sequence, Tuple, Callable +import json + +from .maplibre import MapLibreMap + +# Load widget js and css +try: + with open( + pathlib.Path(__file__).parent / "static" / "dash_widget.js", + "r", + encoding="utf-8", + ) as f: + _esm_dash = f.read() +except FileNotFoundError: + try: + with open( + pathlib.Path(__file__).parent / "static" / "maplibre_widget.js", + "r", + encoding="utf-8", + ) as f: + _esm_dash = f.read() + except FileNotFoundError: + _esm_dash = "console.error('Dash widget JS not found');" + +try: + with open( + pathlib.Path(__file__).parent / "static" / "dash_widget.css", + "r", + encoding="utf-8", + ) as f: + _css_dash = f.read() +except FileNotFoundError: + try: + with open( + pathlib.Path(__file__).parent / "static" / "maplibre_widget.css", + "r", + encoding="utf-8", + ) as f: + _css_dash = f.read() + except FileNotFoundError: + _css_dash = "/* Dash widget CSS not found */" + + +class DashMap(MapLibreMap): + """Plotly Dash map widget implementation. + + This class provides an interactive map widget with Plotly Dash integration. + It supports MapLibre GL JS rendering in Jupyter notebooks as well as + seamless integration into Plotly Dash web applications. + + Attributes: + center: Map center coordinates as [longitude, latitude] or [latitude, longitude]. + zoom: Map zoom level. + style: Map style configuration (URL string or style object). + width: Map container width as CSS string. + height: Map container height as CSS string. + bearing: Map rotation in degrees (0-360). + pitch: Map tilt in degrees (0-60). + + Example: + >>> from anymap import DashMap + >>> m = DashMap( + ... center=[-74.0060, 40.7128], # New York City + ... zoom=13, + ... height="500px", + ... bearing=45, # Map rotation + ... pitch=60 # 3D tilt + ... ) + >>> m + """ + + _esm = _esm_dash + _css = _css_dash + + def __init__( + self, + center: List[float] = [0.0, 20.0], + zoom: float = 1.0, + style: Union[str, Dict[str, Any]] = "dark-matter", + width: str = "100%", + height: str = "500px", + bearing: float = 0.0, + pitch: float = 0.0, + **kwargs: Any, + ) -> None: + """Initialize Plotly Dash map widget. + + Args: + center: Map center coordinates as [longitude, latitude] or [latitude, longitude]. Default is [0, 20]. + zoom: Initial zoom level (typically 0-20). Default is 1.0. + style: MapLibre style URL string or style object dictionary. Default is "dark-matter". + width: Widget width as CSS string (e.g., "100%", "800px"). Default is "100%". + height: Widget height as CSS string (e.g., "500px", "600px"). Default is "500px". + bearing: Map bearing (rotation) in degrees (0-360). Default is 0.0. + pitch: Map pitch (tilt) in degrees (0-60). Default is 0.0. + **kwargs: Additional keyword arguments passed to MapLibreMap. + """ + super().__init__( + center=center, + zoom=zoom, + style=style, + width=width, + height=height, + bearing=bearing, + pitch=pitch, + **kwargs, + ) + + def to_dash( + self, + app: Optional[Any] = None, + title: str = "AnyMap Dash App", + port: int = 8050, + host: str = "127.0.0.1", + debug: bool = True, + inline: bool = False, + **kwargs: Any, + ) -> Any: + """Create or configure a Plotly Dash application with the map. + + Args: + app: Optional existing dash.Dash instance. If None, a new Dash app is created. + title: Title for the Dash application. Default is "AnyMap Dash App". + port: Port to run the server on when running. Default is 8050. + host: Host address to run the server on. Default is "127.0.0.1". + debug: Whether to run Dash in debug mode. Default is True. + inline: Whether to display inline in Jupyter notebooks. Default is False. + **kwargs: Additional arguments passed to dash.Dash(). + + Returns: + The dash.Dash application instance. + """ + try: + import dash + from dash import html + except ImportError: + raise ImportError( + "The 'dash' package is required for this feature. " + "Please install it using 'pip install dash'." + ) + + if app is None: + app = dash.Dash(__name__, title=title, **kwargs) + app.layout = html.Div( + [ + html.H1( + title, + style={"textAlign": "center", "fontFamily": "sans-serif"}, + ), + self.to_dash_component(id="anymap-dash-component"), + ], + style={"padding": "10px", "height": "100vh", "boxSizing": "border-box"}, + ) + + if inline: + if hasattr(app, "run"): + app.run(jupyter_mode="inline", port=port, host=host, debug=debug) + elif hasattr(app, "run_server"): + app.run_server(port=port, host=host, debug=debug) + + return app + + def to_dash_component( + self, + id: str = "dash-map", + width: Optional[str] = None, + height: Optional[str] = None, + **kwargs: Any, + ) -> Any: + """Export the map as a Plotly Dash component (html.Iframe). + + Args: + id: HTML element ID for the component. Default is "dash-map". + width: Width of the map component (CSS string). Defaults to widget width. + height: Height of the map component (CSS string). Defaults to widget height. + **kwargs: Additional HTML iframe attributes or styling. + + Returns: + dash.html.Iframe component. + """ + try: + from dash import html + except ImportError: + raise ImportError( + "The 'dash' package is required for this feature. " + "Please install it using 'pip install dash'." + ) + + comp_width = width or self.width or "100%" + comp_height = height or self.height or "500px" + + style = { + "width": comp_width, + "height": comp_height, + "border": "none", + } + if "style" in kwargs: + style.update(kwargs.pop("style")) + + html_content = self.to_html(width=comp_width, height=comp_height) + return html.Iframe( + id=id, + srcDoc=html_content, + style=style, + **kwargs, + ) + + to_component = to_dash_component + + def to_plotly(self) -> Any: + """Convert the current map into a Plotly Figure object. + + Returns: + plotly.graph_objects.Figure instance. + """ + try: + import plotly.graph_objects as go + except ImportError: + raise ImportError( + "The 'plotly' package is required for this feature. " + "Please install it using 'pip install plotly'." + ) + + fig = go.Figure() + + # Parse style + mapbox_style = "open-street-map" + if isinstance(self.style, str): + if "carto" in self.style.lower(): + mapbox_style = ( + "carto-positron" + if "light" in self.style.lower() or "positron" in self.style.lower() + else "carto-darkmatter" + ) + elif "osm" in self.style.lower() or "openstreetmap" in self.style.lower(): + mapbox_style = "open-street-map" + elif "satellite" in self.style.lower(): + mapbox_style = "white-bg" + + # Height integer if possible + fig_height = None + if isinstance(self.height, str) and self.height.endswith("px"): + try: + fig_height = int(self.height[:-2]) + except ValueError: + pass + + fig.update_layout( + mapbox=dict( + style=mapbox_style, + center=dict(lat=self.center[1], lon=self.center[0]), + zoom=self.zoom, + bearing=self.bearing, + pitch=self.pitch, + ), + margin=dict(r=0, t=0, b=0, l=0), + height=fig_height or 500, + ) + return fig + + to_figure = to_plotly + + def run_dash( + self, + port: int = 8050, + host: str = "127.0.0.1", + debug: bool = True, + **kwargs: Any, + ) -> None: + """Run the map as a standalone Plotly Dash web application. + + Args: + port: Port to run the server on. Default is 8050. + host: Host address. Default is "127.0.0.1". + debug: Whether to run in debug mode. Default is True. + **kwargs: Additional keyword arguments passed to app.run() or app.run_server(). + """ + app = self.to_dash() + if hasattr(app, "run"): + app.run(port=port, host=host, debug=debug, **kwargs) + elif hasattr(app, "run_server"): + app.run_server(port=port, host=host, debug=debug, **kwargs) diff --git a/docs/dash.md b/docs/dash.md new file mode 100644 index 00000000..8355a6bf --- /dev/null +++ b/docs/dash.md @@ -0,0 +1,3 @@ +# dash module + +::: anymap.dash diff --git a/docs/examples/dash/dash.ipynb b/docs/examples/dash/dash.ipynb new file mode 100644 index 00000000..05958f81 --- /dev/null +++ b/docs/examples/dash/dash.ipynb @@ -0,0 +1,77 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "0", + "metadata": {}, + "outputs": [], + "source": [ + "from anymap import DashMap" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1", + "metadata": {}, + "outputs": [], + "source": [ + "m = DashMap(\n", + " center=[-120.44092662894388, 39.24312954407114],\n", + " zoom=8,\n", + " height=\"500px\",\n", + " bearing=45, # Map rotation\n", + " pitch=60, # 3D tilt\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2", + "metadata": {}, + "outputs": [], + "source": [ + "# Add a satellite basemap for better terrain visualization\n", + "m.add_basemap(\"Esri.WorldImagery\")\n", + "\n", + "# Enable terrain with default settings\n", + "m.set_terrain(exaggeration=5)\n", + "# Set bearing and pitch for 3D effect\n", + "m.set_bearing(0)\n", + "m.set_pitch(75)\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/mkdocs.yml b/mkdocs.yml index 116caeab..5f650ba4 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -112,6 +112,7 @@ nav: - base module: base.md - cesium module: cesium.md - compare module: compare.md + - dash module: dash.md - deckgl module: deckgl.md - draw_styles module: draw_styles.md - keplergl module: keplergl.md diff --git a/pyproject.toml b/pyproject.toml index c6283b81..17030554 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,13 +28,18 @@ classifiers = [ [project.optional-dependencies] all = [ - "anymap[extra, raster]", + "anymap[extra, raster, dash]", ] extra = [ "pandas", ] +dash = [ + "dash", + "plotly", +] + raster = ["localtileserver>=0.10.6", "jupyter-server-proxy", "rio-cogeo", "rioxarray", "flask", "flask-cors"] [tool] diff --git a/tests/test_dash.py b/tests/test_dash.py new file mode 100644 index 00000000..0e2bcccd --- /dev/null +++ b/tests/test_dash.py @@ -0,0 +1,189 @@ +"""Tests for Plotly Dash map implementation.""" + +import unittest +from unittest.mock import Mock, patch, MagicMock +import sys + +from anymap import DashMap +import anymap + + +class TestDashMap(unittest.TestCase): + """Test cases for the DashMap class.""" + + def test_import(self): + """Test importing DashMap from anymap and anymap.dash.""" + self.assertTrue(hasattr(anymap, "DashMap")) + from anymap.dash import DashMap as DirectDashMap + + self.assertIs(DashMap, DirectDashMap) + + def test_issue_example(self): + """Test the exact snippet requested in the issue.""" + m = DashMap( + center=[-74.0060, 40.7128], # New York City + zoom=13, + height="500px", + bearing=45, # Map rotation + pitch=60, # 3D tilt + ) + + self.assertEqual(m.center, [-74.0060, 40.7128]) + self.assertEqual(m.zoom, 13) + self.assertEqual(m.height, "500px") + self.assertEqual(m.bearing, 45) + self.assertEqual(m.pitch, 60) + + def test_default_initialization(self): + """Test default DashMap initialization.""" + m = DashMap() + self.assertEqual(m.center, [0.0, 20.0]) + self.assertEqual(m.zoom, 1.0) + self.assertEqual(m.width, "100%") + self.assertEqual(m.height, "500px") + self.assertEqual(m.bearing, 0.0) + self.assertEqual(m.pitch, 0.0) + self.assertIn("dark-matter", m.style) + + def test_custom_initialization(self): + """Test custom initialization parameters.""" + m = DashMap( + center=[-122.4194, 37.7749], + zoom=10, + style="osm", + width="800px", + height="400px", + bearing=30, + pitch=45, + ) + self.assertEqual(m.center, [-122.4194, 37.7749]) + self.assertEqual(m.zoom, 10) + self.assertIn("openfreemap", m.style) + self.assertEqual(m.width, "800px") + self.assertEqual(m.height, "400px") + self.assertEqual(m.bearing, 30) + self.assertEqual(m.pitch, 45) + + def test_maplibre_methods(self): + """Test that inherited MapLibre methods work properly on DashMap.""" + m = DashMap(center=[-74.0060, 40.7128], zoom=12) + + # set_center and set_zoom + m.set_center(-0.1278, 51.5074) + self.assertEqual(m.center, [-0.1278, 51.5074]) + + m.set_zoom(15) + self.assertEqual(m.zoom, 15) + + # fly_to + m.fly_to(2.3522, 48.8566, zoom=14) + self.assertTrue(len(m._js_calls) > 0) + + # add_marker + m.add_marker(-74.0060, 40.7128, popup="NYC") + self.assertTrue(any(call["method"] == "addMarker" for call in m._js_calls)) + + def test_to_html(self): + """Test HTML export for DashMap.""" + m = DashMap(center=[-74.0060, 40.7128], zoom=13, height="500px") + html_str = m.to_html(title="DashMap Test") + self.assertIsInstance(html_str, str) + self.assertIn("", html_str) + self.assertIn("DashMap Test", html_str) + + def test_to_dash_component_without_dash(self): + """Test error when dash is not installed.""" + m = DashMap() + with patch.dict(sys.modules, {"dash": None, "dash.html": None}): + with self.assertRaises(ImportError): + m.to_dash_component() + + def test_to_dash_component_with_dash(self): + """Test exporting DashMap as a Dash component.""" + m = DashMap(center=[-74.0060, 40.7128], zoom=13, height="500px") + + mock_dash = MagicMock() + mock_html = MagicMock() + mock_dash.html = mock_html + mock_iframe = MagicMock() + mock_html.Iframe = mock_iframe + + with patch.dict(sys.modules, {"dash": mock_dash, "dash.html": mock_html}): + comp = m.to_dash_component(id="test-map", width="600px", height="400px") + mock_iframe.assert_called_once() + args, kwargs = mock_iframe.call_args + self.assertEqual(kwargs["id"], "test-map") + self.assertEqual(kwargs["style"]["width"], "600px") + self.assertEqual(kwargs["style"]["height"], "400px") + self.assertIn("srcDoc", kwargs) + + # Test alias to_component + comp2 = m.to_component(id="test-map-2") + self.assertEqual(mock_iframe.call_count, 2) + + def test_to_dash_without_dash(self): + """Test error when dash is not installed for to_dash.""" + m = DashMap() + with patch.dict(sys.modules, {"dash": None, "dash.html": None}): + with self.assertRaises(ImportError): + m.to_dash() + + def test_to_dash_with_dash(self): + """Test to_dash app creation.""" + m = DashMap(center=[-74.0060, 40.7128], zoom=13, height="500px") + + mock_dash = MagicMock() + mock_dash_app = MagicMock() + mock_dash.Dash.return_value = mock_dash_app + mock_html = MagicMock() + mock_dash.html = mock_html + + with patch.dict(sys.modules, {"dash": mock_dash, "dash.html": mock_html}): + app = m.to_dash(title="Custom Title") + mock_dash.Dash.assert_called_once() + self.assertEqual(app, mock_dash_app) + + def test_to_plotly_without_plotly(self): + """Test error when plotly is not installed for to_plotly.""" + m = DashMap() + with patch.dict(sys.modules, {"plotly": None, "plotly.graph_objects": None}): + with self.assertRaises(ImportError): + m.to_plotly() + + def test_to_plotly_with_plotly(self): + """Test to_plotly conversion.""" + m = DashMap( + center=[-74.0060, 40.7128], zoom=13, height="500px", bearing=45, pitch=60 + ) + + mock_plotly = MagicMock() + mock_go = MagicMock() + mock_plotly.graph_objects = mock_go + mock_fig = MagicMock() + mock_go.Figure.return_value = mock_fig + + with patch.dict( + sys.modules, {"plotly": mock_plotly, "plotly.graph_objects": mock_go} + ): + fig = m.to_plotly() + mock_go.Figure.assert_called_once() + mock_fig.update_layout.assert_called_once() + self.assertEqual(fig, mock_fig) + + # Test alias to_figure + fig2 = m.to_figure() + self.assertEqual(fig2, mock_fig) + + def test_run_dash(self): + """Test run_dash method.""" + m = DashMap() + mock_app = MagicMock() + with patch.object(m, "to_dash", return_value=mock_app): + m.run_dash(port=8050, host="127.0.0.1", debug=False) + mock_app.run.assert_called_once_with( + port=8050, host="127.0.0.1", debug=False + ) + + +if __name__ == "__main__": + unittest.main()