Skip to content

Viewer

The main entry point for building CesiumJS visualizations.

viewer

The main Viewer class — primary entry point for cesiumkit.

Classes:

Name Description
Viewer

The main cesiumkit object. Corresponds to Cesium.Viewer.

Viewer

Viewer(
    ion_token: str | None = None,
    container_id: str = "cesiumContainer",
    width: str = "100%",
    height: str = "100%",
    title: str = "cesiumkit",
    animation: bool | None = None,
    base_layer_picker: bool | None = None,
    fullscreen_button: bool | None = None,
    vr_button: bool | None = None,
    geocoder: bool | None = None,
    home_button: bool | None = None,
    info_box: bool | None = None,
    scene_mode_picker: bool | None = None,
    selection_indicator: bool | None = None,
    timeline: bool | None = None,
    navigation_help_button: bool | None = None,
    navigation_instructions_initially_visible: bool | None = None,
    request_render_mode: bool | None = None,
    maximum_render_time_change: float | None = None,
    resolution_scale: float | None = None,
    target_frame_rate: int | None = None,
    show_renderer_errors: bool | None = None,
    scene_mode: SceneMode | None = None,
    scene3d_only: bool | None = None,
    shadows: ShadowMode | None = None,
    terrain_shadows: ShadowMode | None = None,
    scene: SceneConfig | None = None,
    globe: GlobeConfig | None = None,
    terrain_provider: TerrainProvider | None = None,
    imagery_provider: ImageryProvider | None = None,
    clock: ClockConfig | None = None,
    should_animate: bool | None = None,
    camera: Camera | None = None,
    clustering: EntityClusterConfig | None = None,
)

The main cesiumkit object. Corresponds to Cesium.Viewer.

This is the primary entry point for building CesiumJS visualizations. Add entities, data sources, configure the camera, and render to HTML.

Methods:

Name Description
add_entity

Add an entity. Can pass an Entity instance or keyword args.

remove_entity

Remove an entity from the viewer.

remove_entity_by_id

Remove an entity by its ID.

clear_entities

Remove all entities from the viewer.

get_entity

Get an entity by its ID, or None if not found.

add_geodataframe

Add all features from a geopandas.GeoDataFrame to this Viewer.

add_dataframe

Add point entities from a plain pandas.DataFrame with lon/lat columns.

add_data_source

Add a data source.

load_czml

Load CZML data.

load_geojson

Load GeoJSON data.

load_kml

Load KML/KMZ data.

add_tileset

Add a 3D Tiles tileset.

add_primitive

Add a scene primitive such as a particle system.

add_classification

Draw a filled polygon onto terrain or 3D Tiles.

add_raster

Display a local raster (GeoTIFF/COG path or xarray DataArray).

add_wmts_layer

Stack a remote WMTS layer over the current imagery.

add_points

Add points from a GeoDataFrame, optionally aggregated via datashader.

add_particle_system

Add a :class:cesiumkit.ParticleSystem scene primitive.

on

Register a screen space event handler.

on_click

Register a Python callback for left-click events on entities.

wait_for_click

Wait for the next left click and return its entity ID, if any.

add_script

Add custom JavaScript code to be executed after viewer setup.

fly_to

Fly the camera to a destination.

set_view

Set the camera view immediately.

look_at

Point the camera at a target.

fly_to_entities

Fly the camera to fit the extent of all entities.

fly_to_bounding_sphere

Fly the camera to a bounding sphere.

to_widget

Return a Jupyter widget for this viewer (requires [widget] extras).

set_time

Jump the timeline to a specific ISO 8601 epoch and update the widget.

animate

Start or stop clock playback.

set_multiplier

Change the clock playback speed.

get_current_time

Return the live viewer clock as an ISO 8601 string.

screenshot_base64

Return a PNG screenshot of the live viewer as base64 text.

screenshot

Save a PNG screenshot of the live viewer.

canvas_to_image

Return a screenshot as a detached Pillow image.

select_entity

Select a viewer entity by ID.

deselect

Clear the live viewer selection.

pick

Return the local entity at a screen position.

drill_pick

Return all local entities at a screen position.

update_czml

Replace the first live CZML data source from a URL or CZML packets.

update_geojson

Replace the first live GeoJSON data source from a URL or mapping.

poll_czml

