Skip to main content

AdvancedCogViewer

Struct AdvancedCogViewer 

Source
pub struct AdvancedCogViewer { /* private fields */ }
Expand description

Advanced COG viewer with comprehensive tile management and caching

This is the recommended viewer for production applications. It provides advanced features including:

  • LRU Tile Caching: Automatic memory management with configurable size
  • Viewport Management: Pan, zoom, and viewport history (undo/redo)
  • Prefetching: Intelligent prefetching of nearby tiles
  • Multi-resolution: Automatic selection of appropriate overview level
  • Image Processing: Built-in contrast enhancement and statistics
  • Performance Tracking: Cache hit rates and loading metrics

§Memory Management

The viewer uses an LRU (Least Recently Used) cache to manage memory efficiently. When the cache is full, the least recently accessed tiles are evicted. Configure the cache size based on your application’s memory constraints and typical usage patterns.

Recommended cache sizes:

  • Mobile devices: 50-100 MB
  • Desktop browsers: 100-500 MB
  • High-end workstations: 500-1000 MB

§Prefetching Strategies

The viewer supports multiple prefetching strategies:

  • None: No prefetching (lowest memory, highest latency)
  • Neighbors: Prefetch immediately adjacent tiles
  • Pyramid: Prefetch parent and child tiles (smooth zooming)

§Performance Optimization

For best performance:

  1. Use an appropriate cache size (100-200 MB recommended)
  2. Enable prefetching for smoother user experience
  3. Use viewport management to minimize unnecessary tile loads
  4. Monitor cache statistics to tune parameters

§Example

const viewer = new AdvancedCogViewer();
await viewer.open('<https://example.com/image.tif>', 100); // 100MB cache

// Setup viewport
viewer.setViewportSize(800, 600);
viewer.fitToImage();

// Enable prefetching
viewer.setPrefetchStrategy('neighbors');

// Load and display tiles
const imageData = await viewer.readTileAsImageData(0, 0, 0);
ctx.putImageData(imageData, 0, 0);

// Check performance
const stats = JSON.parse(viewer.getCacheStats());
console.log(`Hit rate: ${stats.hit_count / (stats.hit_count + stats.miss_count)}`);

Implementations§

Source§

impl AdvancedCogViewer

Source

pub fn new() -> Self

Creates a new advanced COG viewer

Source

pub async fn open( &mut self, url: &str, cache_size_mb: usize, ) -> Result<(), JsValue>

Opens a COG file from a URL with advanced caching enabled

This method initializes the viewer with full caching and viewport management. It performs the following operations:

  1. Initial Connection: Sends HEAD request to validate URL and check range support
  2. Header Parsing: Fetches and parses TIFF header (8-16 bytes)
  3. Metadata Extraction: Parses IFD to extract image dimensions, tile size, bands
  4. GeoTIFF Tags: Extracts coordinate system information (EPSG, geotransform)
  5. Pyramid Creation: Builds tile pyramid structure for all overview levels
  6. Cache Initialization: Creates LRU cache with specified size
  7. Viewport Setup: Initializes viewport with default settings
§Arguments
  • url - The URL of the COG file. Must support HTTP range requests (Accept-Ranges: bytes) and have proper CORS headers configured.
  • cache_size_mb - Size of the tile cache in megabytes. Recommended values:
    • Mobile: 50-100 MB
    • Desktop: 100-500 MB
    • High-end: 500-1000 MB
§Returns

Returns Ok(()) on successful initialization, or a JavaScript error on failure.

§Errors

This method can fail for several reasons:

§Network Errors
  • Connection timeout
  • DNS resolution failure
  • SSL/TLS errors
§HTTP Errors
  • 404 Not Found: File doesn’t exist at the URL
  • 403 Forbidden: Access denied
  • 500 Server Error: Server-side issues
§CORS Errors
  • Missing Access-Control-Allow-Origin header
  • Missing Access-Control-Allow-Headers for range requests
§Format Errors
  • Invalid TIFF magic bytes
  • Corrupted IFD structure
  • Unsupported TIFF variant
  • Missing required tags
§Performance Considerations

