Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

fix(kepler-jupyter): load config issue + empty geometry + json encoder (#3389)

Xun Li9c7af408f446
diff --git a/bindings/python/keplergl/_html_export.py b/bindings/python/keplergl/_html_export.py
index 2c0cae9a0..88e9a8a03 100644
--- a/bindings/python/keplergl/_html_export.py
+++ b/bindings/python/keplergl/_html_export.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import json
+import html
from typing import Optional
import pandas as pd
@@ -33,12 +34,21 @@ def _dataset_to_csv(data) -> Optional[str]:
return None
-def _dataset_to_geojson(data) -> Optional[dict]:
- """Try to convert dataset to GeoJSON dict."""
+def _dataset_to_geojson(data, json_encoder=str) -> Optional[dict]:
+ """Try to convert dataset to GeoJSON dict.
+
+ Args:
+ data: Dataset value (GeoDataFrame, dict, or string).
+ json_encoder: Fallback function passed as ``default`` to
+ ``GeoDataFrame.to_json()`` so that non-serializable types
+ (e.g. ``datetime``) are converted instead of raising.
+ Defaults to ``str``. Pass ``None`` to disable (will raise
+ on non-serializable types).
+ """
if isinstance(data, gpd.GeoDataFrame):
if data.crs and data.crs.to_epsg() != 4326:
data = data.to_crs(4326)
- return json.loads(data.to_json())
+ return json.loads(data.to_json(default=json_encoder))
elif isinstance(data, dict):
geojson_types = {
"FeatureCollection", "Feature", "Point", "MultiPoint",
@@ -59,15 +69,57 @@ def _dataset_to_geojson(data) -> Optional[dict]:
return None
-def _serialize_datasets_for_html(data: dict) -> str:
+def _geojson_dataset_names(data: dict, json_encoder=str) -> set:
+ """Return the set of dataset names that will be serialized as GeoJSON."""
+ names: set = set()
+ for name, dataset in data.items():
+ if _dataset_to_geojson(dataset, json_encoder=json_encoder) is not None:
+ names.add(name)
+ return names
+
+
+def _fixup_geojson_columns(config: Optional[dict], geojson_names: set) -> Optional[dict]:
+ """Rewrite layer column references for GeoJSON datasets.
+
+ ``processGeojson`` stores the geometry as ``_geojson`` regardless of the
+ original column name. Configs produced by the Jupyter widget use the
+ source GeoDataFrame column name (commonly ``geometry``), so the layer
+ merger cannot match them. This helper patches those references so the
+ exported HTML applies the full config.
+ """
+ if not config or not geojson_names:
+ return config
+
+ import copy
+ config = copy.deepcopy(config)
+ layers = (config
+ .get("config", {})
+ .get("visState", {})
+ .get("layers", []))
+ for layer in layers:
+ layer_cfg = layer.get("config", {})
+ data_id = layer_cfg.get("dataId")
+ if data_id not in geojson_names:
+ continue
+ columns = layer_cfg.get("columns", {})
+ if "geojson" in columns and columns["geojson"] != "_geojson":
+ columns["geojson"] = "_geojson"
+ return config
+
+
+def _serialize_datasets_for_html(data: dict, json_encoder=str) -> str:
"""Serialize datasets dict into JS code that calls addDataToMap.
Generates a JS snippet that processes each dataset using kepler.gl's
processCsvData or processGeojson, then dispatches addDataToMap.
+
+ Args:
+ data: Dict mapping dataset names to data objects.
+ json_encoder: Fallback encoder passed to ``_dataset_to_geojson``.
"""
snippets = []
for name, dataset in data.items():
- geojson = _dataset_to_geojson(dataset)
+ geojson = _dataset_to_geojson(dataset, json_encoder=json_encoder)
if geojson is not None:
snippets.append(
f" datasets.push({{info: {{id: {json.dumps(name, ensure_ascii=False)}, label: {json.dumps(name, ensure_ascii=False)}}}, "
@@ -85,28 +137,53 @@ def _serialize_datasets_for_html(data: dict) -> str:
def export_map_html(
data: dict,
- config: dict,
+ config: Optional[dict],
read_only: bool = False,
center_map: bool = False,
mapbox_token: str = "",
kepler_gl_version: str = DEFAULT_KEPLER_GL_CDN_VERSION,
+ json_encoder=str,
+ app_name: str = "kepler.gl",
+ theme: str = "",
) -> str:
"""Generate a standalone HTML string that renders a kepler.gl map.
Loads all dependencies from CDN (unpkg). No local JS build required.
+
+ Args:
+ data: Dict of dataset name to data.
+ config: Map config dict.
+ read_only: If True, hide side panel to disable map customization.
+ center_map: If True, fit map bounds to the data.
+ mapbox_token: Mapbox API access token.
+ kepler_gl_version: kepler.gl UMD bundle version tag for unpkg.
+ json_encoder: Fallback function passed as ``default`` when
+ JSON-serializing GeoDataFrame data. Defaults to ``str`` so
+ that ``datetime`` and other non-native JSON types are
+ converted automatically. Pass ``None`` to disable.
+ app_name: Application name displayed in the side panel header
+ and used as the HTML ``<title>``. Defaults to ``"kepler.gl"``.
+ theme: UI theme for the kepler.gl component. Accepted values
+ are ``"light"``, ``"dark"``, ``"base"``, or an empty string
+ (default) which uses the built-in dark theme.
"""
- dataset_js = _serialize_datasets_for_html(data)
- config_json = json.dumps(config, ensure_ascii=False) if config else "{}"
+ dataset_js = _serialize_datasets_for_html(data, json_encoder=json_encoder)
+ geojson_names = _geojson_dataset_names(data, json_encoder=json_encoder)
+ fixed_config = _fixup_geojson_columns(config, geojson_names)
+ config_json = json.dumps(fixed_config, ensure_ascii=False) if fixed_config else "{}"
mapbox_token_json = json.dumps(mapbox_token)
read_only_js = "true" if read_only else "false"
center_map_js = "true" if center_map else "false"
+ app_name_json = json.dumps(app_name)
+ theme_js = json.dumps(theme) if theme else "undefined"
+ title_html = html.escape(app_name) if app_name else "kepler.gl"
return f"""\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
- <title>Kepler.gl embedded map</title>
+ <title>{title_html} embedded map</title>
<!--Uber Font-->
<link rel="stylesheet" href="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/uber-fonts/4.0.0/superfine.css">
@@ -185,12 +262,13 @@ def export_map_html(
return react.createElement(
'div',
{{style: {{position: 'absolute', left: 0, width: '100vw', height: '100vh'}}}},
- react.createElement(keplerGl.KeplerGl, {{
+ react.createElement(keplerGl.KeplerGl, Object.assign({{
mapboxApiAccessToken: mapboxToken,
id: "map",
width: windowDimension.width,
- height: windowDimension.height
- }})
+ height: windowDimension.height,
+ appName: {app_name_json}
+ }}, {theme_js} !== undefined ? {{theme: {theme_js}}} : {{}}))
);
}};
}}(React, KeplerGl, MAPBOX_TOKEN));
diff --git a/bindings/python/keplergl/_version.py b/bindings/python/keplergl/_version.py
index 6b3cf1d5a..0c370da8e 100644
--- a/bindings/python/keplergl/_version.py
+++ b/bindings/python/keplergl/_version.py
@@ -3,4 +3,4 @@
"""Version information."""
-__version__ = "0.4.0rc2"
+__version__ = "0.4.0rc4"
diff --git a/bindings/python/keplergl/serializers.py b/bindings/python/keplergl/serializers.py
index a131f93ce..e77a45b7a 100644
--- a/bindings/python/keplergl/serializers.py
+++ b/bindings/python/keplergl/serializers.py
@@ -120,7 +120,12 @@ def serialize_geodataframe(gdf: gpd.GeoDataFrame, name: str) -> dict:
# Convert geometry column to geoarrow format
geom_col = gdf.geometry.name
- geom_array = ga.as_geoarrow(gdf.geometry)
+ geom_series = gdf.geometry
+ if geom_series.notna().any():
+ geom_array = ga.as_geoarrow(geom_series)
+ else:
+ # GeoArrow cannot infer a concrete geometry type from an empty/all-null series.
+ geom_array = ga.as_geoarrow(geom_series, type=ga.wkb())
# Build table with non-geometry columns as regular Arrow arrays
non_geom_cols = [c for c in gdf.columns if c != geom_col]
diff --git a/bindings/python/keplergl/widget.py b/bindings/python/keplergl/widget.py
index 3e72d9ab8..f391163ba 100644
--- a/bindings/python/keplergl/widget.py
+++ b/bindings/python/keplergl/widget.py
@@ -23,8 +23,10 @@ class KeplerGl(anywidget.AnyWidget):
config = traitlets.Dict({}).tag(sync=True)
height = traitlets.Int(400).tag(sync=True)
mapbox_token = traitlets.Unicode("").tag(sync=True)
+ theme = traitlets.Unicode("").tag(sync=True)
+ app_name = traitlets.Unicode("kepler.gl").tag(sync=True)
- def __init__(self, data=None, config=None, height=400, mapbox_token="", use_arrow=False, show_docs=False, **kwargs):
+ def __init__(self, data=None, config=None, height=400, mapbox_token="", use_arrow=False, show_docs=False, theme="", app_name="kepler.gl", **kwargs):
"""
Initialize KeplerGl widget.
@@ -35,9 +37,16 @@ class KeplerGl(anywidget.AnyWidget):
mapbox_token: Mapbox API access token for Mapbox basemap styles
use_arrow: If True, serialize DataFrames as Arrow IPC (more compact, preserves types)
show_docs: Deprecated, kept for compatibility
+ theme: UI theme for exported maps. Accepted values are
+ "light", "dark", "base", or "" (default dark theme).
+ app_name: Application name shown in the side panel header
+ and used as HTML ``<title>`` when exporting. Defaults to
+ ``"kepler.gl"``.
"""
super().__init__(**kwargs)
self._use_arrow = use_arrow
+ self.theme = theme
+ self.app_name = app_name
self.height = height
self.mapbox_token = mapbox_token
@@ -77,6 +86,9 @@ class KeplerGl(anywidget.AnyWidget):
read_only=False,
center_map=True,
mapbox_token="",
+ json_encoder=str,
+ app_name=None,
+ theme=None,
):
"""Export the map to a standalone HTML file.
@@ -91,10 +103,22 @@ class KeplerGl(anywidget.AnyWidget):
center_map: If True, fit map bounds to the data (default: True).
mapbox_token: Mapbox access token. Required for Mapbox basemap styles
(e.g. "Dark", "Muted Light"). Leave empty for free MapLibre styles.
+ json_encoder: Fallback function passed as ``default`` when
+ JSON-serializing GeoDataFrame data. Defaults to ``str`` so
+ that ``datetime`` and similar types are converted automatically.
+ Pass ``None`` to disable (will raise on non-serializable types).
+ app_name: Application name shown in the side panel header and used
+ as HTML ``<title>``. If None, uses the value set at widget
+ creation (default ``"kepler.gl"``).
+ theme: UI theme for the kepler.gl component (``"light"``,
+ ``"dark"``, ``"base"``, or ``""``). If None, uses the value
+ set at widget creation.
"""
data_to_save = data if data is not None else self.data
config_to_save = config if config is not None else self.config
token = mapbox_token if mapbox_token else self.mapbox_token
+ resolved_theme = theme if theme is not None else self.theme
+ resolved_app_name = app_name if app_name is not None else self.app_name
html = export_map_html(
data=data_to_save,
@@ -103,6 +127,9 @@ class KeplerGl(anywidget.AnyWidget):
center_map=center_map,
mapbox_token=token,
kepler_gl_version=DEFAULT_KEPLER_GL_CDN_VERSION,
+ json_encoder=json_encoder,
+ app_name=resolved_app_name,
+ theme=resolved_theme,
)
with open(file_name, "w", encoding="utf-8") as f:
diff --git a/bindings/python/notebooks/DataFrame.ipynb b/bindings/python/notebooks/DataFrame.ipynb
index 0b1c9c437..240ab930c 100644
--- a/bindings/python/notebooks/DataFrame.ipynb
+++ b/bindings/python/notebooks/DataFrame.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
@@ -11,7 +11,7 @@
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
@@ -26,21 +26,21 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
- "model_id": "791c9920051c48ecb9bb7422aff286bd",
+ "model_id": "e911f58eb69e429f94027e300d7cc73c",
"version_major": 2,
"version_minor": 1
},
"text/plain": [
- "<keplergl.widget.KeplerGl object at 0x125b9b3e0>"
+ "<keplergl.widget.KeplerGl object at 0x1126b0920>"
]
},
- "execution_count": 7,
+ "execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
@@ -53,7 +53,7 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": 4,
"metadata": {},
"outputs": [
{
diff --git a/bindings/python/notebooks/Empty GeoDataFrame.ipynb b/bindings/python/notebooks/Empty GeoDataFrame.ipynb
new file mode 100644
index 000000000..cfaa42864
--- /dev/null
+++ b/bindings/python/notebooks/Empty GeoDataFrame.ipynb
@@ -0,0 +1,242 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Empty & Null-Geometry GeoDataFrames\n",
+ "\n",
+ "Demonstrates that `KeplerGl` can accept GeoDataFrames that are empty or\n",
+ "contain only null geometries. This is useful when an analysis pipeline\n",
+ "produces no spatial results — the layer still appears on the map,\n",
+ "signalling that the analysis ran but found nothing."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import pandas as pd\n",
+ "import geopandas"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Empty GeoDataFrame (zero rows)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div>\n",
+ "<style scoped>\n",
+ " .dataframe tbody tr th:only-of-type {\n",
+ " vertical-align: middle;\n",
+ " }\n",
+ "\n",
+ " .dataframe tbody tr th {\n",
+ " vertical-align: top;\n",
+ " }\n",
+ "\n",
+ " .dataframe thead th {\n",
+ " text-align: right;\n",
+ " }\n",
+ "</style>\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>name</th>\n",
+ " <th>geometry</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ "Empty GeoDataFrame\n",
+ "Columns: [name, geometry]\n",
+ "Index: []"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "empty_gdf = geopandas.GeoDataFrame(\n",
+ " {\"name\": pd.Series([], dtype=\"str\")},\n",
+ " geometry=geopandas.GeoSeries([], crs=\"EPSG:4326\"),\n",
+ ")\n",
+ "display(empty_gdf)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## All-null geometries (rows exist, but every geometry is None)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div>\n",
+ "<style scoped>\n",
+ " .dataframe tbody tr th:only-of-type {\n",
+ " vertical-align: middle;\n",
+ " }\n",
+ "\n",
+ " .dataframe tbody tr th {\n",
+ " vertical-align: top;\n",
+ " }\n",
+ "\n",
+ " .dataframe thead th {\n",
+ " text-align: right;\n",
+ " }\n",
+ "</style>\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>label</th>\n",
+ " <th>geometry</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>0</th>\n",
+ " <td>a</td>\n",
+ " <td>None</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>1</th>\n",
+ " <td>b</td>\n",
+ " <td>None</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td>c</td>\n",
+ " <td>None</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ " label geometry\n",
+ "0 a None\n",
+ "1 b None\n",
+ "2 c None"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "null_geom_gdf = geopandas.GeoDataFrame(\n",
+ " {\"label\": [\"a\", \"b\", \"c\"]},\n",
+ " geometry=[None, None, None],\n",
+ ")\n",
+ "display(null_geom_gdf)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Load into kepler.gl"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.jupyter.widget-view+json": {
+ "model_id": "5acbf2fc0ae74e8191e8f0f0e267b6d5",
+ "version_major": 2,
+ "version_minor": 1
+ },
+ "text/plain": [
+ "<keplergl.widget.KeplerGl object at 0x126b7cf50>"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "import keplergl\n",
+ "w = keplergl.KeplerGl(height=500)\n",
+ "w"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "w.add_data(data=empty_gdf, name=\"empty\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "w.add_data(data=null_geom_gdf, name=\"null_geom\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/bindings/python/notebooks/GeoDataFrame with Datetime.ipynb b/bindings/python/notebooks/GeoDataFrame with Datetime.ipynb
new file mode 100644
index 000000000..7ad1c52ae
--- /dev/null
+++ b/bindings/python/notebooks/GeoDataFrame with Datetime.ipynb
@@ -0,0 +1,291 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# GeoDataFrame with Datetime Columns\n",
+ "\n",
+ "Demonstrates that `KeplerGl` handles GeoDataFrames containing\n",
+ "`datetime` (and other non-JSON-native) columns when adding data\n",
+ "and exporting to HTML.\n",
+ "\n",
+ "By default, `save_to_html` uses `default=str` when serializing\n",
+ "GeoDataFrame data to GeoJSON, so datetime values are automatically\n",
+ "converted to strings. You can override this with the `json_encoder`\n",
+ "parameter."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import pandas as pd\n",
+ "import geopandas"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Create a GeoDataFrame with datetime columns"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div>\n",
+ "<style scoped>\n",
+ " .dataframe tbody tr th:only-of-type {\n",
+ " vertical-align: middle;\n",
+ " }\n",
+ "\n",
+ " .dataframe tbody tr th {\n",
+ " vertical-align: top;\n",
+ " }\n",
+ "\n",
+ " .dataframe thead th {\n",
+ " text-align: right;\n",
+ " }\n",
+ "</style>\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>City</th>\n",
+ " <th>Country</th>\n",
+ " <th>Latitude</th>\n",
+ " <th>Longitude</th>\n",
+ " <th>Timestamp</th>\n",
+ " <th>geometry</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>0</th>\n",
+ " <td>Buenos Aires</td>\n",
+ " <td>Argentina</td>\n",
+ " <td>-34.58</td>\n",
+ " <td>-58.66</td>\n",
+ " <td>2024-01-15 08:00:00</td>\n",
+ " <td>POINT (-58.66 -34.58)</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>1</th>\n",
+ " <td>Brasilia</td>\n",
+ " <td>Brazil</td>\n",
+ " <td>-15.78</td>\n",
+ " <td>-47.91</td>\n",
+ " <td>2024-02-20 09:30:00</td>\n",
+ " <td>POINT (-47.91 -15.78)</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td>Santiago</td>\n",
+ " <td>Chile</td>\n",
+ " <td>-33.45</td>\n",
+ " <td>-70.66</td>\n",
+ " <td>2024-03-10 11:00:00</td>\n",
+ " <td>POINT (-70.66 -33.45)</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>3</th>\n",
+ " <td>Bogota</td>\n",
+ " <td>Colombia</td>\n",
+ " <td>4.60</td>\n",
+ " <td>-74.08</td>\n",
+ " <td>2024-04-05 14:15:00</td>\n",
+ " <td>POINT (-74.08 4.6)</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>4</th>\n",
+ " <td>Caracas</td>\n",
+ " <td>Venezuela</td>\n",
+ " <td>10.48</td>\n",
+ " <td>-66.86</td>\n",
+ " <td>2024-05-22 16:45:00</td>\n",
+ " <td>POINT (-66.86 10.48)</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ " City Country Latitude Longitude Timestamp \\\n",
+ "0 Buenos Aires Argentina -34.58 -58.66 2024-01-15 08:00:00 \n",
+ "1 Brasilia Brazil -15.78 -47.91 2024-02-20 09:30:00 \n",
+ "2 Santiago Chile -33.45 -70.66 2024-03-10 11:00:00 \n",
+ "3 Bogota Colombia 4.60 -74.08 2024-04-05 14:15:00 \n",
+ "4 Caracas Venezuela 10.48 -66.86 2024-05-22 16:45:00 \n",
+ "\n",
+ " geometry \n",
+ "0 POINT (-58.66 -34.58) \n",
+ "1 POINT (-47.91 -15.78) \n",
+ "2 POINT (-70.66 -33.45) \n",
+ "3 POINT (-74.08 4.6) \n",
+ "4 POINT (-66.86 10.48) "
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "df = pd.DataFrame({\n",
+ " \"City\": [\"Buenos Aires\", \"Brasilia\", \"Santiago\", \"Bogota\", \"Caracas\"],\n",
+ " \"Country\": [\"Argentina\", \"Brazil\", \"Chile\", \"Colombia\", \"Venezuela\"],\n",
+ " \"Latitude\": [-34.58, -15.78, -33.45, 4.60, 10.48],\n",
+ " \"Longitude\": [-58.66, -47.91, -70.66, -74.08, -66.86],\n",
+ " \"Timestamp\": pd.to_datetime([\n",
+ " \"2024-01-15 08:00\",\n",
+ " \"2024-02-20 09:30\",\n",
+ " \"2024-03-10 11:00\",\n",
+ " \"2024-04-05 14:15\",\n",
+ " \"2024-05-22 16:45\",\n",
+ " ]),\n",
+ "})\n",
+ "\n",
+ "gdf = geopandas.GeoDataFrame(\n",
+ " df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude)\n",
+ ")\n",
+ "display(gdf)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Load into kepler.gl"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.jupyter.widget-view+json": {
+ "model_id": "82b0ac8ca9fc49c7b2b9b29e46b3761f",
+ "version_major": 2,
+ "version_minor": 1
+ },
+ "text/plain": [
+ "<keplergl.widget.KeplerGl object at 0x115f62000>"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "import keplergl\n",
+ "\n",
+ "w = keplergl.KeplerGl(height=500)\n",
+ "w"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "w.add_data(data=gdf, name=\"cities\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Export to HTML\n",
+ "\n",
+ "The default `json_encoder=str` converts datetime values automatically."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Map saved to datetime_map.html!\n"
+ ]
+ }
+ ],
+ "source": [
+ "w.save_to_html(file_name=\"datetime_map.html\", read_only=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Custom json_encoder\n",
+ "\n",
+ "You can pass a custom function to control how non-serializable types\n",
+ "are encoded. For example, use `isoformat()` for ISO 8601 strings:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Map saved to datetime_map_iso.html!\n"
+ ]
+ }
+ ],
+ "source": [
+ "w.save_to_html(\n",
+ " file_name=\"datetime_map_iso.html\",\n",
+ " read_only=True,\n",
+ " json_encoder=lambda o: o.isoformat() if hasattr(o, \"isoformat\") else str(o),\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/bindings/python/notebooks/GeoDataFrame.ipynb b/bindings/python/notebooks/GeoDataFrame.ipynb
index 4be974457..b4bc20b96 100644
--- a/bindings/python/notebooks/GeoDataFrame.ipynb
+++ b/bindings/python/notebooks/GeoDataFrame.ipynb
@@ -139,12 +139,12 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
- "model_id": "0de352dc6ee744e7b073abff5b4d2d8c",
+ "model_id": "e8da0655899f4786aedd855e9d9d5fe8",
"version_major": 2,
"version_minor": 1
},
"text/plain": [
- "<keplergl.widget.KeplerGl object at 0x11f7d56a0>"
+ "<keplergl.widget.KeplerGl object at 0x1161ce2d0>"
]
},
"execution_count": 5,
@@ -185,8 +185,7 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "save_to_html() is no longer supported in this version.\n",
- "Please use the 'Share' button in the map config panel to export your map to HTML.\n"
+ "Map saved to city_map.html!\n"
]
}
],
diff --git a/bindings/python/notebooks/GeoJSON.ipynb b/bindings/python/notebooks/GeoJSON.ipynb
index cb7483e3b..fef6878b6 100644
--- a/bindings/python/notebooks/GeoJSON.ipynb
+++ b/bindings/python/notebooks/GeoJSON.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
@@ -12,21 +12,21 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
- "model_id": "4e568feadd104e7fa7b957693328369c",
+ "model_id": "225dc7b74849473b83f3cffba4f031ba",
"version_major": 2,
"version_minor": 1
},
"text/plain": [
- "<keplergl.widget.KeplerGl object at 0x10641c110>"
+ "<keplergl.widget.KeplerGl object at 0x109f1c320>"
]
},
- "execution_count": 3,
+ "execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
@@ -39,7 +39,7 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
@@ -48,15 +48,14 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
- "save_to_html() is no longer supported in this version.\n",
- "Please use the 'Share' button in the map config panel to export your map to HTML.\n"
+ "Map saved to geojson_map.html!\n"
]
}
],
diff --git a/bindings/python/notebooks/Load kepler.gl.ipynb b/bindings/python/notebooks/Load kepler.gl.ipynb
index 461506f44..341854750 100644
--- a/bindings/python/notebooks/Load kepler.gl.ipynb
+++ b/bindings/python/notebooks/Load kepler.gl.ipynb
@@ -64,12 +64,12 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
- "model_id": "bb5e76638fab46b39b476ad048984097",
+ "model_id": "bb76ecb992224bf39ba7e16d77a8b454",
"version_major": 2,
"version_minor": 1
},
"text/plain": [
- "<keplergl.widget.KeplerGl object at 0x11adf8c80>"
+ "<keplergl.widget.KeplerGl object at 0x12075e9c0>"
]
},
"execution_count": 4,
@@ -104,30 +104,16 @@
"data": {
"text/plain": [
"{'version': 'v1',\n",
- " 'config': {'visState': {'layers': [{'type': 'hexagonId',\n",
- " 'visualChannels': {'sizeField': {'type': 'integer', 'name': 'value'},\n",
- " 'coverageField': None,\n",
- " 'colorScale': 'quantize',\n",
- " 'coverageScale': 'linear',\n",
- " 'colorField': {'type': 'integer', 'name': 'value'},\n",
- " 'sizeScale': 'linear'},\n",
+ " 'config': {'visState': {'filters': [],\n",
+ " 'layers': [{'id': 'jdys7lp',\n",
+ " 'type': 'hexagonId',\n",
" 'config': {'dataId': 'data_1',\n",
- " 'color': [250, 116, 0],\n",
- " 'textLabel': {'color': [255, 255, 255],\n",
- " 'field': None,\n",
- " 'size': 50,\n",
- " 'anchor': 'middle',\n",
- " 'offset': [0, 0]},\n",
" 'label': 'H3 Hexagon',\n",
+ " 'color': [250, 116, 0],\n",
+ " 'highlightColor': [252, 242, 26, 255],\n",
+ " 'columns': {'hex_id': 'hex_id'},\n",
" 'isVisible': True,\n",
- " 'visConfig': {'coverageRange': [0, 1],\n",
- " 'opacity': 0.8,\n",
- " 'elevationScale': 5,\n",
- " 'hi-precision': False,\n",
- " 'coverage': 1,\n",
- " 'enable3d': True,\n",
- " 'sizeRange': [0, 500],\n",
- " 'colorRange': {'category': 'Uber',\n",
+ " 'visConfig': {'colorRange': {'category': 'Uber',\n",
" 'type': 'sequential',\n",
" 'colors': ['#194266',\n",
" '#355C7D',\n",
@@ -138,32 +124,88 @@
" '#E59A8F',\n",
" '#F8B195'],\n",
" 'reversed': False,\n",
- " 'name': 'Sunrise 8'}},\n",
- " 'columns': {'hex_id': 'hex_id'}},\n",
- " 'id': 'jdys7lp'}],\n",
- " 'interactionConfig': {'brush': {'enabled': False, 'size': 0.5},\n",
- " 'tooltip': {'fieldsToShow': {'data_1': ['hex_id', 'value']},\n",
- " 'enabled': True}},\n",
- " 'splitMaps': [],\n",
+ " 'name': 'Sunrise'},\n",
+ " 'filled': True,\n",
+ " 'opacity': 0.8,\n",
+ " 'outline': False,\n",
+ " 'strokeColor': None,\n",
+ " 'strokeColorRange': {'name': 'Global Warming',\n",
+ " 'type': 'sequential',\n",
+ " 'category': 'Uber',\n",
+ " 'colors': ['#4C0035',\n",
+ " '#880030',\n",
+ " '#B72F15',\n",
+ " '#D6610A',\n",
+ " '#EF9100',\n",
+ " '#FFC300']},\n",
+ " 'strokeOpacity': 0.8,\n",
+ " 'thickness': 2,\n",
+ " 'coverage': 1,\n",
+ " 'enable3d': True,\n",
+ " 'sizeRange': [0, 500],\n",
+ " 'coverageRange': [0, 1],\n",
+ " 'elevationScale': 5,\n",
+ " 'enableElevationZoomFactor': True,\n",
+ " 'fixedHeight': False},\n",
+ " 'hidden': False,\n",
+ " 'textLabel': [{'field': None,\n",
+ " 'color': [255, 255, 255],\n",
+ " 'size': 50,\n",
+ " 'offset': [0, 0],\n",
+ " 'anchor': 'middle',\n",
+ " 'alignment': 'center',\n",
+ " 'outlineWidth': 0,\n",
+ " 'outlineColor': [255, 0, 0, 255],\n",
+ " 'background': False,\n",
+ " 'backgroundColor': [0, 0, 200, 255]}]},\n",
+ " 'visualChannels': {'colorField': {'name': 'value', 'type': 'integer'},\n",
+ " 'colorScale': 'quantize',\n",
+ " 'strokeColorField': None,\n",
+ " 'strokeColorScale': 'quantile',\n",
+ " 'sizeField': {'name': 'value', 'type': 'integer'},\n",
+ " 'sizeScale': 'linear',\n",
+ " 'coverageField': None,\n",
+ " 'coverageScale': 'linear'}}],\n",
+ " 'effects': [],\n",
+ " 'interactionConfig': {'tooltip': {'fieldsToShow': {'data_1': [{'name': 'hex_id',\n",
+ " 'format': None},\n",
+ " {'name': 'value', 'format': None}]},\n",
+ " 'compareMode': False,\n",
+ " 'compareType': 'absolute',\n",
+ " 'enabled': True},\n",
+ " 'brush': {'size': 0.5, 'enabled': False},\n",
+ " 'geocoder': {'enabled': False},\n",
+ " 'coordinate': {'enabled': False}},\n",
" 'layerBlending': 'normal',\n",
- " 'filters': []},\n",
+ " 'overlayBlending': 'normal',\n",
+ " 'splitMaps': [],\n",
+ " 'animationConfig': {'currentTime': None, 'speed': 1},\n",
+ " 'editor': {'features': [], 'visible': True}},\n",
" 'mapState': {'bearing': 2.6192893401015205,\n",
" 'dragRotate': True,\n",
- " 'zoom': 12.32053899007826,\n",
+ " 'latitude': 37.76209132041332,\n",
" 'longitude': -122.42590232651203,\n",
- " 'isSplit': False,\n",
" 'pitch': 37.374216241015446,\n",
- " 'latitude': 37.76209132041332},\n",
- " 'mapStyle': {'mapStyles': {},\n",
+ " 'zoom': 12.32053899007826,\n",
+ " 'isSplit': False,\n",
+ " 'isViewportSynced': True,\n",
+ " 'isZoomLocked': False,\n",
+ " 'splitMapViewports': []},\n",
+ " 'mapStyle': {'styleType': 'dark-matter',\n",
" 'topLayerGroups': {},\n",
- " 'styleType': 'dark',\n",
- " 'visibleLayerGroups': {'building': True,\n",
- " 'land': True,\n",
- " '3d building': False,\n",
- " 'label': True,\n",
- " 'water': True,\n",
+ " 'visibleLayerGroups': {'label': True,\n",
+ " 'road': True,\n",
" 'border': False,\n",
- " 'road': True}}}}"
+ " 'building': True,\n",
+ " 'water': True,\n",
+ " 'land': True,\n",
+ " '3d building': False},\n",
+ " 'threeDBuildingColor': [15.035172933000911,\n",
+ " 15.035172933000911,\n",
+ " 15.035172933000911],\n",
+ " 'backgroundColor': [0, 0, 0],\n",
+ " 'mapStyles': {}},\n",
+ " 'uiState': {'mapControls': {'mapLegend': {'active': False}}}}}"
]
},
"execution_count": 6,
@@ -186,12 +228,131 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 8,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Map saved to first_map.html!\n"
+ ]
+ }
+ ],
"source": [
"w1.save_to_html(file_name='first_map.html', data={\"data_1\": df}, config=config)"
]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Apply a config with polygon color scale\n",
+ "\n",
+ "You can set layer styles, basemap, and more through the `config` dict.\n",
+ "The `config` structure mirrors what `w1.config` returns — you can interactively\n",
+ "style your map in the widget, then copy `w1.config` into your code.\n",
+ "\n",
+ "Below we load the GeoJSON zip code polygons and apply a config that:\n",
+ "- Uses a **geojson** layer with a quantize color scale on `OBJECTID`\n",
+ "- Sets the basemap to **positron** (a light free basemap, no Mapbox token needed)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.jupyter.widget-view+json": {
+ "model_id": "80748740e6f44091870ef47350115a31",
+ "version_major": 2,
+ "version_minor": 1
+ },
+ "text/plain": [
+ "<keplergl.widget.KeplerGl object at 0x130837980>"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "polygon_config = {\n",
+ " 'version': 'v1',\n",
+ " 'config': {\n",
+ " 'visState': {\n",
+ " 'layers': [{\n",
+ " 'type': 'geojson',\n",
+ " 'config': {\n",
+ " 'dataId': 'zip_codes',\n",
+ " 'label': 'SF Zip Codes',\n",
+ " 'isVisible': True,\n",
+ " 'visConfig': {\n",
+ " 'opacity': 0.8,\n",
+ " 'filled': True,\n",
+ " 'stroked': True,\n",
+ " 'thickness': 1,\n",
+ " 'colorRange': {\n",
+ " 'name': 'Sunrise 8',\n",
+ " 'type': 'sequential',\n",
+ " 'category': 'Uber',\n",
+ " 'colors': [\n",
+ " '#194266', '#355C7D', '#63617F', '#916681',\n",
+ " '#C06C84', '#D28389', '#E59A8F', '#F8B195'\n",
+ " ]\n",
+ " }\n",
+ " },\n",
+ " 'columns': {'geojson': '_geojson'}\n",
+ " },\n",
+ " 'visualChannels': {\n",
+ " 'colorField': {'name': 'OBJECTID', 'type': 'integer'},\n",
+ " 'colorScale': 'quantize'\n",
+ " }\n",
+ " }]\n",
+ " },\n",
+ " 'mapStyle': {\n",
+ " 'styleType': 'positron'\n",
+ " }\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "w2 = keplergl.KeplerGl(\n",
+ " height=500,\n",
+ " data={'zip_codes': json_data},\n",
+ " config=polygon_config,\n",
+ " theme='light',\n",
+ " app_name='SF Zip Codes'\n",
+ ")\n",
+ "w2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Map saved to sf_zip_styled.html!\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Export the styled polygon map\n",
+ "w2.save_to_html(file_name='sf_zip_styled.html')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
diff --git a/bindings/python/notebooks/Theme and App Name.ipynb b/bindings/python/notebooks/Theme and App Name.ipynb
new file mode 100644
index 000000000..5d9cc60f7
--- /dev/null
+++ b/bindings/python/notebooks/Theme and App Name.ipynb
@@ -0,0 +1,192 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Theme and App Name\n",
+ "\n",
+ "This notebook demonstrates how to customize the kepler.gl UI theme and application name.\n",
+ "\n",
+ "**`theme`** controls the kepler.gl UI appearance:\n",
+ "- `\"light\"` – light UI, pairs well with Mapbox light basemap styles\n",
+ "- `\"dark\"` – dark UI (default)\n",
+ "- `\"base\"` – base theme\n",
+ "\n",
+ "**`app_name`** controls the title shown in the side panel header and the HTML `<title>` when exporting."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import pandas as pd\n",
+ "import keplergl"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "df = pd.DataFrame({\n",
+ " 'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],\n",
+ " 'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],\n",
+ " 'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],\n",
+ " 'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86]\n",
+ "})"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Default (dark theme)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.jupyter.widget-view+json": {
+ "model_id": "dd4973c6f6294e22be290563363f66f1",
+ "version_major": 2,
+ "version_minor": 1
+ },
+ "text/plain": [
+ "<keplergl.widget.KeplerGl object at 0x10db8d070>"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "w_default = keplergl.KeplerGl(height=400, data={'cities': df})\n",
+ "w_default"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Light theme with custom app name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.jupyter.widget-view+json": {
+ "model_id": "2711ffcffb5845acabd195c823da7fba",
+ "version_major": 2,
+ "version_minor": 1
+ },
+ "text/plain": [
+ "<keplergl.widget.KeplerGl object at 0x10db8f170>"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "w_light = keplergl.KeplerGl(\n",
+ " height=400,\n",
+ " data={'cities': df},\n",
+ " theme='light',\n",
+ " app_name='City Explorer'\n",
+ ")\n",
+ "w_light"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Export to HTML\n",
+ "\n",
+ "Both `theme` and `app_name` carry over to `save_to_html`. You can also override them at export time."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Map saved to light_theme_map.html!\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Uses the widget's theme=\"light\" and app_name=\"City Explorer\"\n",
+ "w_light.save_to_html(file_name='light_theme_map.html')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Map saved to custom_export.html!\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Override theme and app_name at export time\n",
+ "w_default.save_to_html(\n",
+ " file_name='custom_export.html',\n",
+ " theme='light',\n",
+ " app_name='My Custom Map'\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/bindings/python/notebooks/hex_config.py b/bindings/python/notebooks/hex_config.py
index 798799724..7486e8ab0 100644
--- a/bindings/python/notebooks/hex_config.py
+++ b/bindings/python/notebooks/hex_config.py
@@ -1,4 +1,4 @@
# SPDX-License-Identifier: MIT
# Copyright contributors to the kepler.gl project
-config = {u'version': u'v1', u'config': {u'visState': {u'layers': [{u'type': u'hexagonId', u'visualChannels': {u'sizeField': {u'type': u'integer', u'name': u'value'}, u'coverageField': None, u'colorScale': u'quantize', u'coverageScale': u'linear', u'colorField': {u'type': u'integer', u'name': u'value'}, u'sizeScale': u'linear'}, u'config': {u'dataId': u'data_1', u'color': [250, 116, 0], u'textLabel': {u'color': [255, 255, 255], u'field': None, u'size': 50, u'anchor': u'middle', u'offset': [0, 0]}, u'label': u'H3 Hexagon', u'isVisible': True, u'visConfig': {u'coverageRange': [0, 1], u'opacity': 0.8, u'elevationScale': 5, u'hi-precision': False, u'coverage': 1, u'enable3d': True, u'sizeRange': [0, 500], u'colorRange': {u'category': u'Uber', u'type': u'sequential', u'colors': [u'#194266', u'#355C7D', u'#63617F', u'#916681', u'#C06C84', u'#D28389', u'#E59A8F', u'#F8B195'], u'reversed': False, u'name': u'Sunrise 8'}}, u'columns': {u'hex_id': u'hex_id'}}, u'id': u'jdys7lp'}], u'interactionConfig': {u'brush': {u'enabled': False, u'size': 0.5}, u'tooltip': {u'fieldsToShow': {u'data_1': [u'hex_id', u'value']}, u'enabled': True}}, u'splitMaps': [], u'layerBlending': u'normal', u'filters': []}, u'mapState': {u'bearing': 2.6192893401015205, u'dragRotate': True, u'zoom': 12.32053899007826, u'longitude': -122.42590232651203, u'isSplit': False, u'pitch': 37.374216241015446, u'latitude': 37.76209132041332}, u'mapStyle': {u'mapStyles': {}, u'topLayerGroups': {}, u'styleType': u'dark', u'visibleLayerGroups': {u'building': True, u'land': True, u'3d building': False, u'label': True, u'water': True, u'border': False, u'road': True}}}}
\ No newline at end of file
+config = {u'version': u'v1', u'config': {u'visState': {u'layers': [{u'type': u'hexagonId', u'visualChannels': {u'sizeField': {u'type': u'integer', u'name': u'value'}, u'coverageField': None, u'colorScale': u'quantize', u'coverageScale': u'linear', u'colorField': {u'type': u'integer', u'name': u'value'}, u'sizeScale': u'linear'}, u'config': {u'dataId': u'data_1', u'color': [250, 116, 0], u'textLabel': {u'color': [255, 255, 255], u'field': None, u'size': 50, u'anchor': u'middle', u'offset': [0, 0]}, u'label': u'H3 Hexagon', u'isVisible': True, u'visConfig': {u'coverageRange': [0, 1], u'opacity': 0.8, u'elevationScale': 5, u'hi-precision': False, u'coverage': 1, u'enable3d': True, u'sizeRange': [0, 500], u'colorRange': {u'category': u'Uber', u'type': u'sequential', u'colors': [u'#194266', u'#355C7D', u'#63617F', u'#916681', u'#C06C84', u'#D28389', u'#E59A8F', u'#F8B195'], u'reversed': False, u'name': u'Sunrise 8'}}, u'columns': {u'hex_id': u'hex_id'}}, u'id': u'jdys7lp'}], u'interactionConfig': {u'brush': {u'enabled': False, u'size': 0.5}, u'tooltip': {u'fieldsToShow': {u'data_1': [u'hex_id', u'value']}, u'enabled': True}}, u'splitMaps': [], u'layerBlending': u'normal', u'filters': []}, u'mapState': {u'bearing': 2.6192893401015205, u'dragRotate': True, u'zoom': 12.32053899007826, u'longitude': -122.42590232651203, u'isSplit': False, u'pitch': 37.374216241015446, u'latitude': 37.76209132041332}, u'mapStyle': {u'mapStyles': {}, u'topLayerGroups': {}, u'styleType': u'dark-matter', u'visibleLayerGroups': {u'building': True, u'land': True, u'3d building': False, u'label': True, u'water': True, u'border': False, u'road': True}}}}
\ No newline at end of file
diff --git a/bindings/python/pyproject.toml b/bindings/python/pyproject.toml
index 5194af007..1a76e3718 100644
--- a/bindings/python/pyproject.toml
+++ b/bindings/python/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "keplergl"
-version = "0.4.0rc2"
+version = "0.4.0rc4"
description = "Kepler.gl Jupyter Widget"
readme = "README.md"
requires-python = ">=3.9"
diff --git a/bindings/python/src/components/App.tsx b/bindings/python/src/components/App.tsx
index 3b1b1341c..1ea5b51a9 100644
--- a/bindings/python/src/components/App.tsx
+++ b/bindings/python/src/components/App.tsx
@@ -4,19 +4,34 @@
import React, {useEffect, useState, useRef} from 'react';
import {injectComponents} from '@kepler.gl/components';
import {KEPLER_ID} from '../store';
+import {theme as basicTheme, themeLT, themeBS} from '@kepler.gl/styles';
import type {WidgetModel} from '../types';
-// Get the KeplerGl container component via dependency injection
const KeplerGl = injectComponents();
interface AppProps {
model: WidgetModel;
}
+function resolveTheme(themeValue: string): object | undefined {
+ switch (themeValue) {
+ case 'light':
+ return themeLT;
+ case 'base':
+ return themeBS;
+ case 'dark':
+ return basicTheme;
+ default:
+ return undefined;
+ }
+}
+
export function App({model}: AppProps) {
const [height, setHeight] = useState(model.get('height'));
const [width, setWidth] = useState(800);
const [mapboxToken, setMapboxToken] = useState(model.get('mapbox_token') || '');
+ const [theme, setTheme] = useState(model.get('theme') || '');
+ const [appName, setAppName] = useState(model.get('app_name') || 'kepler.gl');
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -31,6 +46,18 @@ export function App({model}: AppProps) {
return () => model.off('change:mapbox_token', handleTokenChange);
}, [model]);
+ useEffect(() => {
+ const handleThemeChange = () => setTheme(model.get('theme') || '');
+ model.on('change:theme', handleThemeChange);
+ return () => model.off('change:theme', handleThemeChange);
+ }, [model]);
+
+ useEffect(() => {
+ const handleAppNameChange = () => setAppName(model.get('app_name') || 'kepler.gl');
+ model.on('change:app_name', handleAppNameChange);
+ return () => model.off('change:app_name', handleAppNameChange);
+ }, [model]);
+
// Observe container width changes
useEffect(() => {
if (!containerRef.current) return;
@@ -47,9 +74,18 @@ export function App({model}: AppProps) {
return () => resizeObserver.disconnect();
}, []);
+ const resolvedTheme = resolveTheme(theme);
+
return (
<div ref={containerRef} style={{width: '100%', height}}>
- <KeplerGl id={KEPLER_ID} width={width} height={height} mapboxApiAccessToken={mapboxToken} />
+ <KeplerGl
+ id={KEPLER_ID}
+ width={width}
+ height={height}
+ mapboxApiAccessToken={mapboxToken}
+ appName={appName}
+ {...(resolvedTheme ? {theme: resolvedTheme} : {})}
+ />
</div>
);
}
diff --git a/bindings/python/src/types.ts b/bindings/python/src/types.ts
index 478a7be9c..a5d691860 100644
--- a/bindings/python/src/types.ts
+++ b/bindings/python/src/types.ts
@@ -8,6 +8,8 @@ export interface KeplerGlWidgetModel {
config: KeplerGlConfig;
height: number;
mapbox_token: string;
+ theme: string;
+ app_name: string;
}
export interface DatasetPayload {
diff --git a/bindings/python/src/widget.ts b/bindings/python/src/widget.ts
index 67175af5d..b70370c39 100644
--- a/bindings/python/src/widget.ts
+++ b/bindings/python/src/widget.ts
@@ -8,8 +8,8 @@ import {createStore, KEPLER_ID} from './store';
import {App} from './components/App';
import {processDataset} from './utils/data';
import type {WidgetModel, DatasetPayload} from './types';
-import type {ParsedConfig} from '@kepler.gl/types';
-import {addDataToMap, receiveMapConfig, wrapTo} from '@kepler.gl/actions';
+import type {AddDataToMapPayload} from '@kepler.gl/types';
+import {addDataToMap, wrapTo} from '@kepler.gl/actions';
import KeplerGlSchema from '@kepler.gl/schemas';
const DEBUG = false;
@@ -24,9 +24,10 @@ export class KeplerGlWidget {
private el: HTMLElement;
private root: Root | null = null;
private store: ReturnType<typeof createStore>;
- private previousConfigHash: string = '';
- private mapUpdateCounter: number = 0;
- private isSyncingConfig: boolean = false;
+ private previousConfigHash = '';
+ private mapUpdateCounter = 0;
+ private isSyncingConfig = false;
+ private loadedDatasetHashes: Map<string, string> = new Map();
constructor(model: WidgetModel, el: HTMLElement) {
debug('KeplerGlWidget constructor');
@@ -46,8 +47,7 @@ export class KeplerGlWidget {
})
);
- this.loadData();
- this.loadConfig();
+ this.loadInitial();
this.store.subscribe(() => this.syncConfigToPython());
}
@@ -78,45 +78,104 @@ export class KeplerGlWidget {
this.el.style.height = `${this.model.get('height')}px`;
}
+ private async loadInitial() {
+ const data = this.model.get('data');
+ const config = this.model.get('config');
+ debug(
+ 'loadInitial() called, data keys:',
+ Object.keys(data),
+ 'has config:',
+ !!(config && Object.keys(config).length)
+ );
+
+ await this.waitForInstance();
+
+ const datasets = await this.processAllDatasets(data);
+
+ if (datasets.length > 0 || (config && Object.keys(config).length > 0)) {
+ const hasMapState = !!config?.config?.mapState;
+ const payload: Record<string, unknown> = {
+ datasets,
+ options: {centerMap: !hasMapState, readOnly: false}
+ };
+ if (config && Object.keys(config).length > 0) {
+ payload.config = config;
+ this.previousConfigHash = JSON.stringify(config);
+ }
+ const action = addDataToMap(payload as AddDataToMapPayload);
+ this.store.dispatch(wrapTo(KEPLER_ID, action));
+ for (const [name, dataPayload] of Object.entries(data)) {
+ this.loadedDatasetHashes.set(name, JSON.stringify(dataPayload));
+ }
+ debug('loadInitial: dispatched addDataToMap with datasets + config');
+ }
+ }
+
private async loadData() {
const data = this.model.get('data');
debug('loadData() called, data keys:', Object.keys(data));
- debug('loadData() raw data:', JSON.stringify(data, null, 2));
- // Wait for the KeplerGl component to register itself
await this.waitForInstance();
+ const currentNames = new Set(Object.keys(data));
+
+ for (const prevName of this.loadedDatasetHashes.keys()) {
+ if (!currentNames.has(prevName)) {
+ this.loadedDatasetHashes.delete(prevName);
+ debug(`Dataset '${prevName}' removed`);
+ }
+ }
+
for (const [name, payload] of Object.entries(data)) {
+ const hash = JSON.stringify(payload);
+ if (this.loadedDatasetHashes.get(name) === hash) {
+ continue;
+ }
debug(`Processing dataset '${name}'...`);
try {
const processed = await processDataset(payload as DatasetPayload);
- debug(
- `Dataset '${name}' processed:`,
- processed ? {fields: processed.fields, rowCount: processed.rows?.length} : null
- );
-
if (!processed) {
debug(`Dataset '${name}' returned null, skipping`);
continue;
}
-
const action = addDataToMap({
datasets: {
info: {id: name, label: name},
data: processed
- }
- });
- // Wrap the action to target the specific kepler.gl instance
- const wrappedAction = wrapTo(KEPLER_ID, action);
- debug(`Dispatching addDataToMap for '${name}'`, wrappedAction);
- this.store.dispatch(wrappedAction);
- debug(`addDataToMap dispatched for '${name}'`);
+ },
+ options: {centerMap: true, readOnly: false, keepExistingConfig: true}
+ } as AddDataToMapPayload);
+ this.store.dispatch(wrapTo(KEPLER_ID, action));
+ this.loadedDatasetHashes.set(name, hash);
+ debug(`Dataset '${name}' dispatched`);
} catch (error) {
console.error(`[keplergl-widget] Error processing dataset '${name}':`, error);
}
}
+ }
- debug('loadData() complete, store state:', this.store.getState());
+ private async processAllDatasets(
+ data: Record<string, DatasetPayload>
+ ): Promise<Array<{info: {id: string; label: string}; data: unknown}>> {
+ const datasets: Array<{info: {id: string; label: string}; data: unknown}> = [];
+ for (const [name, payload] of Object.entries(data)) {
+ debug(`Processing dataset '${name}'...`);
+ try {
+ const processed = await processDataset(payload as DatasetPayload);
+ if (!processed) {
+ debug(`Dataset '${name}' returned null, skipping`);
+ continue;
+ }
+ datasets.push({
+ info: {id: name, label: name},
+ data: processed
+ });
+ debug(`Dataset '${name}' processed successfully`);
+ } catch (error) {
+ console.error(`[keplergl-widget] Error processing dataset '${name}':`, error);
+ }
+ }
+ return datasets;
}
private waitForInstance(): Promise<void> {
@@ -155,7 +214,12 @@ export class KeplerGlWidget {
debug('loadConfig() called, config:', config);
if (config && Object.keys(config).length > 0) {
this.isSyncingConfig = true;
- this.store.dispatch(wrapTo(KEPLER_ID, receiveMapConfig(config as ParsedConfig, {})));
+ const action = addDataToMap({
+ datasets: [],
+ config,
+ options: {centerMap: false, keepExistingConfig: true}
+ } as AddDataToMapPayload);
+ this.store.dispatch(wrapTo(KEPLER_ID, action));
this.previousConfigHash = JSON.stringify(config);
this.isSyncingConfig = false;
}
diff --git a/bindings/python/tests/test_html_export.py b/bindings/python/tests/test_html_export.py
index 8024765ac..c75bb1048 100644
--- a/bindings/python/tests/test_html_export.py
+++ b/bindings/python/tests/test_html_export.py
@@ -146,6 +146,36 @@ class TestDatasetToGeojson:
def test_int_returns_none(self):
assert _dataset_to_geojson(42) is None
+ def test_geodataframe_with_datetime(self):
+ """GeoDataFrame with datetime column should serialize without error."""
+ gdf = gpd.GeoDataFrame(
+ {
+ "name": ["A", "B"],
+ "timestamp": pd.to_datetime(["2024-01-01", "2024-06-15"]),
+ },
+ geometry=[Point(-122.4, 37.8), Point(-118.2, 34.0)],
+ crs="EPSG:4326",
+ )
+ result = _dataset_to_geojson(gdf)
+ assert result is not None
+ assert result["type"] == "FeatureCollection"
+ assert len(result["features"]) == 2
+ ts_val = result["features"][0]["properties"]["timestamp"]
+ assert "2024" in str(ts_val)
+
+ def test_geodataframe_with_datetime_custom_encoder(self):
+ """json_encoder=None should raise on datetime columns."""
+ gdf = gpd.GeoDataFrame(
+ {
+ "name": ["A"],
+ "timestamp": pd.to_datetime(["2024-01-01"]),
+ },
+ geometry=[Point(-122.4, 37.8)],
+ crs="EPSG:4326",
+ )
+ with pytest.raises(TypeError):
+ _dataset_to_geojson(gdf, json_encoder=None)
+
class TestSerializeDatasetsForHtml:
"""Tests for _serialize_datasets_for_html JS snippet generation."""
@@ -184,6 +214,20 @@ class TestSerializeDatasetsForHtml:
js = _serialize_datasets_for_html({})
assert js == ""
+ def test_geodataframe_with_datetime(self):
+ """Datetime columns in GeoDataFrame should not break JS snippet generation."""
+ gdf = gpd.GeoDataFrame(
+ {
+ "name": ["A"],
+ "ts": pd.to_datetime(["2024-03-01"]),
+ },
+ geometry=[Point(-122.4, 37.8)],
+ crs="EPSG:4326",
+ )
+ js = _serialize_datasets_for_html({"events": gdf})
+ assert "processGeojson" in js
+ assert "2024" in js
+
class TestExportMapHtml:
"""Tests for the full export_map_html function."""
@@ -272,6 +316,30 @@ class TestExportMapHtml:
assert "processGeojson" in html
assert "FeatureCollection" in html
+ def test_light_theme(self, sample_df):
+ html = export_map_html(data={"d": sample_df}, config={}, theme="light")
+ assert '"light"' in html
+
+ def test_dark_theme(self, sample_df):
+ html = export_map_html(data={"d": sample_df}, config={}, theme="dark")
+ assert '"dark"' in html
+
+ def test_no_theme_omits_prop(self, sample_df):
+ html = export_map_html(data={"d": sample_df}, config={}, theme="")
+ assert "theme:" not in html or "undefined" in html
+
+ def test_custom_app_name_in_title(self, sample_df):
+ html = export_map_html(data={"d": sample_df}, config={}, app_name="My Dashboard")
+ assert "<title>My Dashboard embedded map</title>" in html
+
+ def test_custom_app_name_in_component(self, sample_df):
+ html = export_map_html(data={"d": sample_df}, config={}, app_name="My Dashboard")
+ assert '"My Dashboard"' in html
+
+ def test_default_app_name(self, sample_df):
+ html = export_map_html(data={"d": sample_df}, config={})
+ assert "<title>kepler.gl embedded map</title>" in html
+
class TestSaveToHtml:
"""Tests for the KeplerGl.save_to_html widget method."""
@@ -349,3 +417,62 @@ class TestSaveToHtml:
content = f.read()
assert "São Paulo" in content
assert "Zürich" in content
+
+ def test_saves_geodataframe_with_datetime(self, tmp_path):
+ """Regression: GeoDataFrame with datetime column should export to HTML."""
+ gdf = gpd.GeoDataFrame(
+ {
+ "name": ["SF"],
+ "timestamp": pd.to_datetime(["2024-01-15 10:30:00"]),
+ },
+ geometry=[Point(-122.4, 37.8)],
+ crs="EPSG:4326",
+ )
+ widget = KeplerGl(data={"events": gdf})
+ out = str(tmp_path / "map.html")
+ widget.save_to_html(file_name=out)
+ with open(out, encoding="utf-8") as f:
+ content = f.read()
+ assert "processGeojson" in content
+ assert "2024" in content
+
+ def test_saves_with_custom_json_encoder(self, sample_gdf, tmp_path):
+ """json_encoder parameter is forwarded through save_to_html."""
+ widget = KeplerGl(data={"geo": sample_gdf})
+ out = str(tmp_path / "map.html")
+ widget.save_to_html(file_name=out, json_encoder=repr)
+ assert os.path.exists(out)
+
+ def test_saves_with_light_theme(self, sample_df, tmp_path):
+ widget = KeplerGl(data={"d": sample_df}, theme="light")
+ out = str(tmp_path / "map.html")
+ widget.save_to_html(file_name=out)
+ with open(out) as f:
+ content = f.read()
+ assert '"light"' in content
+
+ def test_saves_with_theme_override(self, sample_df, tmp_path):
+ widget = KeplerGl(data={"d": sample_df}, theme="dark")
+ out = str(tmp_path / "map.html")
+ widget.save_to_html(file_name=out, theme="light")
+ with open(out) as f:
+ content = f.read()
+ assert '"light"' in content
+
+ def test_saves_with_custom_app_name(self, sample_df, tmp_path):
+ widget = KeplerGl(data={"d": sample_df}, app_name="My Map")
+ out = str(tmp_path / "map.html")
+ widget.save_to_html(file_name=out)
+ with open(out) as f:
+ content = f.read()
+ assert "<title>My Map embedded map</title>" in content
+ assert '"My Map"' in content
+
+ def test_saves_with_app_name_override(self, sample_df, tmp_path):
+ widget = KeplerGl(data={"d": sample_df}, app_name="Original")
+ out = str(tmp_path / "map.html")
+ widget.save_to_html(file_name=out, app_name="Override")
+ with open(out) as f:
+ content = f.read()
+ assert "<title>Override embedded map</title>" in content
+ assert '"Override"' in content
diff --git a/bindings/python/tests/test_serializers.py b/bindings/python/tests/test_serializers.py
index 4c91daac4..e29ec1108 100644
--- a/bindings/python/tests/test_serializers.py
+++ b/bindings/python/tests/test_serializers.py
@@ -140,6 +140,28 @@ class TestGeoDataFrameSerialization:
assert result["format"] == "geoarrow"
assert "data" in result
+ def test_serialize_empty_geodataframe(self):
+ """Test that an empty GeoDataFrame serializes without error."""
+ gdf = gpd.GeoDataFrame(
+ {"name": pd.Series([], dtype="str")},
+ geometry=gpd.GeoSeries([], crs="EPSG:4326"),
+ )
+ result = serialize_dataset(gdf, "empty")
+ assert result["id"] == "empty"
+ assert result["format"] == "geoarrow"
+ assert "data" in result
+
+ def test_serialize_all_null_geometry_geodataframe(self):
+ """Test that a GeoDataFrame with all-null geometries serializes without error."""
+ gdf = gpd.GeoDataFrame(
+ {"name": ["a", "b"]},
+ geometry=[None, None],
+ )
+ result = serialize_dataset(gdf, "nulls")
+ assert result["id"] == "nulls"
+ assert result["format"] == "geoarrow"
+ assert "data" in result
+
class TestGeoJSONSerialization:
"""Tests for GeoJSON serialization (from GeoJSON.ipynb)."""
diff --git a/bindings/python/uv.lock b/bindings/python/uv.lock
index 3b694f4d2..cecbb5a51 100644
--- a/bindings/python/uv.lock
+++ b/bindings/python/uv.lock
@@ -1582,7 +1582,7 @@ wheels = [
[[package]]
name = "keplergl"
-version = "0.4.0rc2"
+version = "0.4.0rc4"
source = { editable = "." }
dependencies = [
{ name = "anywidget" },