Refresh CZML from url in the browser at a fixed interval.

stop_polling

Stop a browser-side data-source poller.

stream_czml

Consume CZML packet batches in a daemon thread and queue live updates.

to_html

Render the complete standalone HTML document string.

save

Save to an HTML file.

__enter__

Return this viewer and close its runtime resources on exit.

close

Stop the local server and release all viewer-owned resources.

show

Launch a local HTTP server and open the visualization in a browser.

show_in_browser

Alias for show(). Opens visualization via local HTTP server.

to_czml

Export all entities as CZML JSON.

to_czml_string

Export CZML as formatted JSON string.

save_czml

Save CZML to a .czml file.

Attributes:

Name Type Description
entity_count int

Number of entities currently in the viewer.

selected_entity Entity | None

Return the selected local entity, or None if it is not local.

entity_count property

entity_count: int

Number of entities currently in the viewer.

selected_entity property

selected_entity: Entity | None

Return the selected local entity, or None if it is not local.

add_entity

add_entity(entity: Any = None, **kwargs: Any) -> Any

Add an entity. Can pass an Entity instance or keyword args.

remove_entity

remove_entity(entity: Any) -> bool

Remove an entity from the viewer.

Returns True if the entity was found and removed.

remove_entity_by_id

remove_entity_by_id(entity_id: str) -> bool

Remove an entity by its ID.

Returns True if the entity was found and removed.

clear_entities

clear_entities() -> None

Remove all entities from the viewer.

get_entity

get_entity(entity_id: str) -> Any | None

Get an entity by its ID, or None if not found.

add_geodataframe

add_geodataframe(gdf: Any, **options: Any) -> list[Any]

Add all features from a geopandas.GeoDataFrame to this Viewer.

This is a one-line shortcut for the most common geospatial workflow: load a GeoDataFrame, drop it on the globe. The GeoDataFrame is auto-reprojected to WGS84 (EPSG:4326) if needed. All keyword arguments are forwarded to cesiumkit.gis.geodataframe_to_entities.

Returns the list of created entities so they can be further customized.

add_dataframe

add_dataframe(df: Any, lon_col: str, lat_col: str, **options: Any) -> list[Any]

Add point entities from a plain pandas.DataFrame with lon/lat columns.

Shortcut for cesiumkit.gis.dataframe_to_entities that also attaches each entity to the viewer. Returns the list of created entities.

add_data_source

add_data_source(data_source: Any) -> Any

Add a data source.

load_czml

load_czml(url: str | None = None, data: list[dict] | None = None) -> Any

Load CZML data.

load_geojson

load_geojson(
    url: str | None = None, data: dict | None = None, **kwargs: Any
) -> Any

Load GeoJSON data.

load_kml

load_kml(url: str, **kwargs: Any) -> Any

Load KML/KMZ data.

add_tileset

add_tileset(
    url: str | None = None, ion_asset_id: int | None = None, **kwargs: Any
) -> Any

Add a 3D Tiles tileset.

add_primitive

add_primitive(primitive: Any) -> Any

Add a scene primitive such as a particle system.

add_classification

add_classification(
    positions: list[Cartesian3],
    *,
    color: Color | str | None = None,
    height: float = 0.0,
    extruded_height: float = 100000.0,
    classification_type: ClassificationType | None = None,
) -> ClassificationPrimitive

Draw a filled polygon onto terrain or 3D Tiles.

The polygon reuses the depth of the surface it drapes over, so it follows hills and buildings instead of floating. positions are ECEF points (use Cartesian3FromDegrees). height and extruded_height bound the required classification volume; classification_type is one of ClassificationType.TERRAIN, CESIUM_3D_TILE, or BOTH (the default).

add_raster

add_raster(
    source: Any,
    *,
    name: str | None = None,
    opacity: float = 1.0,
    maximum_level: int | None = None,
) -> RasterSource

Display a local raster (GeoTIFF/COG path or xarray DataArray).

Requires [raster] extras (rio-tiler/rasterio/xarray). The raster is served as Web Mercator tiles by the show() server. The first raster becomes the viewer's base imagery layer; later rasters stack on top of it, each with its own opacity (0.0 to 1.0). Overlays keep the order they were added in, WMTS and raster alike; the first raster is always the base. Needs a running server (not static HTML export). maximum_level must be a plain int (numpy integers are rejected).