Opening a COG typically requires 2-4 HTTP requests:

  1. HEAD request (~10ms)
  2. Header fetch (~20ms for 16 bytes)
  3. IFD fetch (~50ms for typical IFD)
  4. GeoTIFF tags fetch (~30ms if separate)

Total typical open time: 100-200ms on good connections.

§Example
const viewer = new AdvancedCogViewer();

try {
    // Open with 100MB cache
    await viewer.open('<https://example.com/landsat8.tif>', 100);

    console.log(`Opened: ${viewer.width()}x${viewer.height()}`);
    console.log(`Tiles: ${viewer.tile_width()}x${viewer.tile_height()}`);
    console.log(`Cache size: 100 MB`);
} catch (error) {
    if (error.message.includes('404')) {
        console.error('File not found');
    } else if (error.message.includes('CORS')) {
        console.error('CORS not configured. Add these headers:');
        console.error('  Access-Control-Allow-Origin: *');
        console.error('  Access-Control-Allow-Headers: Range');
    } else {
        console.error('Failed to open:', error.message);
    }
}
§See Also
  • WasmCogViewer::open() - Simple version without caching
  • set_prefetch_strategy() - Configure prefetching after opening
  • get_cache_stats() - Monitor cache performance
Source

pub fn width(&self) -> u64

Returns the image width

Source

pub fn height(&self) -> u64

Returns the image height

Source

pub fn tile_width(&self) -> u32

Returns the tile width

Source

pub fn tile_height(&self) -> u32

Returns the tile height

Source

pub fn band_count(&self) -> u32

Returns the number of bands

Source

pub fn overview_count(&self) -> usize

Returns the number of overview levels

Source

pub fn epsg_code(&self) -> Option<u32>

Returns the EPSG code if available

Source

pub fn url(&self) -> Option<String>

Returns the URL

Source

pub fn set_viewport_size(&mut self, width: u32, height: u32)

Sets the viewport size

Source

pub fn pan(&mut self, dx: f64, dy: f64)

Pans the viewport

Source

pub fn zoom_in(&mut self)

Zooms in

Source

pub fn zoom_out(&mut self)

Zooms out

Source

pub fn set_zoom(&mut self, zoom: u32)

Sets the zoom level

Source

pub fn center_on(&mut self, x: f64, y: f64)

Centers the viewport on a point

Source

pub fn fit_to_image(&mut self)

Fits the viewport to the image

Source

pub fn get_viewport(&self) -> Option<String>

Returns the current viewport as JSON

Source

pub fn get_cache_stats(&self) -> Option<String>

Returns cache statistics as JSON

Source

pub fn clear_cache(&mut self)

Clears the tile cache

Source

pub fn set_prefetch_strategy(&mut self, strategy: &str)

Sets the prefetch strategy

Source

pub fn get_metadata(&self) -> String

Returns comprehensive metadata as JSON

Source

pub async fn compute_stats( &self, level: usize, tile_x: u32, tile_y: u32, ) -> Result<String, JsValue>

Computes image statistics for a region

Source

pub async fn compute_histogram( &self, level: usize, tile_x: u32, tile_y: u32, ) -> Result<String, JsValue>

Computes histogram for a region (tile)

Returns a comprehensive JSON object containing:

  • Image dimensions (width, height, total_pixels)
  • Per-channel histograms (red, green, blue, luminance)
  • Statistics for each channel (min, max, mean, median, std_dev, count)
  • Histogram bins (256 bins for 8-bit values)
§Arguments
  • level - Overview/pyramid level (0 = full resolution)
  • tile_x - Tile X coordinate
  • tile_y - Tile Y coordinate
§Example
const viewer = new AdvancedCogViewer();
await viewer.open('<https://example.com/image.tif>', 100);

// Get histogram for tile at (0, 0) at full resolution
const histogramJson = await viewer.computeHistogram(0, 0, 0);
const histogram = JSON.parse(histogramJson);

console.log(`Luminance mean: ${histogram.luminance.mean}`);
console.log(`Luminance std_dev: ${histogram.luminance.std_dev}`);
console.log(`Red min/max: ${histogram.red.min} - ${histogram.red.max}`);
Source

pub async fn read_tile_cached( &mut self, level: usize, tile_x: u32, tile_y: u32, ) -> Result<Vec<u8>, JsValue>

