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:
- Use an appropriate cache size (100-200 MB recommended)
- Enable prefetching for smoother user experience
- Use viewport management to minimize unnecessary tile loads
- 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
impl AdvancedCogViewer
Sourcepub async fn open(
&mut self,
url: &str,
cache_size_mb: usize,
) -> Result<(), JsValue>
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:
- Initial Connection: Sends HEAD request to validate URL and check range support
- Header Parsing: Fetches and parses TIFF header (8-16 bytes)
- Metadata Extraction: Parses IFD to extract image dimensions, tile size, bands
- GeoTIFF Tags: Extracts coordinate system information (EPSG, geotransform)
- Pyramid Creation: Builds tile pyramid structure for all overview levels
- Cache Initialization: Creates LRU cache with specified size
- 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:
- HEAD request (~10ms)
- Header fetch (~20ms for 16 bytes)
- IFD fetch (~50ms for typical IFD)
- 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 cachingset_prefetch_strategy()- Configure prefetching after openingget_cache_stats()- Monitor cache performance
Sourcepub fn tile_width(&self) -> u32
pub fn tile_width(&self) -> u32
Returns the tile width
Sourcepub fn tile_height(&self) -> u32
pub fn tile_height(&self) -> u32
Returns the tile height
Sourcepub fn band_count(&self) -> u32
pub fn band_count(&self) -> u32
Returns the number of bands
Sourcepub fn overview_count(&self) -> usize
pub fn overview_count(&self) -> usize
Returns the number of overview levels
Sourcepub fn set_viewport_size(&mut self, width: u32, height: u32)
pub fn set_viewport_size(&mut self, width: u32, height: u32)
Sets the viewport size
Sourcepub fn fit_to_image(&mut self)
pub fn fit_to_image(&mut self)
Fits the viewport to the image
Sourcepub fn get_viewport(&self) -> Option<String>
pub fn get_viewport(&self) -> Option<String>
Returns the current viewport as JSON
Sourcepub fn get_cache_stats(&self) -> Option<String>
pub fn get_cache_stats(&self) -> Option<String>
Returns cache statistics as JSON
Sourcepub fn clear_cache(&mut self)
pub fn clear_cache(&mut self)
Clears the tile cache
Sourcepub fn set_prefetch_strategy(&mut self, strategy: &str)
pub fn set_prefetch_strategy(&mut self, strategy: &str)
Sets the prefetch strategy
Sourcepub fn get_metadata(&self) -> String
pub fn get_metadata(&self) -> String
Returns comprehensive metadata as JSON
Sourcepub async fn compute_stats(
&self,
level: usize,
tile_x: u32,
tile_y: u32,
) -> Result<String, JsValue>
pub async fn compute_stats( &self, level: usize, tile_x: u32, tile_y: u32, ) -> Result<String, JsValue>
Computes image statistics for a region
Sourcepub async fn compute_histogram(
&self,
level: usize,
tile_x: u32,
tile_y: u32,
) -> Result<String, JsValue>
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 coordinatetile_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}`);Sourcepub async fn read_tile_cached(
&mut self,
level: usize,
tile_x: u32,
tile_y: u32,
) -> Result<Vec<u8>, JsValue>
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
Trait Implementations§
Source§impl Default for AdvancedCogViewer
impl Default for AdvancedCogViewer
Source§impl From<AdvancedCogViewer> for JsValue
impl From<AdvancedCogViewer> for JsValue
Source§fn from(value: AdvancedCogViewer) -> Self
fn from(value: AdvancedCogViewer) -> Self
Source§impl FromWasmAbi for AdvancedCogViewer
impl FromWasmAbi for AdvancedCogViewer
Source§impl IntoWasmAbi for AdvancedCogViewer
impl IntoWasmAbi for AdvancedCogViewer
Source§impl RefFromWasmAbi for AdvancedCogViewer
impl RefFromWasmAbi for AdvancedCogViewer
Source§type Anchor = RcRef<AdvancedCogViewer>
type Anchor = RcRef<AdvancedCogViewer>
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§impl TryFromJsValue for AdvancedCogViewer
impl TryFromJsValue for AdvancedCogViewer
Source§impl VectorFromWasmAbi for AdvancedCogViewer
impl VectorFromWasmAbi for AdvancedCogViewer
type Abi = <Box<[JsValue]> as FromWasmAbi>::Abi
unsafe fn vector_from_abi(js: Self::Abi) -> Box<[AdvancedCogViewer]>
Source§impl VectorIntoWasmAbi for AdvancedCogViewer
impl VectorIntoWasmAbi for AdvancedCogViewer
type Abi = <Box<[JsValue]> as IntoWasmAbi>::Abi
fn vector_into_abi(vector: Box<[AdvancedCogViewer]>) -> Self::Abi
Source§impl WasmDescribeVector for AdvancedCogViewer
impl WasmDescribeVector for AdvancedCogViewer
impl SupportsConstructor for AdvancedCogViewer
impl SupportsInstanceProperty for AdvancedCogViewer
impl SupportsStaticProperty for AdvancedCogViewer
Auto Trait Implementations§
impl Freeze for AdvancedCogViewer
impl RefUnwindSafe for AdvancedCogViewer
impl Send for AdvancedCogViewer
impl Sync for AdvancedCogViewer
impl Unpin for AdvancedCogViewer
impl UnsafeUnpin for AdvancedCogViewer
impl UnwindSafe for AdvancedCogViewer
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> ReturnWasmAbi for Twhere
T: IntoWasmAbi,
impl<T> ReturnWasmAbi for Twhere
T: IntoWasmAbi,
Source§type Abi = <T as IntoWasmAbi>::Abi
type Abi = <T as IntoWasmAbi>::Abi
IntoWasmAbi::AbiSource§fn return_abi(self) -> <T as ReturnWasmAbi>::Abi
fn return_abi(self) -> <T as ReturnWasmAbi>::Abi
IntoWasmAbi::into_abi, except that it may throw and never
return in the case of Err.