The LayerApi class provides comprehensive methods for managing map layers in GeoView. It handles layer creation, removal, configuration, visibility, and interaction with various layer types including WMS, ESRI services, GeoJSON, and more.
The Layer API is available through the MapViewer instance:
// Get the map viewer
const mapViewer = cgpv.api.getMapViewer("mapId");
// Access the layer API
const layerApi = mapViewer.layer;- Vector Layers: GeoJSON, WFS, OGC Feature, ESRI Feature, CSV, KML, WKB
- Raster Layers: WMS, ESRI Dynamic, ESRI Image, XYZ Tiles, Vector Tiles, Image Static
- Special: GeoCore, GeoPackage, Shapefile, RCS
Adds a layer to the map using a layer configuration object.
addGeoviewLayer(
geoviewLayerConfig: TypeGeoviewLayerConfig,
abortSignal?: AbortSignal
): GeoViewLayerAddedResultParameters:
geoviewLayerConfig- Layer configuration object (see Configuration Reference)abortSignal- Optional AbortSignal to cancel the layer addition
Returns: GeoViewLayerAddedResult object containing:
layerConfig- The configuration usedlayer- The created GeoView layer instance
Example:
const result = mapViewer.layer.addGeoviewLayer({
geoviewLayerId: "myLayer",
geoviewLayerName: "My WMS Layer",
geoviewLayerType: "ogcWms",
metadataAccessPath: "https://example.com/wms",
listOfLayerEntryConfig: [
{
layerId: "layer1",
layerName: "Layer 1",
},
],
});Adds a layer from the GeoCore catalog using its UUID.
async addGeoviewLayerByGeoCoreUUID(
uuid: string,
layerEntryConfig?: string
): Promise<GeoViewLayerAddedResult | void>Parameters:
uuid- The GeoCore layer UUIDlayerEntryConfig- Optional layer entry configuration path
Example:
await mapViewer.layer.addGeoviewLayerByGeoCoreUUID(
"12345678-1234-1234-1234-123456789012"
);Loads multiple layers from the map configuration.
async loadListOfGeoviewLayer(
mapConfigLayerEntries: MapConfigLayerEntry[]
): Promise<void>Parameters:
mapConfigLayerEntries- Array of map configuration layer entries
Removes a layer and all its children using its layer path.
removeLayerUsingPath(layerPath: string): voidParameters:
layerPath- The path of the layer to remove (e.g., 'layerId' or 'layerId/sublayerId')
Example:
mapViewer.layer.removeLayerUsingPath("myLayer");Removes all layers from the map.
removeAllGeoviewLayers(): voidRemoves all layers that have an error status.
removeAllLayersInError(): voidReloads a specific layer.
reloadLayer(layerPath: string): voidParameters:
layerPath- The path of the layer to reload
Example:
mapViewer.layer.reloadLayer("myLayer");Reloads all GeoCore layers on the map.
reloadGeocoreLayers(): voidRefreshes all layers on the map.
refreshLayers(): voidGets all GeoView layer IDs/UUIDs.
getGeoviewLayerIds(): string[]Returns: Array of layer IDs
Gets all GeoView layer paths.
getGeoviewLayerPaths(): string[]Returns: Array of layer paths
Gets all GeoView layer instances.
getGeoviewLayers(): AbstractBaseLayer[]Returns: Array of layer instances
Gets a specific GeoView layer by path (throws error if not found).
getGeoviewLayer(layerPath: string): AbstractBaseLayerParameters:
layerPath- The path of the layer to retrieve
Returns: The layer instance
Throws: LayerNotFoundError if layer doesn't exist
Gets a specific GeoView layer by path (returns undefined if not found).
getGeoviewLayerIfExists(layerPath: string): AbstractBaseLayer | undefinedParameters:
layerPath- The path of the layer to retrieve
Returns: The layer instance or undefined
Example:
const layer = mapViewer.layer.getGeoviewLayerIfExists("myLayer");
if (layer) {
console.log("Layer found:", layer);
}Gets the configuration for a specific layer entry (throws error if not found).
getLayerEntryConfig(layerPath: string): ConfigBaseClass | undefinedParameters:
layerPath- The path of the layer
Returns: The layer configuration object
Gets the configuration for a specific layer entry (returns undefined if not found).
getLayerEntryConfigIfExists(layerPath: string): ConfigBaseClass | undefinedParameters:
layerPath- The path of the layer
Returns: The layer configuration object or undefined
Gets all layer entry configurations.
getLayerEntryConfigs(): ConfigBaseClass[]Returns: Array of layer configuration objects
Gets all layer entry configuration IDs.
getLayerEntryConfigIds(): string[]Returns: Array of layer configuration IDs
Checks if a layer entry configuration is registered.
isLayerEntryConfigRegistered(layerPath: string): booleanParameters:
layerPath- The path of the layer to check
Returns: True if registered, false otherwise
Gets the OpenLayers layer instance (throws error if not found).
getOLLayer(layerPath: string): BaseLayerParameters:
layerPath- The path of the layer
Returns: The OpenLayers layer instance
Gets the OpenLayers layer instance (returns undefined if not found).
getOLLayerIfExists(layerPath: string): BaseLayer | undefinedParameters:
layerPath- The path of the layer
Returns: The OpenLayers layer instance or undefined
Gets the OpenLayers layer instance asynchronously (waits for layer to be created).
getOLLayerAsync(
layerPath: string,
timeout?: number,
checkFrequency?: number
): Promise<BaseLayer>Parameters:
layerPath- The path of the layertimeout- Maximum wait time in milliseconds (default: 10000)checkFrequency- Check interval in milliseconds (default: 100)
Returns: Promise resolving to the OpenLayers layer instance
Example:
const olLayer = await mapViewer.layer.getOLLayerAsync("myLayer", 5000);Sets or toggles the visibility of a layer.
setOrToggleLayerVisibility(
layerPath: string,
newValue?: boolean
): booleanParameters:
layerPath- The path of the layernewValue- Optional visibility value (true/false). If omitted, toggles current state
Returns: The new visibility state
Example:
// Toggle visibility
mapViewer.layer.setOrToggleLayerVisibility("myLayer");
// Set explicit visibility
mapViewer.layer.setOrToggleLayerVisibility("myLayer", true);Sets the visibility of all layers.
setAllLayersVisibility(newValue: boolean): voidParameters:
newValue- The visibility state to apply to all layers
Sets the visibility of a specific legend item within a layer.
setItemVisibility(
layerPath: string,
item: TypeLegendItem,
visibility: boolean,
updateLegendLayers?: boolean
): voidParameters:
layerPath- The path of the layeritem- The legend item to modifyvisibility- The visibility stateupdateLegendLayers- Whether to update legend layers (default: true)
Sets the opacity of a layer.
setLayerOpacity(
layerPath: string,
opacity: number,
emitOpacityChange?: boolean
): voidParameters:
layerPath- The path of the layeropacity- Opacity value (0-1)emitOpacityChange- Whether to emit opacity change event (default: true)
Example:
// Set layer to 50% opacity
mapViewer.layer.setLayerOpacity("myLayer", 0.5);Highlights a layer by reducing opacity of other layers.
highlightLayer(layerPath: string): voidParameters:
layerPath- The path of the layer to highlight
Example:
mapViewer.layer.highlightLayer("myLayer");Removes layer highlighting and restores original opacity.
removeHighlightLayer(): voidRemoves all highlights from a specific layer.
removeLayerHighlights(layerPath: string): voidParameters:
layerPath- The path of the layer
Sets the name of a layer.
setLayerName(layerPath: string, name: string): voidParameters:
layerPath- The path of the layername- The new layer name
Example:
mapViewer.layer.setLayerName("myLayer", "Updated Layer Name");Updates the GeoJSON source data for a GeoJSON layer.
setGeojsonSource(
layerPath: string,
geojson: GeoJSONObject | string
): voidParameters:
layerPath- The path of the GeoJSON layergeojson- GeoJSON object or string
Throws: LayerNotGeoJsonError if layer is not a GeoJSON layer
Example:
const geojson = {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [-75.6972, 45.4215],
},
properties: {
name: "Ottawa",
},
},
],
};
mapViewer.layer.setGeojsonSource("myGeoJsonLayer", geojson);Redefines feature field names or aliases.
redefineFeatureFields(
layerPath: string,
fieldNames: string[],
fields: 'alias' | 'name'
): voidParameters:
layerPath- The path of the layerfieldNames- Array of field names/aliasesfields- Whether to redefine 'alias' or 'name'
Throws: LayerDifferingFieldLengths if array lengths don't match
Example:
mapViewer.layer.redefineFeatureFields(
"myLayer",
["Population", "Area", "Density"],
"alias"
);Replaces the outfields configuration for a layer.
replaceFeatureOutfields(
layerPath: string,
types: TypeOutfieldsType[],
fieldNames: string[],
fieldAliases?: string[]
): voidParameters:
layerPath- The path of the layertypes- Array of field types (e.g., 'string', 'number', 'date')fieldNames- Array of field namesfieldAliases- Optional array of field aliases
Throws: LayerDifferingFieldLengths if array lengths don't match
Example:
mapViewer.layer.replaceFeatureOutfields(
"myLayer",
["string", "number", "number"],
["name", "population", "area"],
["Name", "Population", "Area (km²)"]
);Calculates the bounds/extent of a layer.
calculateBounds(layerPath: string): Extent | undefinedParameters:
layerPath- The path of the layer
Returns: The extent as [minX, minY, maxX, maxY] or undefined
Example:
const bounds = mapViewer.layer.calculateBounds("myLayer");
if (bounds) {
console.log("Layer bounds:", bounds);
// Zoom to layer bounds
mapViewer.map.getView().fit(bounds, { padding: [50, 50, 50, 50] });
}Recalculates bounds for all layers.
recalculateBoundsAll(): voidThe Layer API provides extensive event handling for layer lifecycle and interactions.
Registers a callback for when a layer configuration is added.
onLayerConfigAdded(callback: LayerBuilderDelegate): voidCallback Signature:
type LayerBuilderDelegate = (
sender: LayerApi,
event: LayerBuilderEvent
) => void;
interface LayerBuilderEvent {
layerConfig: ConfigBaseClass;
layer: AbstractGeoViewLayer;
}Example:
mapViewer.layer.onLayerConfigAdded((sender, event) => {
console.log("Layer config added:", event.layerConfig);
});Unregisters a layer configuration added callback.
offLayerConfigAdded(callback: LayerBuilderDelegate): voidRegisters a callback for when a layer configuration is removed.
onLayerConfigRemoved(callback: LayerPathDelegate): voidCallback Signature:
type LayerPathDelegate = (sender: LayerApi, event: LayerPathEvent) => void;
interface LayerPathEvent {
layerPath: string;
}Unregisters a layer configuration removed callback.
offLayerConfigRemoved(callback: LayerPathDelegate): voidRegisters a callback for when a layer configuration error occurs.
onLayerConfigError(callback: LayerConfigErrorDelegate): voidCallback Signature:
type LayerConfigErrorDelegate = (
sender: LayerApi,
event: LayerConfigErrorEvent
) => void;
interface LayerConfigErrorEvent {
layerPath: string;
error: Error;
}Unregisters a layer configuration error callback.
offLayerConfigError(callback: LayerConfigErrorDelegate): voidRegisters a callback for when a layer is created.
onLayerCreated(callback: LayerDelegate): voidCallback Signature:
type LayerDelegate = (sender: LayerApi, event: LayerEvent) => void;
interface LayerEvent {
layerPath: string;
layer: AbstractBaseLayer;
}Example:
mapViewer.layer.onLayerCreated((sender, event) => {
console.log("Layer created:", event.layerPath);
});Unregisters a layer created callback.
offLayerCreated(callback: LayerDelegate): voidRegisters a callback for when a layer loads for the first time.
onLayerFirstLoaded(callback: LayerDelegate): voidUnregisters a layer first loaded callback.
offLayerFirstLoaded(callback: LayerDelegate): voidRegisters a callback for when a layer starts loading.
onLayerLoading(callback: LayerDelegate): voidUnregisters a layer loading callback.
offLayerLoading(callback: LayerDelegate): voidRegisters a callback for when a layer finishes loading.
onLayerLoaded(callback: LayerDelegate): voidUnregisters a layer loaded callback.
offLayerLoaded(callback: LayerDelegate): voidRegisters a callback for when all configured layers have loaded.
onLayerAllLoaded(callback: LayerConfigDelegate): voidCallback Signature:
type LayerConfigDelegate = (sender: LayerApi, event: LayerConfigEvent) => void;
interface LayerConfigEvent {
layerConfigs: ConfigBaseClass[];
}Unregisters an all layers loaded callback.
offLayerAllLoaded(callback: LayerConfigDelegate): voidRegisters a callback for when a layer error occurs.
onLayerError(callback: LayerErrorDelegate): voidCallback Signature:
type LayerErrorDelegate = (sender: LayerApi, event: LayerErrorEvent) => void;
interface LayerErrorEvent {
layerPath: string;
error: Error;
}Example:
mapViewer.layer.onLayerError((sender, event) => {
console.error("Layer error:", event.layerPath, event.error);
});Unregisters a layer error callback.
offLayerError(callback: LayerErrorDelegate): voidRegisters a callback for when a layer's status changes.
onLayerStatusChanged(callback: LayerStatusChangedDelegate): voidCallback Signature:
type LayerStatusChangedDelegate = (
sender: LayerApi,
event: LayerStatusChangedEvent
) => void;
interface LayerStatusChangedEvent {
layerPath: string;
status: TypeLayerStatus; // 'registered', 'loading', 'loaded', 'error', etc.
}Example:
mapViewer.layer.onLayerStatusChanged((sender, event) => {
console.log(`Layer ${event.layerPath} status: ${event.status}`);
});Unregisters a layer status changed callback.
offLayerStatusChanged(callback: LayerStatusChangedDelegate): voidRegisters a callback for when a layer's visibility is toggled.
onLayerVisibilityToggled(callback: LayerVisibilityToggledDelegate): voidCallback Signature:
type LayerVisibilityToggledDelegate = (
sender: LayerApi,
event: LayerVisibilityToggledEvent
) => void;
interface LayerVisibilityToggledEvent {
layerPath: string;
visible: boolean;
}Example:
mapViewer.layer.onLayerVisibilityToggled((sender, event) => {
console.log(`Layer ${event.layerPath} visibility: ${event.visible}`);
});Unregisters a layer visibility toggled callback.
offLayerVisibilityToggled(callback: LayerVisibilityToggledDelegate): voidRegisters a callback for when a layer item's visibility is toggled.
onLayerItemVisibilityToggled(callback: LayerItemVisibilityToggledDelegate): voidCallback Signature:
type LayerItemVisibilityToggledDelegate = (
sender: LayerApi,
event: LayerItemVisibilityToggledEvent
) => void;
interface LayerItemVisibilityToggledEvent {
layerPath: string;
item: TypeLegendItem;
visible: boolean;
}Unregisters a layer item visibility toggled callback.
offLayerItemVisibilityToggled(callback: LayerItemVisibilityToggledDelegate): voidThe Layer API maintains several specialized layer sets for different purposes:
Manages layer legend information.
mapViewer.layer.legendsLayerSet;Manages feature information from map clicks.
mapViewer.layer.featureInfoLayerSet;Manages feature information from hover interactions.
mapViewer.layer.hoverFeatureInfoLayerSet;Manages all feature information (click + hover).
mapViewer.layer.allFeatureInfoLayerSet;Access geometry manipulation functions:
mapViewer.layer.geometry;See Geometry API Documentation for details.
Access feature and bbox highlighting:
mapViewer.layer.featureHighlight;Methods:
highlightFeatures(features, style)- Highlight specific featuresclearHighlights()- Clear all feature highlights
The Layer API can throw various errors:
import {
LayerNotFoundError,
LayerNotGeoJsonError,
LayerNotQueryableError,
LayerWrongTypeError,
LayerDifferingFieldLengths,
LayerCreatedTwiceError,
} from "@/core/exceptions/layer-exceptions";
try {
const layer = mapViewer.layer.getGeoviewLayer("nonexistent");
} catch (error) {
if (error instanceof LayerNotFoundError) {
console.error("Layer not found");
}
}// Use safe methods when unsure if layer exists
const layer = mapViewer.layer.getGeoviewLayerIfExists("myLayer");
if (layer) {
// Work with layer
}mapViewer.layer.onLayerAllLoaded((sender, event) => {
console.log("All layers loaded");
// Perform operations that require all layers
});mapViewer.layer.onLayerError((sender, event) => {
// Show user-friendly error message
console.error(`Failed to load layer: ${event.layerPath}`);
});const handleLayerLoaded = (sender, event) => {
console.log("Layer loaded:", event.layerPath);
};
// Register
mapViewer.layer.onLayerLoaded(handleLayerLoaded);
// Later, clean up
mapViewer.layer.offLayerLoaded(handleLayerLoaded);// When adding layers dynamically, wait for them
const result = mapViewer.layer.addGeoviewLayer(config);
const olLayer = await mapViewer.layer.getOLLayerAsync(
result.layerConfig.layerPath
);mapViewer.layer.addGeoviewLayer({
geoviewLayerId: "wmsLayer",
geoviewLayerName: "WMS Layer",
geoviewLayerType: "ogcWms",
metadataAccessPath: "https://example.com/wms",
listOfLayerEntryConfig: [
{
layerId: "layer1",
layerName: "Layer 1",
},
],
});const button = document.getElementById("toggle-layer");
button.addEventListener("click", () => {
mapViewer.layer.setOrToggleLayerVisibility("myLayer");
});const layerList = document.getElementById("layer-list");
layerList.addEventListener("mouseenter", (e) => {
const layerPath = e.target.dataset.layerPath;
mapViewer.layer.highlightLayer(layerPath);
});
layerList.addEventListener("mouseleave", () => {
mapViewer.layer.removeHighlightLayer();
});// Fetch new data
const response = await fetch("/api/updated-data");
const geojson = await response.json();
// Update layer
mapViewer.layer.setGeojsonSource("myGeoJsonLayer", geojson);The Layer API provides access to four Layer Sets that automatically manage layer-specific data:
legendsLayerSet- Legend and symbology information for all layersfeatureInfoLayerSet- Feature information at specific locations (for map clicks)allFeatureInfoLayerSet- All features from all layers (for data tables, exports)hoverFeatureInfoLayerSet- Feature information under mouse cursor (for tooltips)
Quick Example:
// Access legend data
const legendsLayerSet = mapViewer.layer.legendsLayerSet;
Object.values(legendsLayerSet.resultSet).forEach((entry) => {
console.log(`Legend for ${entry.layerName}:`, entry.items);
});
// Query features on click
mapViewer.onMapSingleClick((sender, payload) => {
mapViewer.layer.featureInfoLayerSet.queryLayers(payload.lnglat).then(() => {
// Access queried features
Object.values(mapViewer.layer.featureInfoLayerSet.resultSet).forEach(
(entry) => {
console.log(
`Features in ${entry.layerName}:`,
entry.featureInfo?.features
);
}
);
});
});For complete Layer Sets documentation, examples, and patterns, see:
- Layer Sets - Working with layer sets for legends, features, and hover info
- Event Processors - State management and event handling
- Configuration Reference - Layer configuration options
- API Reference - Main API entry points
- Map Viewer API - MapViewer instance methods