Reads a tile with caching

Source

pub async fn read_tile_as_image_data( &mut self, level: usize, tile_x: u32, tile_y: u32, ) -> Result<ImageData, JsValue>

Reads a tile as ImageData with caching

Source

pub async fn read_tile_with_contrast( &mut self, level: usize, tile_x: u32, tile_y: u32, method: &str, ) -> Result<ImageData, JsValue>

Applies contrast enhancement to a tile

Trait Implementations§

Source§

impl Default for AdvancedCogViewer

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<AdvancedCogViewer> for JsValue

Source§

fn from(value: AdvancedCogViewer) -> Self

Converts to this type from the input type.
Source§

impl FromWasmAbi for AdvancedCogViewer

Source§

type Abi = u32

The Wasm ABI type that this converts from when coming back out from the ABI boundary.
Source§

unsafe fn from_abi(js: u32) -> Self

Recover a Self from Self::Abi. Read more
Source§

impl IntoWasmAbi for AdvancedCogViewer

Source§

type Abi = u32

The Wasm ABI type that this converts into when crossing the ABI boundary.
Source§

fn into_abi(self) -> u32

Convert self into Self::Abi so that it can be sent across the wasm ABI boundary.
Source§

impl LongRefFromWasmAbi for AdvancedCogViewer

Source§

type Abi = u32

Same as RefFromWasmAbi::Abi
Source§

type Anchor = RcRef<AdvancedCogViewer>

Same as RefFromWasmAbi::Anchor
Source§

unsafe fn long_ref_from_abi(js: Self::Abi) -> Self::Anchor

Same as RefFromWasmAbi::ref_from_abi
Source§

impl OptionFromWasmAbi for AdvancedCogViewer

Source§

fn is_none(abi: &Self::Abi) -> bool

Tests whether the argument is a “none” instance. If so it will be deserialized as None, and otherwise it will be passed to FromWasmAbi.
Source§

impl OptionIntoWasmAbi for AdvancedCogViewer

Source§

fn none() -> Self::Abi

Returns an ABI instance indicating “none”, which JS will interpret as the None branch of this option. Read more
Source§

impl RefFromWasmAbi for AdvancedCogViewer

Source§

type Abi = u32

The Wasm ABI type references to Self are recovered from.
Source§

type Anchor = RcRef<AdvancedCogViewer>

The type that holds the reference to Self for the duration of the invocation of the function that has an &Self parameter. This is required to ensure that the lifetimes don’t persist beyond one function call, and so that they remain anonymous.
Source§

unsafe fn ref_from_abi(js: Self::Abi) -> Self::Anchor

Recover a Self::Anchor from Self::Abi. Read more
Source§

impl RefMutFromWasmAbi for AdvancedCogViewer

Source§

type Abi = u32

Same as RefFromWasmAbi::Abi
Source§

type Anchor = RcRefMut<AdvancedCogViewer>

Same as RefFromWasmAbi::Anchor
Source§

unsafe fn ref_mut_from_abi(js: Self::Abi) -> Self::Anchor

Same as RefFromWasmAbi::ref_from_abi
Source§

impl TryFromJsValue for AdvancedCogViewer

Source§

fn try_from_js_value(value: JsValue) -> Result<Self, JsValue>

Performs the conversion.
Source§

fn try_from_js_value_ref(value: &JsValue) -> Option<Self>

Performs the conversion.
Source§

impl VectorFromWasmAbi for AdvancedCogViewer

Source§

impl VectorIntoWasmAbi for AdvancedCogViewer

Source§

impl WasmDescribe for AdvancedCogViewer

Source§

impl WasmDescribeVector for AdvancedCogViewer

Source§

impl SupportsConstructor for AdvancedCogViewer

Source§

impl SupportsInstanceProperty for AdvancedCogViewer

Source§

impl SupportsStaticProperty for AdvancedCogViewer

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ReturnWasmAbi for T
where T: IntoWasmAbi,

Source§

type Abi = <T as IntoWasmAbi>::Abi

Same as IntoWasmAbi::Abi
Source§

fn return_abi(self) -> <T as ReturnWasmAbi>::Abi

Same as IntoWasmAbi::into_abi, except that it may throw and never return in the case of Err.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more