add_wmts_layer

add_wmts_layer(
    url: str,
    layer: str,
    *,
    style: str = "",
    tile_matrix_set: str = "default",
    format: str = "image/png",
    maximum_level: int | None = None,
    opacity: float = 1.0,
) -> None

Stack a remote WMTS layer over the current imagery.

layer/style/tile_matrix_set map to the WMTS capabilities for the service at url. The layer is added on top of whatever imagery is already configured, with its own opacity. Overlays keep the order they were added in, raster and WMTS alike; the first raster is always the base. maximum_level must be a plain int (numpy integers are rejected).

add_points

add_points(
    gdf: Any,
    *,
    aggregation: bool = True,
    colormap: list[str] | None = None,
    plot_width: int = 1024,
    plot_height: int = 512,
    **kwargs: Any,
) -> Any

Add points from a GeoDataFrame, optionally aggregated via datashader.

With aggregation=True (default) the points are rasterized with datashader ([datashader] extras) into an imagery layer, which stays responsive for millions of points. colormap is a list of CSS colors for the shading ramp. Pass aggregation=False to fall back to per-point entities.

add_particle_system

add_particle_system(particle_system: Any = None, **kwargs: Any) -> Any

Add a :class:cesiumkit.ParticleSystem scene primitive.

on

on(event_type: ScreenSpaceEventType, handler: JsCode | str) -> None

Register a screen space event handler.

on_click

on_click(callback: Callable[[str | None], None]) -> None

Register a Python callback for left-click events on entities.

The callback receives the public Cesium entity ID, or None when the click did not hit an entity. The bridge works when registered before or after :meth:show starts.

wait_for_click

wait_for_click(timeout: float | None = 30.0) -> str | None

Wait for the next left click and return its entity ID, if any.

Raises :class:TimeoutError if no click arrives within timeout. Pass None to wait indefinitely.

add_script

add_script(js_code: str) -> None

Add custom JavaScript code to be executed after viewer setup.

fly_to

fly_to(destination: Any, **kwargs: Any) -> None

Fly the camera to a destination.

set_view

set_view(destination: Any, orientation: Any = None) -> None

Set the camera view immediately.

look_at

look_at(target: Any, offset: Any) -> None

Point the camera at a target.

fly_to_entities

fly_to_entities(duration: float = 3.0) -> None

Fly the camera to fit the extent of all entities.

fly_to_bounding_sphere

fly_to_bounding_sphere(
    bounding_sphere: Any, duration: float = 3.0, **kwargs: Any
) -> None

Fly the camera to a bounding sphere.

to_widget

to_widget(*, height: str = '600px', cesium_version: str | None = None) -> Any

Return a Jupyter widget for this viewer (requires [widget] extras).

set_time

set_time(iso_string: str) -> None

Jump the timeline to a specific ISO 8601 epoch and update the widget.

Example: viewer.set_time("2024-03-15T03:00:00Z")

animate

animate(on: bool = True) -> None

Start or stop clock playback.

Example: viewer.animate(on=False) to pause.

set_multiplier

set_multiplier(multiplier: float) -> None

Change the clock playback speed.

Example: viewer.set_multiplier(3600) for 1 hour per second.

get_current_time

get_current_time(*, timeout: float = 10.0) -> str

Return the live viewer clock as an ISO 8601 string.

screenshot_base64

screenshot_base64(*, timeout: float = 10.0) -> str

Return a PNG screenshot of the live viewer as base64 text.

screenshot

screenshot(path: str | PathLike[str], *, timeout: float = 10.0) -> None

Save a PNG screenshot of the live viewer.

canvas_to_image

canvas_to_image(*, timeout: float = 10.0) -> Image

Return a screenshot as a detached Pillow image.

Install the optional images extra to use this method.

select_entity

select_entity(entity_id: str) -> None

Select a viewer entity by ID.

deselect

deselect() -> None

Clear the live viewer selection.

pick

pick(position: Cartesian2, *, timeout: float = 10.0) -> Entity | None

Return the local entity at a screen position.

drill_pick

drill_pick(position: Cartesian2, *, timeout: float = 10.0) -> list[Entity]

Return all local entities at a screen position.

update_czml

update_czml(source: str | list[dict[str, Any]]) -> None

Replace the first live CZML data source from a URL or CZML packets.

