Skip to main content

Add a raster layer

The base interface for raster layers, displaying pixel data (imagery, scanned maps, etc.) as a part of a terrain.

A raster layer displays pixel data (imagery, scanned maps, shaded relief, etc.) as a part of its terrain; it is also the base of the code-map layers (see IMcCodeMapLayer), whose pixels code data rather than colors. It is inherited by IMcNativeRasterMapLayer (data converted to MapCore's format, in a directory or behind a URL), IMcRawRasterMapLayer (unconverted source files), IMcNativeServerRasterMapLayer (MapCore's Map Layer Server) and IMcWebServiceRasterMapLayer (OGC WMS, WMTS and WCS servers); the variants differ in how they are created and in the source-specific members they add, while the pixels are displayed the same way whatever their source.

Used for:

  • Color statistics: CalcHistogram() (per color channel, from a coarse level of detail).
  • Tile access: GetTileBitmapByKey() (a tile's pixels, decompressed or as stored); for a layer already in a terrain, the cache-based IMcSpatialQueries::GetRasterLayerTileBitmapByKey() and IMcSpatialQueries::GetRasterLayerColorByPoint() are preferable.
  • Everything a map layer does, as IMcMapLayer: visibility, coordinate system and bounding box, ID and user data, tiles and levels of detail, saving and loading, type and casting.

The per-terrain display parameters of a raster layer - scale range, draw priority, transparency and magnification filter - are set by IMcMapTerrain::SetLayerParams() (see IMcMapTerrain::SLayerParams).

See also: IMcMapLayer, IMcDtmMapLayer, IMcCodeMapLayer

— from Map/IMcRasterMapLayer.h

Imagery, scanned maps, shaded relief — anything that arrives as pixels rather than as features. This page covers getting one on screen; Layers and terrain covers how layers and terrains fit together.

Choose the interface​

All four derive from IMcRasterMapLayer and differ in where the pixels come from. The choice determines which Create() you call and which source-specific members you get; the pixels themselves are displayed the same way whatever produced them.

InterfaceReads fromCreate() takes
IMcNativeRasterMapLayerData converted to MapCore's format, in a directory or behind a URLa directory or URL
IMcRawRasterMapLayerYour source files, unconverted, read where they sitSRawParams
IMcNativeServerRasterMapLayerMapCore's Map Layer Servera layer URL
IMcWebServiceRasterMapLayerA WMS, WMTS or WCS serviceSWMSParams, SWMTSParams or SWCSParams

If you are unsure between the first two, Layers and terrain has the trade-off: raw costs nothing to set up, converted costs an offline pass and is faster to display.

Create the layer​

Every Create() returns the layer with a zero reference count. If you keep it, AddRef() it; if you are passing it straight to terrain creation, pass it as is and let the terrain own it. The rules are in Threading and lifecycle.

A layer also needs a map device to exist first — a layer lives in the device's terrain resources, and creating one without a device returns IMcErrors::NOT_INITIALIZED.

Converted data​

IMcNativeRasterMapLayer *pLayer = NULL;
IMcErrors::ECode eCode = IMcNativeRasterMapLayer::Create(&pLayer, "C:/maps/orthophoto");

The remaining parameters are all optional:

ParameterEffectDefault
uFirstLowerQualityLevelFirst level of detail (zero-based) that may load at 256×256 instead of 512×512UINT_MAX — never
bThereAreMissingFilesTells the layer some of its files are absent, rather than treating that as an errorfalse
uNumLevelsToIgnoreDrops that many of the finest levels of detail0
bEnhanceBorderOverlapSuppresses black border lines where layers overlap, at a performance costfalse
pReadCallbackReceives initialisation and read eventsNULL
pLocalCacheLayerParamsCaches tiles on disk — see Tune the local cacheNULL

On a memory-constrained machine, uFirstLowerQualityLevel = 1 is the recommended setting: the finest level keeps its original quality and everything coarser loads at half resolution.

GetCreateParams() reads these four values back off an existing layer.

A directory or a URL. The same call accepts either, and the difference is not cosmetic: given a directory the layer is initialised by the time Create() returns, and given a URL it is not. See Wait for initialisation below.

Raw data​

Raw layers are described by SRawParams, which carries a base directory plus an array of SComponentParams — each a file or a directory (ECT_FILE / ECT_DIRECTORY) named relative to that base, optionally with its own world limit. Fill a component's WorldLimit with DBL_MAX values to take the extent from the files themselves.

The fields worth knowing before your first raw layer:

FieldWhat it is for
pCoordinateSystemRequired unless every component carries its own, or the layer is an anchored image
fMaxScaleThe layer's typical maximum scale; sources without levels of detail perform best at or below it
bIgnoreRasterPaletteIgnores a palette and shows the data as grayscale
bResolveOverlapConflictsWith overlapping sources, uses the last non-empty value rather than simply the last
TransparentColor, byTransparentColorPrecisionTreats one colour — optionally ±a tolerance per channel — as transparent
bAddLevelsOfDetailIfAbsentBuilds missing levels of detail as GDAL .ovr files, reporting progress through pLodProgressCallback
uMaxNumOpenFilesCaps simultaneously open files; 0 means MapCore's default of 5000 on Windows, 500 elsewhere

A resolutions pyramid is the alternative to per-file levels of detail: list the same components several times at decreasing resolution, then set auPyramidResolutions to the index at which each resolution starts and fFirstPyramidResolution to the finest. Each resolution must be twice coarser than the one before, and the indices must increase starting from 0.

A dynamic layer is created empty and grows: set MaxWorldLimit and fHighestResolution to real values instead of leaving them at their defaults, pass no components, and add them later with AddComponents(). Tiles touched by the new components are dropped from the terrain caches and redrawn. This is the one case where an empty component list is not an error — and it does not combine with a resolutions pyramid.

For an image with no geography at all — a floor plan, a scanned sheet — pass bImageCoordinateSystem = true. That is the anchored-image case described in Coordinate systems.

From a Map Layer Server​

IMcNativeServerRasterMapLayer *pLayer = NULL;
IMcErrors::ECode eCode = IMcNativeServerRasterMapLayer::Create(
&pLayer, "http://server:8080/maps/orthophoto", &ReadCallback);

The URL must contain a /. Loading is always deferred here — Create() returns as soon as the requests are issued — so a read callback is effectively mandatory. If the server does not recognise the layer, initialisation fails with IMcErrors::NATIVE_SERVER_LAYER_NOT_VALID.

From an OGC service​

IMcWebServiceRasterMapLayer::Create() is overloaded three ways, one per service, distinguished by the parameter struct. All three share SWebMapServiceParams:

FieldNotes
strServerURLRequired. For WMTS it may or may not already carry the capabilities request; MapCore appends ?service=WMTS&request=GetCapabilities if it does not. For WMS and WCS it should not carry one
strLayersListRequired. One or more layers, comma-separated and URL-encoded
strServerCoordinateSystemFor WMS and WCS, the CRS in server form (EPSG:4326, CRS:84) matching the layer's own; for WMTS, the ID of one of the layer's tile matrix sets. Required for WMS and WMTS
strImageFormatRequired for WMS and WMTS — png, jpeg, tiff
BoundingBoxRequired for WMS, optional for WMTS, unused for WCS
strOptionalUserAndPasswordHTTP authentication as user:password
bSkipSSLCertificateVerificationFor self-signed certificates
aRequestParamsExtra key=value pairs appended to every request
uTimeoutInSecDefault 300
strZeroBlockHttpCodesResponse codes to render as a zero-filled tile instead of failing the request. Default 204,404
bZeroBlockOnServerExceptionSame treatment for a Service Exception. Default true

Then per service: SWMSParams adds strWMSVersion (default 1.3.0), the request block size (uBlockWidth/uBlockHeight, default 256) and fMinScale. SWMTSParams adds strInfoFormat for GetFeatureInfo, bExtendBeyondDateLine, bUseServerTilingScheme, and eCapabilitiesBoundingBoxAxesOrder for servers whose capabilities report axes in an unexpected order. SWCSParams adds strWCSVersion (default 1.0.0) and bDontUseServerInterpolation.

Reading the parameters back is service-specific: GetWebMapServiceType() says which service the layer uses, and GetWMSParams(), GetWMTSParams() and GetWCSParams() each fail with IMcErrors::INVALID_PARAMETERS if asked about the wrong one. They return shallow copies — the strings and pointers inside belong to the layer.

You do not have to know the layer name up front. IMcMapDevice::GetWebServerLayers() asks a server what it offers and reports back asynchronously, with each layer's title, formats, styles, bounding box and tile matrix sets, so you can present a real list.

Add it to a terrain​

A raster layer is not visible until a terrain holds it and a viewport shows that terrain. Pass it to IMcMapTerrain::Create() along with any other layers, or AddLayer() it to a terrain that already exists. Per-terrain display parameters — scale range, draw priority, transparency, magnification filter — are set with IMcMapTerrain::SetLayerParams() and are described in Layers and terrain.

Wait for initialisation​

IsInitialized() reports whether the layer's data has arrived; an IReadCallback tells you when it does. OnInitialized() fires exactly once — with the layer on success, or with NULL and an error code on failure, in which case the failed layer has already been destroyed.

The timing depends on the source, and this is the detail most likely to catch you out. Two cases the headers state outright:

SourceState when Create() returns
Converted data in a directoryAlready initialised. Coordinate system and bounding box readable immediately; only tiles arrive later
Converted data behind a URLNot initialised. No coordinate system, no bounding box until OnInitialized()
Map Layer ServerNot initialised. Create() returns once the requests are issued

For raw and web-service layers, do not assume either way. Both can report failure synchronously — a web-service Create() returns IMcErrors::FILE_NOT_FOUND or IMcErrors::CANT_READ_FILE if the capabilities could not be fetched or parsed, so that work is not purely deferred — and a raw layer, too, can be returned not yet initialised, which is why CalcHistogram() documents IMcErrors::NOT_INITIALIZED for raw layers that are not yet initialised.

The rule that covers every case without guessing: OnInitialized() fires exactly once whatever the source, and IsInitialized() answers the question at any moment. Use them rather than inferring the state from the kind of layer you created.

Anything derived from the layer's own metadata has to wait accordingly: a terrain created with a NULL coordinate system has nothing to adopt yet, and you cannot frame a camera on a bounding box that is not known. On the web, where a URL is the only kind of source, this is unavoidable.

Two more callbacks matter for a network-backed layer. OnReadError() reports a failure after initialisation, naming the file or request that failed. OnNativeServerLayerNotValid() fires when the Map Layer Server's copy of the layer changes underneath you, and its bLayerVersionUpdated argument tells you which repair to make: true means the version moved on, so call ReplaceNativeServerLayerAsync(); false means the layer is gone, so call RemoveLayerAsync().

Adjust what is displayed​

Colour channels. On a raw layer, SetColorChannels() remaps which band feeds red, green and blue — useful for multispectral imagery where the natural-colour bands are not the first three. UINT_MAX keeps a channel's original index and UINT_MAX - 1 drops the channel. GetColorChannels() reads the current mapping.

Histograms. CalcHistogram() fills three 256-entry, 64-bit histograms — red, green, blue. It is computed from one sampled coarse level rather than the full-resolution data; native layers exclude tile margins and fully transparent pixels, raw layers use the raster source's own band histograms with a gray band counted into all three channels. It is not available on a layer that streams tiles straight from a server.

Individual tiles. GetTileBitmapByKey() returns one tile's pixels by SLayerTileKey, optionally still compressed. It loads the tile every time it is called, bypassing the terrain cache — so if the layer is in a terrain, prefer IMcSpatialQueries::GetRasterLayerTileBitmapByKey(), or IMcSpatialQueries::GetRasterLayerColorByPoint() when you only want one pixel.

Components and resolutions. On a raw layer, GetComponents() lists the components (a pyramid layer reports the original list, duplicates included) and GetResolutions() reports the pyramid.

Error codes​

The codes you are most likely to meet, and what each one usually means:

CodeCause
IMcErrors::NOT_INITIALIZEDNo map device yet — or, from a getter, the layer's loading has not finished
IMcErrors::INVALID_PARAMETERSA required pointer is NULL, a directory is empty, or it holds a layer of a different type
IMcErrors::FILE_NOT_FOUNDA layer file is missing or unreadable, no raw component could be opened, or uNumLevelsToIgnore is not less than the number of levels
IMcErrors::READ_FROM_STORAGE_FAILEDThe tile data could not be read
IMcErrors::COORDINATE_SYSTEMS_MISMATCHRaw components disagree about their coordinate system
IMcErrors::MAPLAYER_FILE_WITHOUT_COORDINATE_SYSTEMA component carries no coordinate system, none was supplied, and it is not an anchored image
IMcErrors::CANT_READ_FILEThe raster source, or a service's capabilities, could not be processed
IMcErrors::LAYER_WEB_REQUEST_FAILUREA required web request could not be issued
IMcErrors::NATIVE_SERVER_LAYER_NOT_VALIDThe Map Layer Server does not recognise the layer
IMcErrors::NOT_IMPLEMENTEDThis build has no HTTP support, or the tile is in a format that cannot be decoded
IMcErrors::NOT_SUPPORTED_FOR_THIS_LAYERCalcHistogram() on a server-streamed layer

Local-cache failures — IMcErrors::LOCAL_CACHE_NOT_INIT, IMcErrors::LAYER_ALREADY_EXISTS, IMcErrors::LOCAL_CACHE_CANT_CREATE_DIR, IMcErrors::LOCAL_CACHE_CANT_BE_TRIMMED — are covered in Tune the local cache.

Verified against MapCore 12.5.0

Written from Map/IMcRasterMapLayer.h, Map/IMcMapLayer.h, Map/IMcMapTerrain.h, Map/IMcMapDevice.h, Calculations/IMcSpatialQueries.h