update_geojson

update_geojson(source: str | dict[str, Any]) -> None

Replace the first live GeoJSON data source from a URL or mapping.

poll_czml

poll_czml(url: str, *, interval: float = 5.0) -> str

Refresh CZML from url in the browser at a fixed interval.

Returns an identifier that can be passed to :meth:stop_polling.

stop_polling

stop_polling(poller_id: str) -> None

Stop a browser-side data-source poller.

stream_czml

stream_czml(
    packets: Iterable[list[dict[str, Any]]], *, interval: float = 1.0
) -> Thread

Consume CZML packet batches in a daemon thread and queue live updates.

to_html

to_html() -> str

Render the complete standalone HTML document string.

save

save(path: str) -> None

Save to an HTML file.

__enter__

__enter__() -> Viewer

Return this viewer and close its runtime resources on exit.

close

close() -> None

Stop the local server and release all viewer-owned resources.

This method is idempotent. Closing a viewer is terminal: create a new viewer to start another local runtime after resources have been freed.

show

show(port: int = 0, open_browser: bool = True) -> None

Launch a local HTTP server and open the visualization in a browser.

Cesium requires HTTP (not file://) due to web worker CORS restrictions. The server runs until interrupted. Call show() from a background thread when other Python code needs to control the live viewer.

Parameters:

Name Type Description Default
port int

Port to serve on. 0 = auto-pick a free port.

0
open_browser bool

Whether to automatically open the browser.

True

show_in_browser

show_in_browser() -> None

Alias for show(). Opens visualization via local HTTP server.

to_czml

to_czml() -> list[dict]

Export all entities as CZML JSON.

to_czml_string

to_czml_string(indent: int = 2) -> str

Export CZML as formatted JSON string.

save_czml

save_czml(path: str) -> None

Save CZML to a .czml file.

Shadows and 3D-only mode

shadows and terrain_shadows take a ShadowMode (DISABLED, ENABLED, CAST_ONLY, RECEIVE_ONLY) and control which objects cast and receive shadows. scene3d_only=True builds a scene that only ever renders in 3D (no 2D/Columbus morphing widgets, marginally faster startup):

viewer = cesiumkit.Viewer(
    shadows=cesiumkit.ShadowMode.ENABLED,
    terrain_shadows=cesiumkit.ShadowMode.RECEIVE_ONLY,
    scene3d_only=False,
)

Runtime clock control

When a viewer is being served with show(), Python can update and read its live Cesium clock:

viewer.set_time("2024-03-15T03:00:00Z")
viewer.animate(on=True)
viewer.set_multiplier(60)
current_time = viewer.get_current_time()

show() blocks while serving. Run it in a background thread when the same Python process needs to issue runtime commands.

Live data sources

CZML and GeoJSON sources can be replaced without rebuilding the viewer. Values may be URLs or in-memory JSON-compatible data:

viewer.update_czml([{"id": "document", "version": "1.0"}, packet])
viewer.update_geojson({"type": "FeatureCollection", "features": []})

poller = viewer.poll_czml("https://example.com/live.czml", interval=5)
viewer.stop_polling(poller)

For Python-produced updates, stream_czml() consumes an iterable of CZML packet batches in a daemon thread.

Runtime selection and picking

Selection commands operate on entities already added to the viewer. Picking returns the corresponding local Python Entity when its ID is known:

viewer.select_entity("sat-1")
selected = viewer.selected_entity
picked = viewer.pick(cesiumkit.Cartesian2(x=100, y=200))
all_picked = viewer.drill_pick(cesiumkit.Cartesian2(x=100, y=200))
viewer.deselect()

Python click events

Register callbacks before or after show() starts, or synchronously wait for the next click. A click on an entity returns its public ID; a click on empty space returns None:

viewer.on_click(lambda entity_id: print("clicked", entity_id))

# Run viewer.show() in another thread, then:
entity_id = viewer.wait_for_click(timeout=30)

wait_for_click() raises TimeoutError when no click arrives before the timeout. Callback exceptions are logged and do not prevent other callbacks from running.

Screenshots

Capture the live canvas as a file, base64 text, or a Pillow image:

viewer.screenshot("output.png")
encoded = viewer.screenshot_base64()
image = viewer.canvas_to_image()  # pip install cesiumkit[images]