Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

feat: add heatmap and WMS legends to the map legend (#3718)

Igor Dykhtae090e7c2e3d1
diff --git a/docs/user-guides/c-types-of-layers/o-wms-layer.md b/docs/user-guides/c-types-of-layers/o-wms-layer.md
index 037a4923f..5271dc851 100644
--- a/docs/user-guides/c-types-of-layers/o-wms-layer.md
+++ b/docs/user-guides/c-types-of-layers/o-wms-layer.md
@@ -11,6 +11,7 @@ Use WMS Layer to render imagery from OGC Web Map Service (WMS) endpoints.
Notes:
- Feature info on click is supported for queryable layers (`queryable=true`).
+- The map legend shows a GetLegendGraphic / LegendURL image when the service provides one.
Example WMS services:
diff --git a/src/components/src/common/color-legend.tsx b/src/components/src/common/color-legend.tsx
index eb9160b56..f88d4c27f 100644
--- a/src/components/src/common/color-legend.tsx
+++ b/src/components/src/common/color-legend.tsx
@@ -42,6 +42,31 @@ const StyledLegend = styled.div<{$disableEdit: boolean; isExpanded?: boolean}>`
${props => (props.$disableEdit ? inputCss : '')}
`;
+const StyledHorizontalLegend = styled.div`
+ padding: 2px 0;
+`;
+
+const StyledColorRamp = styled.div`
+ display: flex;
+ height: 12px;
+ width: 100%;
+ overflow: hidden;
+`;
+
+const StyledRampSegment = styled.div<{$color: string}>`
+ flex: 1;
+ background-color: ${props => props.$color};
+`;
+
+const StyledRampLabels = styled.div`
+ display: flex;
+ justify-content: space-between;
+ margin-top: 2px;
+ font-size: 9.5px;
+ line-height: 12px;
+ color: ${props => props.theme.textColor};
+`;
+
const StyledLegendRow = styled.div`
display: flex;
align-items: center;
@@ -301,6 +326,8 @@ export type ColorLegendProps = {
isFixed?: boolean;
isExpanded?: boolean;
onUpdateColorLegend?: (colorLegends: {[key: HexColor]: string}) => void;
+ endpointLabels?: {min: string; max: string};
+ orientation?: 'vertical' | 'horizontal';
};
export type Legend = {
@@ -323,7 +350,9 @@ function ColorLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {
mapState,
onUpdateColorLegend,
displayLabel = true,
- disableEdit = false
+ disableEdit = false,
+ endpointLabels,
+ orientation = 'vertical'
}) => {
const {colorLegends} = range || {};
@@ -363,22 +392,54 @@ function ColorLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {
[onUpdateColorLegend, colorLegends]
);
+ if (orientation === 'horizontal') {
+ return (
+ <StyledHorizontalLegend className="styled-color-legend legend--color-ramp">
+ <StyledColorRamp>
+ {legends.map((legend, i) => (
+ <StyledRampSegment
+ key={`${legend.data}-${i}`}
+ className="legend--color-ramp__segment"
+ $color={legend.data}
+ />
+ ))}
+ </StyledColorRamp>
+ {endpointLabels ? (
+ <StyledRampLabels className="legend--color-ramp__labels">
+ <span className="legend--color-ramp__min">{endpointLabels.min}</span>
+ <span className="legend--color-ramp__max">{endpointLabels.max}</span>
+ </StyledRampLabels>
+ ) : null}
+ </StyledHorizontalLegend>
+ );
+ }
+
return (
<StyledLegend
className="styled-color-legend"
$disableEdit={disableEdit}
isExpanded={isExpanded}
>
- {legends.map((legend, i) => (
- <LegendRow
- key={`${legend.data}-${i}`}
- label={legend.label}
- displayLabel={displayLabel}
- color={legend.data}
- onUpdateLabel={!disableEdit ? onUpdateLabel : undefined}
- onResetLabel={legend.override && !disableEdit ? onResetLabel : undefined}
- />
- ))}
+ {legends.map((legend, i) => {
+ const endpointLabel =
+ endpointLabels && legends.length
+ ? i === 0
+ ? endpointLabels.min
+ : i === legends.length - 1
+ ? endpointLabels.max
+ : ''
+ : undefined;
+ return (
+ <LegendRow
+ key={`${legend.data}-${i}`}
+ label={endpointLabel !== undefined ? endpointLabel : legend.label}
+ displayLabel={displayLabel}
+ color={legend.data}
+ onUpdateLabel={!disableEdit ? onUpdateLabel : undefined}
+ onResetLabel={legend.override && !disableEdit ? onResetLabel : undefined}
+ />
+ );
+ })}
</StyledLegend>
);
};
diff --git a/src/components/src/map/map-legend.tsx b/src/components/src/map/map-legend.tsx
index f0fbd7658..f40c7c4ac 100644
--- a/src/components/src/map/map-legend.tsx
+++ b/src/components/src/map/map-legend.tsx
@@ -72,6 +72,19 @@ export const StyledMapControlLegend = styled.div<StyledMapControlLegendProps>`
.legend--layer_color-legend {
margin-top: 6px;
}
+
+ .legend--layer_image-wrap {
+ max-height: 240px;
+ overflow: auto;
+ background: #fff;
+ border-radius: 2px;
+ }
+
+ .legend--layer_image {
+ display: block;
+ max-width: 100%;
+ height: auto;
+ }
`;
const StyledLegendHeaderRow = styled.div`
@@ -225,6 +238,7 @@ export function LayerColorLegendFactory(
},
[layer, onLayerVisConfigChange, colorRange, range]
);
+ const isHeatmap = layer.type === 'heatmap';
const [isExpanded, setIsExpanded] = useState(isExport);
const handleToggleExpanded = () => setIsExpanded(!isExpanded);
return (
@@ -234,7 +248,7 @@ export function LayerColorLegendFactory(
{enableColorBy ? (
<div className="legend--layer_size-title-row">
<VisualChannelMetric name={enableColorBy} />
- {!isExport ? (
+ {!isExport && !isHeatmap ? (
<PanelHeaderAction
id="legend-collapse-button"
onClick={handleToggleExpanded}
@@ -257,6 +271,15 @@ export function LayerColorLegendFactory(
disableEdit={disableEdit || Boolean(isExport)}
isFixed={isFixed}
mapState={mapState}
+ orientation={isHeatmap ? 'horizontal' : 'vertical'}
+ endpointLabels={
+ isHeatmap
+ ? {
+ min: intl.formatMessage({id: 'mapLegend.min', defaultMessage: 'Min'}),
+ max: intl.formatMessage({id: 'mapLegend.max', defaultMessage: 'Max'})
+ }
+ : undefined
+ }
labelFormat={
colorField?.displayFormat ? d3Format(colorField?.displayFormat) : null
}
@@ -445,6 +468,18 @@ const defaultActionIcons = {
collapsed: ArrowRight
};
+const LayerImageLegend: React.FC<{src: string; alt: string}> = ({src, alt}) => {
+ const [failed, setFailed] = useState(false);
+ if (failed) {
+ return null;
+ }
+ return (
+ <div className="legend--layer_image-wrap">
+ <img className="legend--layer_image" src={src} alt={alt} onError={() => setFailed(true)} />
+ </div>
+ );
+};
+
export type LayerLegendContentProps = {
layer: Layer;
containerW: number;
@@ -470,6 +505,7 @@ export function LayerLegendContentFactory(
actionIcons
}) => {
const visualChannels = layer.getLegendVisualChannels();
+ const legendImageUrl = layer.getLegendImageUrl();
const channelKeys = Object.values(visualChannels);
const colorChannels = channelKeys.filter(isColorChannel) as VisualChannel[];
const nonColorChannels = channelKeys.filter(vc => !isColorChannel(vc));
@@ -489,6 +525,13 @@ export function LayerLegendContentFactory(
}
return (
<>
+ {legendImageUrl ? (
+ <LayerImageLegend
+ key={legendImageUrl}
+ src={legendImageUrl}
+ alt={layer.config.label || 'Layer legend'}
+ />
+ ) : null}
{colorChannelToRender.map(colorChannel => (
<LayerColorLegend
key={colorChannel.key}
diff --git a/src/components/src/modals/tilesets-modals/tileset-wms-form.tsx b/src/components/src/modals/tilesets-modals/tileset-wms-form.tsx
index c477d5e23..f6170a920 100644
--- a/src/components/src/modals/tilesets-modals/tileset-wms-form.tsx
+++ b/src/components/src/modals/tilesets-modals/tileset-wms-form.tsx
@@ -7,7 +7,11 @@ import {WMSCapabilities} from '@loaders.gl/wms';
import {validateUrl} from '@kepler.gl/common-utils';
import {DatasetType, REMOTE_TILE, RemoteTileFormat, WMSDatasetMetadata} from '@kepler.gl/constants';
-import {getWMSCapabilities, wmsCapabilitiesToDatasetMetadata} from '@kepler.gl/table';
+import {
+ getWMSCapabilities,
+ wmsCapabilitiesToDatasetMetadata,
+ buildWmsGetCapabilitiesUrl
+} from '@kepler.gl/table';
import {getApplicationConfig} from '@kepler.gl/utils';
import {MetaResponse} from './common';
@@ -135,7 +139,7 @@ const TilesetWMSForm: React.FC<WMSTileFormProps> = ({setResponse}) => {
const data = await getWMSCapabilities(newWmsUrl);
- const datasetMetadata = wmsCapabilitiesToDatasetMetadata(data);
+ const datasetMetadata = wmsCapabilitiesToDatasetMetadata(data, newWmsUrl);
// Extract name or title from GetCapabilities response
const serviceTitle = data?.title || data?.name;
@@ -167,7 +171,8 @@ const TilesetWMSForm: React.FC<WMSTileFormProps> = ({setResponse}) => {
type: REMOTE_TILE,
remoteTileFormat: RemoteTileFormat.WMS,
tilesetDataUrl: wmsUrl,
- tilesetMetadataUrl: `${wmsUrl}?service=WMS&request=GetCapabilities`,
+ tilesetMetadataUrl:
+ buildWmsGetCapabilitiesUrl(wmsUrl) || `${wmsUrl}?service=WMS&request=GetCapabilities`,
layers: wmsData?.layers || [],
version: wmsData?.version || '1.3.0'
}
diff --git a/src/constants/src/dataset.ts b/src/constants/src/dataset.ts
index 5c1250117..dbe90dda2 100644
--- a/src/constants/src/dataset.ts
+++ b/src/constants/src/dataset.ts
@@ -220,13 +220,21 @@ export type RasterTileMetadataSourceType = {
export type RasterTileDatasetMetadata = (RasterTileLocalMetadata | RasterTileRemoteMetadata) &
RasterTileMetadataSourceType;
+export type WMSServiceLayer = {
+ name: string;
+ title: string;
+ boundingBox: number[] | null;
+ queryable?: boolean;
+ legendUrl?: string | null;
+};
+
export type WMSDatasetMetadata = {
type: typeof REMOTE_TILE;
remoteTileFormat: RemoteTileFormat.WMS;
tilesetDataUrl: string;
tilesetMetadataUrl: string;
version: string;
- layers: {name: string; title: string; boundingBox: number[] | null}[];
+ layers: WMSServiceLayer[];
label?: string;
attribution?: string;
};
diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.ts
index f2e7bb82a..2e5e13c7a 100644
--- a/src/layers/src/base-layer.ts
+++ b/src/layers/src/base-layer.ts
@@ -132,6 +132,8 @@ export type LayerRadiusConfig = {
};
export type LayerWeightConfig = {
weightField: VisualChannelField;
+ weightDomain?: VisualChannelDomain;
+ weightScale?: VisualChannelScale;
};
export type VisualChannelDescription = {
@@ -1723,6 +1725,10 @@ class Layer implements KeplerLayer {
getLegendVisualChannels(): {[key: string]: VisualChannel} {
return this.visualChannels;
}
+
+ getLegendImageUrl(): string | null {
+ return null;
+ }
}
export default Layer;
diff --git a/src/layers/src/heatmap-layer/heatmap-layer.ts b/src/layers/src/heatmap-layer/heatmap-layer.ts
index 76a706834..d2dcafba8 100644
--- a/src/layers/src/heatmap-layer/heatmap-layer.ts
+++ b/src/layers/src/heatmap-layer/heatmap-layer.ts
@@ -6,9 +6,18 @@ import {
CHANNEL_SCALES,
ALL_FIELD_TYPES,
GEOJSON_FIELDS,
- GEOARROW_METADATA_KEY
+ GEOARROW_METADATA_KEY,
+ SCALE_TYPES
} from '@kepler.gl/constants';
-import Layer, {LayerBaseConfigPartial, LayerWeightConfig, VisualChannels} from '../base-layer';
+import Layer, {
+ LayerBaseConfigPartial,
+ LayerColorConfig,
+ LayerWeightConfig,
+ VisualChannel,
+ VisualChannelDomain,
+ VisualChannelScale,
+ VisualChannels
+} from '../base-layer';
import HeatmapLayerIcon from './heatmap-layer-icon';
import {
ColorRange,
@@ -72,7 +81,11 @@ export type HeatmapLayerVisConfig = {
aggregation: string;
};
-export type HeatmapLayerVisualChannelConfig = LayerWeightConfig;
+export type HeatmapLayerVisualChannelConfig = LayerWeightConfig &
+ LayerColorConfig & {
+ weightDomain: VisualChannelDomain;
+ weightScale: VisualChannelScale;
+ };
export type HeatmapLayerConfig = Merge<
LayerBaseConfig,
{columns: HeatmapLayerColumnsConfig; visConfig: HeatmapLayerVisConfig}
@@ -81,6 +94,19 @@ export type HeatmapLayerConfig = Merge<
export const MAX_ZOOM_LEVEL = 18;
+// Legend-only: heatmap GPU color is density × colorRange, not a data field.
+// Keep this off `visualChannels` so layer type change does not copy colorField.
+const HEATMAP_LEGEND_COLOR_CHANNEL: VisualChannel = {
+ property: 'color',
+ field: 'colorField',
+ scale: 'colorScale',
+ domain: 'colorDomain',
+ range: 'colorRange',
+ key: 'color',
+ channelScaleType: CHANNEL_SCALES.color,
+ defaultMeasure: 'property.density'
+};
+
export const pointPosAccessor =
({lat, lng}: HeatmapLayerColumnsConfig) =>
(dc: DataContainerInterface) =>
@@ -324,6 +350,29 @@ class HeatmapLayer extends Layer {
};
}
+ getLegendVisualChannels() {
+ const channels: VisualChannels = {color: HEATMAP_LEGEND_COLOR_CHANNEL};
+ // Show "weight by <field>" when a weight column is selected. Default
+ // density weighting is already represented by the color ramp.
+ if (this.config.weightField) {
+ channels.weight = this.visualChannels.weight;
+ }
+ return channels;
+ }
+
+ assignConfigToLayer(
+ ...args: Parameters<Layer['assignConfigToLayer']>
+ ): ReturnType<Layer['assignConfigToLayer']> {
+ super.assignConfigToLayer(...args);
+ // Density legend is not a color-by-field channel. Drop copied colorField /
+ // colorScale / colorDomain from the previous layer type.
+ this.updateLayerConfig({
+ colorField: null,
+ colorScale: SCALE_TYPES.quantize,
+ colorDomain: [0, 1]
+ });
+ }
+
get layerIcon() {
return HeatmapLayerIcon;
}
@@ -368,19 +417,19 @@ class HeatmapLayer extends Layer {
};
}
- getDefaultLayerConfig(props: LayerBaseConfigPartial): HeatmapLayerConfig {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const {colorField, colorDomain, colorScale, ...layerConfig} = {
+ getDefaultLayerConfig(props: LayerBaseConfigPartial) {
+ // Keep colorScale / colorDomain so the map legend can render the selected
+ // color ramp. colorField stays unused: heatmap color is density, not a field.
+ return {
...super.getDefaultLayerConfig(props),
columnMode: props?.columnMode ?? DEFAULT_COLUMN_MODE,
-
+ colorField: null,
+ colorScale: SCALE_TYPES.quantize,
+ colorDomain: [0, 1] as [number, number],
weightField: null,
- weightDomain: [0, 1],
- weightScale: 'linear'
+ weightDomain: [0, 1] as [number, number],
+ weightScale: SCALE_TYPES.linear
};
-
- // @ts-expect-error
- return layerConfig;
}
updateLayerMeta(dataset: KeplerTable) {
@@ -503,10 +552,7 @@ class HeatmapLayer extends Layer {
return {};
}
const dataset = datasets[dataId];
- const {weightField, weightScale, weightDomain} = this.config as HeatmapLayerConfig & {
- weightScale: string;
- weightDomain: number[];
- };
+ const {weightField, weightScale, weightDomain} = this.config;
const {gpuFilter, dataContainer} = dataset;
const oldData = oldLayerData as any;
@@ -538,7 +584,7 @@ class HeatmapLayer extends Layer {
let getWeight: ((d: {index: number}) => number) | number = 1;
if (weightField) {
const weightRange = [0, 1];
- const scaleFunc = this.getVisChannelScale(weightScale, weightDomain, weightRange);
+ const scaleFunc = this.getVisChannelScale(String(weightScale), weightDomain, weightRange);
getWeight = (d: {index: number}) =>
this.getEncodedChannelValue(scaleFunc || (x => x), d as any, weightField, 0 as any);
}
diff --git a/src/layers/src/scenegraph-layer/scenegraph-layer.ts b/src/layers/src/scenegraph-layer/scenegraph-layer.ts
index 3fce03043..dee33da65 100644
--- a/src/layers/src/scenegraph-layer/scenegraph-layer.ts
+++ b/src/layers/src/scenegraph-layer/scenegraph-layer.ts
@@ -148,6 +148,11 @@ export default class ScenegraphLayer extends Layer {
return ScenegraphLayerIcon;
}
+ // Mesh appearance comes from the GLTF, not layer fill/stroke encoding
+ getLegendVisualChannels() {
+ return {};
+ }
+
get layerInfoModal() {
return {
id: 'scenegraphInfo',
diff --git a/src/layers/src/wms-layer/wms-layer.ts b/src/layers/src/wms-layer/wms-layer.ts
index 2d5d49d70..be84deca7 100644
--- a/src/layers/src/wms-layer/wms-layer.ts
+++ b/src/layers/src/wms-layer/wms-layer.ts
@@ -4,7 +4,7 @@
import {notNullorUndefined} from '@kepler.gl/common-utils';
import {DatasetType, WMSDatasetMetadata, LAYER_TYPES} from '@kepler.gl/constants';
import {WMSLayer as DeckWMSLayer} from '@kepler.gl/deckgl-layers';
-import {KeplerTable as KeplerDataset} from '@kepler.gl/table';
+import {KeplerTable as KeplerDataset, buildWmsGetLegendGraphicUrl} from '@kepler.gl/table';
import {
AnimationConfig,
Field,
@@ -43,6 +43,7 @@ export type WMSLayerVisConfig = {
title: string;
boundingBox: number[][];
queryable: boolean;
+ legendUrl?: string | null;
} | null;
};
@@ -122,6 +123,30 @@ export default class WMSLayer extends AbstractTileLayer<WMSTile, any[]> {
return [DatasetType.WMS_TILE];
}
+ // Image overlay has no fill/stroke encoding to show in the map legend
+ getLegendVisualChannels() {
+ return {};
+ }
+
+ getLegendImageUrl(): string | null {
+ const serviceLayer = this._getCurrentServiceLayer();
+ if (!serviceLayer?.name) {
+ return null;
+ }
+ const refreshedLegendUrl = this._getRefreshedServiceLayer(serviceLayer.name)?.legendUrl;
+ const legendUrl = refreshedLegendUrl || serviceLayer.legendUrl;
+ if (legendUrl) {
+ return legendUrl;
+ }
+ const tilesetDataUrl = this.meta?.tilesetDataUrl;
+ if (typeof tilesetDataUrl === 'string' && tilesetDataUrl) {
+ return buildWmsGetLegendGraphicUrl(tilesetDataUrl, serviceLayer.name, {
+ version: this.meta?.wmsVersion
+ });
+ }
+ return null;
+ }
+
protected initTileDataset() {
// Provide dummy accessors for raster/WMS
return new TileDataset<WMSTile, any[]>({
@@ -160,19 +185,53 @@ export default class WMSLayer extends AbstractTileLayer<WMSTile, any[]> {
return visConfig.wmsLayer ?? null;
}
+ _getRefreshedServiceLayer(layerName: string) {
+ const layers = this.meta?.layers;
+ if (!Array.isArray(layers)) {
+ return null;
+ }
+ return layers.find(layer => layer?.name === layerName) ?? null;
+ }
+
updateLayerMeta(dataset: KeplerDataset): void {
if (dataset.type !== DatasetType.WMS_TILE) {
return;
}
+ const metadata = dataset.metadata as WMSDatasetMetadata | undefined;
const currentLayer = this._getCurrentServiceLayer();
- if (currentLayer && currentLayer.boundingBox) {
+ const refreshedLayer =
+ currentLayer?.name && metadata?.layers
+ ? metadata.layers.find(layer => layer.name === currentLayer.name)
+ : undefined;
+
+ if (currentLayer && refreshedLayer) {
+ this.updateLayerVisConfig({
+ wmsLayer: {
+ ...currentLayer,
+ ...refreshedLayer
+ }
+ });
+ }
+
+ const selectedLayer = this._getCurrentServiceLayer();
+ if (selectedLayer?.boundingBox) {
this.updateMeta({
- bounds: currentLayer.boundingBox
+ bounds: selectedLayer.boundingBox
});
}
- const metadata = dataset.metadata as WMSDatasetMetadata | undefined;
+ if (metadata?.layers) {
+ this.updateMeta({
+ layers: metadata.layers
+ });
+ }
+ if (metadata?.tilesetDataUrl) {
+ this.updateMeta({
+ tilesetDataUrl: metadata.tilesetDataUrl,
+ wmsVersion: metadata.version
+ });
+ }
if (metadata?.attribution) {
this.updateMeta({
attribution: {title: metadata.attribution, url: metadata.tilesetDataUrl || ''}
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 1f1cf486e..e7569f7ce 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -862,6 +862,8 @@ ${'```'}
Save: 'Save',
Share: 'Share',
mapLegend: {
+ min: 'Min',
+ max: 'Max',
layers: {
line: {
singleColor: {
diff --git a/src/table/src/dataset-utils.ts b/src/table/src/dataset-utils.ts
index a99509117..01d98ed87 100644
--- a/src/table/src/dataset-utils.ts
+++ b/src/table/src/dataset-utils.ts
@@ -34,6 +34,7 @@ import {
getFieldsFromTile,
VectorTileMetadata
} from './tileset/vector-tile-utils';
+import {buildWmsGetCapabilitiesUrl, wmsCapabilitiesToDatasetMetadata} from './tileset/wms-utils';
// apply a color for each dataset
// to use as label colors
@@ -262,7 +263,7 @@ async function refreshWMSMetadata(datasetInfo: CreateTableProps): Promise<any |
try {
const data = await getWMSCapabilities(tilesetDataUrl);
- return wmsCapabilitiesToDatasetMetadata(data);
+ return wmsCapabilitiesToDatasetMetadata(data, tilesetDataUrl);
} catch (err) {
// ignore for now, and use old metadata
}
@@ -270,42 +271,8 @@ async function refreshWMSMetadata(datasetInfo: CreateTableProps): Promise<any |
}
export async function getWMSCapabilities(wsmUrl: string): Promise<WMSCapabilities> {
- return (await load(
- `${wsmUrl}?service=WMS&request=GetCapabilities`,
- WMSCapabilitiesLoader
- )) as WMSCapabilities;
-}
-
-export function wmsCapabilitiesToDatasetMetadata(capabilities: WMSCapabilities): any | null {
- // Flatten layers if they are nested
- const layers = capabilities.layers.flatMap(layer => {
- if (layer.layers && layer.layers.length > 0) {
- return layer.layers;
- }
- return layer;
- });
-
- let availableLayers: WMSDatasetMetadata['layers'] = [];
- if (Array.isArray(layers)) {
- availableLayers = layers.map((layer: any) => {
- const bb = layer.geographicBoundingBox;
-
- let boundingBox: number[] | null = null;
- if (Array.isArray(bb) && Array.isArray(bb[0]) && Array.isArray(bb[1])) {
- boundingBox = [bb[0][0], bb[0][1], bb[1][0], bb[1][1]];
- }
-
- return {
- name: layer.name,
- title: layer.title || layer.name,
- boundingBox,
- queryable: layer.queryable
- };
- });
- }
-
- return {
- layers: availableLayers,
- version: capabilities.version || '1.3.0'
- };
+ const capabilitiesUrl = buildWmsGetCapabilitiesUrl(wsmUrl) || wsmUrl;
+ return (await load(capabilitiesUrl, WMSCapabilitiesLoader, {
+ wms: {includeRawJSON: true}
+ })) as WMSCapabilities;
}
diff --git a/src/table/src/index.ts b/src/table/src/index.ts
index 4a551a39f..c650a5cee 100644
--- a/src/table/src/index.ts
+++ b/src/table/src/index.ts
@@ -23,6 +23,7 @@ export type {
} from './kepler-table';
export * from './gpu-filter-utils';
export * from './dataset-utils';
+export * from './tileset/wms-utils';
export * from './tileset/tileset-utils';
export * from './tileset/vector-tile-utils';
export * from './tileset/raster-tile-utils';
diff --git a/src/table/src/tileset/wms-utils.ts b/src/table/src/tileset/wms-utils.ts
new file mode 100644
index 000000000..6b6a30f22
--- /dev/null
+++ b/src/table/src/tileset/wms-utils.ts
@@ -0,0 +1,265 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+const WMS_PARAM_KEYS_TO_REPLACE = new Set([
+ 'service',
+ 'request',
+ 'version',
+ 'layers',
+ 'layer',
+ 'styles',
+ 'style',
+ 'format',
+ 'crs',
+ 'srs',
+ 'bbox',
+ 'width',
+ 'height',
+ 'transparent',
+ 'bgcolor',
+ 'exceptions',
+ 'sld',
+ 'sld_version',
+ 'legend_options'
+]);
+
+function asArray<T>(value: T | T[] | undefined | null): T[] {
+ if (value == null) {
+ return [];
+ }
+ return Array.isArray(value) ? value : [value];
+}
+
+function decodeXmlEntities(value: string): string {
+ return value.replace(/&amp;/g, '&').replace(/&quot;/g, '"');
+}
+
+/**
+ * LegendURL may be a relative URI. Resolve it against the WMS service URL so
+ * `<img src>` does not load it from the Kepler app origin.
+ */
+export function resolveWmsLegendUrl(href: string, serviceUrl?: string): string | null {
+ if (!href) {
+ return null;
+ }
+ try {
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(href)) {
+ return href;
+ }
+ if (!serviceUrl) {
+ return href;
+ }
+ return new URL(href, serviceUrl).toString();
+ } catch {
+ return href;
+ }
+}
+
+function getHref(node: unknown): string | null {
+ if (!node) {
+ return null;
+ }
+ if (typeof node === 'string') {
+ return decodeXmlEntities(node) || null;
+ }
+ if (typeof node !== 'object') {
+ return null;
+ }
+ const obj = node as Record<string, unknown>;
+ const candidates = [obj['xlink:href'], obj.href, obj.Href, obj['@_xlink:href'], obj['@_href']];
+ for (const candidate of candidates) {
+ if (typeof candidate === 'string' && candidate) {
+ return decodeXmlEntities(candidate);
+ }
+ }
+ return null;
+}
+
+function extractLegendUrlFromLayerNode(layerNode: Record<string, unknown>): string | null {
+ const styles = asArray(layerNode.Style ?? layerNode.style);
+ for (const style of styles) {
+ if (!style || typeof style !== 'object') {
+ continue;
+ }
+ const legendUrls = asArray(
+ (style as Record<string, unknown>).LegendURL ?? (style as Record<string, unknown>).LegendUrl
+ );
+ for (const legend of legendUrls) {
+ if (!legend || typeof legend !== 'object') {
+ continue;
+ }
+ const legendObj = legend as Record<string, unknown>;
+ const href = getHref(legendObj) ?? getHref(legendObj.OnlineResource);
+ if (href) {
+ return href;
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Walk raw GetCapabilities JSON (from loaders.gl `includeRawJSON`) and collect
+ * Style/LegendURL OnlineResource hrefs keyed by layer name.
+ */
+export function collectWmsLegendUrlsFromRawJson(json: unknown): Record<string, string> {
+ const urls: Record<string, string> = {};
+
+ const visit = (node: unknown) => {
+ if (!node) {
+ return;
+ }
+ if (Array.isArray(node)) {
+ node.forEach(visit);
+ return;
+ }
+ if (typeof node !== 'object') {
+ return;
+ }
+ const obj = node as Record<string, unknown>;
+ const name = obj.Name ?? obj.name;
+ const legendUrl = extractLegendUrlFromLayerNode(obj);
+ if (typeof name === 'string' && name && legendUrl) {
+ urls[name] = legendUrl;
+ }
+ if ('Layer' in obj) {
+ visit(obj.Layer);
+ }
+ if ('layer' in obj) {
+ visit(obj.layer);
+ }
+ if ('Capability' in obj) {
+ visit(obj.Capability);
+ }
+ };
+
+ const root =
+ json && typeof json === 'object' && !Array.isArray(json)
+ ? (json as Record<string, unknown>).WMS_Capabilities ||
+ (json as Record<string, unknown>).WMT_MS_Capabilities ||
+ json
+ : json;
+
+ visit(root);
+ return urls;
+}
+
+/**
+ * Replace WMS request parameters on a service URL while keeping vendor query params.
+ */
+export function buildWmsRequestUrl(
+ serviceUrl: string,
+ params: Record<string, string | undefined>
+): string | null {
+ if (!serviceUrl) {
+ return null;
+ }
+ try {
+ const url = new URL(serviceUrl);
+ for (const key of [...url.searchParams.keys()]) {
+ if (WMS_PARAM_KEYS_TO_REPLACE.has(key.toLowerCase())) {
+ url.searchParams.delete(key);
+ }
+ }
+ for (const [key, value] of Object.entries(params)) {
+ if (value !== undefined && value !== '') {
+ url.searchParams.set(key, value);
+ }
+ }
+ return url.toString();
+ } catch {
+ return null;
+ }
+}
+
+export function buildWmsGetCapabilitiesUrl(serviceUrl: string): string | null {
+ return buildWmsRequestUrl(serviceUrl, {
+ SERVICE: 'WMS',
+ REQUEST: 'GetCapabilities'
+ });
+}
+
+export function buildWmsGetLegendGraphicUrl(
+ serviceUrl: string,
+ layerName: string,
+ options?: {version?: string; format?: string; style?: string}
+): string | null {
+ if (!serviceUrl || !layerName) {
+ return null;
+ }
+ return buildWmsRequestUrl(serviceUrl, {
+ SERVICE: 'WMS',
+ REQUEST: 'GetLegendGraphic',
+ VERSION: options?.version || '1.3.0',
+ LAYER: layerName,
+ FORMAT: options?.format || 'image/png',
+ STYLE: options?.style,
+ TRANSPARENT: 'TRUE',
+ SLD_VERSION: '1.1.0'
+ });
+}
+
+export function wmsCapabilitiesToDatasetMetadata(
+ capabilities: {
+ layers?: Array<{
+ name?: string;
+ title?: string;
+ geographicBoundingBox?: unknown;
+ queryable?: boolean;
+ layers?: any[];
+ }>;
+ json?: unknown;
+ version?: string;
+ },
+ serviceUrl?: string
+): {
+ layers: Array<{
+ name: string;
+ title: string;
+ boundingBox: number[] | null;
+ queryable?: boolean;
+ legendUrl?: string | null;
+ }>;
+ version: string;
+} {
+ const layers = (capabilities.layers || []).flatMap(layer => {
+ if (layer.layers && layer.layers.length > 0) {
+ return layer.layers;
+ }
+ return layer;
+ });
+
+ const legendUrlsFromCapabilities = collectWmsLegendUrlsFromRawJson(capabilities.json);
+ const version = capabilities.version || '1.3.0';
+
+ const availableLayers = layers.map((layer: any) => {
+ const bb = layer.geographicBoundingBox;
+
+ let boundingBox: number[] | null = null;
+ if (Array.isArray(bb) && Array.isArray(bb[0]) && Array.isArray(bb[1])) {
+ boundingBox = [bb[0][0], bb[0][1], bb[1][0], bb[1][1]];
+ }
+
+ const layerName = layer.name;
+ const advertisedLegendUrl =
+ typeof layerName === 'string' ? legendUrlsFromCapabilities[layerName] : undefined;
+ const legendUrl =
+ (advertisedLegendUrl && resolveWmsLegendUrl(advertisedLegendUrl, serviceUrl)) ||
+ (typeof layerName === 'string' && serviceUrl
+ ? buildWmsGetLegendGraphicUrl(serviceUrl, layerName, {version})
+ : null);
+
+ return {
+ name: layerName,
+ title: layer.title || layer.name,
+ boundingBox,
+ queryable: layer.queryable,
+ legendUrl: legendUrl || null
+ };
+ });
+
+ return {
+ layers: availableLayers,
+ version
+ };
+}
diff --git a/src/types/layers.d.ts b/src/types/layers.d.ts
index 7e1114e16..de1c6b0ca 100644
--- a/src/types/layers.d.ts
+++ b/src/types/layers.d.ts
@@ -107,6 +107,8 @@ export type LayerRadiusConfig = {
};
export type LayerWeightConfig = {
weightField: VisualChannelField;
+ weightDomain?: VisualChannelDomain;
+ weightScale?: VisualChannelScale;
};
export type IndexBy = {
diff --git a/test/browser/components/map/map-legend-test.js b/test/browser/components/map/map-legend-test.js
index ea759b460..061ea47b7 100644
--- a/test/browser/components/map/map-legend-test.js
+++ b/test/browser/components/map/map-legend-test.js
@@ -26,7 +26,7 @@ import {
} from 'test/helpers/mock-state';
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
import {KeplerGlLayers} from '@kepler.gl/layers';
-const {PointLayer} = KeplerGlLayers;
+const {PointLayer, WMSLayer, HeatmapLayer} = KeplerGlLayers;
const MapLegend = appInjector.get(MapLegendFactory);
const LayerColorLegend = appInjector.get(LayerColorLegendFactory);
@@ -276,3 +276,136 @@ test('Components -> MapLegend.render -> with colorLegends', t => {
t.end();
});
+
+test('Components -> MapLegend.render -> WMS legend image', t => {
+ const wmsLayer = new WMSLayer({
+ id: 'wms-legend',
+ dataId: 'wms-dataset',
+ label: 'WMS legend layer',
+ isVisible: true
+ });
+ wmsLayer.updateLayerVisConfig({
+ wmsLayer: {
+ name: 'OSM-WMS',
+ title: 'OpenStreetMap',
+ boundingBox: [
+ [-180, -90],
+ [180, 90]
+ ],
+ queryable: true,
+ legendUrl: 'https://example.com/legend.png'
+ }
+ });
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <MapLegend layers={[wmsLayer]} />
+ </IntlWrapper>
+ );
+ }, 'Should not fail with a WMS layer');
+
+ t.equal(wrapper.find(StyledMapControlLegend).length, 1, 'should render 1 layer legend');
+ t.equal(
+ wrapper.find('.legend--layer_name').at(0).text(),
+ 'WMS legend layer',
+ 'should render WMS layer label'
+ );
+ t.equal(wrapper.find('img.legend--layer_image').length, 1, 'should render WMS legend image');
+ t.equal(
+ wrapper.find('img.legend--layer_image').at(0).props().src,
+ 'https://example.com/legend.png',
+ 'should use GetLegendGraphic / LegendURL'
+ );
+ t.equal(wrapper.find(LayerColorLegend).length, 0, 'should not render fill color legend for WMS');
+
+ t.end();
+});
+
+test('Components -> MapLegend.render -> heatmap color scale', t => {
+ const heatmapLayer = new HeatmapLayer({
+ id: 'heatmap-legend',
+ dataId: 'heatmap-dataset',
+ label: 'Heatmap legend layer',
+ isVisible: true
+ });
+ heatmapLayer.updateLayerConfig({
+ columns: {
+ lat: {value: 'lat', fieldIdx: 0},
+ lng: {value: 'lng', fieldIdx: 1}
+ }
+ });
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <MapLegend layers={[heatmapLayer]} />
+ </IntlWrapper>
+ );
+ }, 'Should not fail with a heatmap layer');
+
+ t.equal(wrapper.find(StyledMapControlLegend).length, 1, 'should render 1 layer legend');
+ t.equal(wrapper.find(LayerColorLegend).length, 1, 'should render heatmap color legend');
+ t.equal(
+ wrapper.find('.legend--layer_color_field').at(0).text().toLowerCase(),
+ 'density',
+ 'should label heatmap legend as density'
+ );
+ t.ok(
+ wrapper.find('.legend--color-ramp__segment').length >= 2,
+ 'should render a horizontal color ramp'
+ );
+ t.equal(
+ wrapper.find('.legend--color-ramp__min').at(0).text(),
+ 'Min',
+ 'left end of the ramp should be labeled Min'
+ );
+ t.equal(
+ wrapper.find('.legend--color-ramp__max').at(0).text(),
+ 'Max',
+ 'right end of the ramp should be labeled Max'
+ );
+ t.equal(
+ wrapper.find(LayerDefaultLegend).length,
+ 0,
+ 'should not render weight by density when no weight field is set'
+ );
+
+ t.end();
+});
+
+test('Components -> MapLegend.render -> heatmap weight field', t => {
+ const heatmapLayer = new HeatmapLayer({
+ id: 'heatmap-legend-weight',
+ dataId: 'heatmap-dataset',
+ label: 'Heatmap weight legend',
+ isVisible: true
+ });
+ heatmapLayer.updateLayerConfig({
+ columns: {
+ lat: {value: 'lat', fieldIdx: 0},
+ lng: {value: 'lng', fieldIdx: 1}
+ },
+ weightField: {name: 'trip_distance', type: 'real'}
+ });
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <MapLegend layers={[heatmapLayer]} />
+ </IntlWrapper>
+ );
+ }, 'Should not fail with a weighted heatmap layer');
+
+ t.equal(wrapper.find(LayerColorLegend).length, 1, 'should still render heatmap color legend');
+ t.equal(wrapper.find(LayerDefaultLegend).length, 1, 'should render weight legend');
+ t.ok(
+ wrapper.find(LayerDefaultLegend).at(0).text().toLowerCase().includes('trip_distance'),
+ 'weight legend should show the selected field name'
+ );
+
+ t.end();
+});
diff --git a/test/browser/layer-tests/heatmap-layer-specs.js b/test/browser/layer-tests/heatmap-layer-specs.js
index 2689c4b02..f3ad66b13 100644
--- a/test/browser/layer-tests/heatmap-layer-specs.js
+++ b/test/browser/layer-tests/heatmap-layer-specs.js
@@ -17,7 +17,7 @@ import {KeplerGlLayers} from '@kepler.gl/layers';
import {copyTableAndUpdate} from '@kepler.gl/table';
import {convertGeometryToWKB} from '@loaders.gl/gis';
-const {HeatmapLayer} = KeplerGlLayers;
+const {HeatmapLayer, PointLayer} = KeplerGlLayers;
const columns = {
lat: 'lat',
@@ -44,6 +44,21 @@ test('#HeatmapLayer -> contructor', t => {
t.ok(layer.isAggregated === true, 'heatmaplayer is aggregated');
t.ok(layer.config.label === 'test heatmap layer', 'label should be correct');
t.ok(Object.keys(layer.columnPairs).length, 'should have columnPairs');
+ t.equal(layer.config.colorScale, 'quantize', 'heatmap legend should use quantize scale');
+ t.deepEqual(layer.config.colorDomain, [0, 1], 'heatmap legend domain should be 0-1');
+ t.notOk(
+ layer.visualChannels.color,
+ 'color is legend-only and should not be a visual channel'
+ );
+ t.ok(
+ layer.getLegendVisualChannels().color,
+ 'should expose a color channel for the legend'
+ );
+ t.deepEqual(
+ Object.keys(layer.getLegendVisualChannels()),
+ ['color'],
+ 'legend should not show weight when no weight field is set'
+ );
}
}
]
@@ -53,6 +68,79 @@ test('#HeatmapLayer -> contructor', t => {
t.end();
});
+test('#HeatmapLayer -> assignConfigToLayer does not copy colorField', t => {
+ const pointLayer = new PointLayer({
+ dataId: 'taro',
+ isVisible: true,
+ label: 'points'
+ });
+ pointLayer.updateLayerConfig({
+ colorField: {name: 'trip_distance', type: 'real'},
+ colorScale: 'quantile',
+ colorDomain: [0, 100]
+ });
+
+ const heatmapLayer = new HeatmapLayer({
+ dataId: 'taro',
+ isVisible: true,
+ label: 'heatmap'
+ });
+ heatmapLayer.assignConfigToLayer(pointLayer.config, pointLayer.visConfigSettings);
+
+ t.equal(
+ heatmapLayer.config.colorField,
+ null,
+ 'should not copy colorField from the previous layer type'
+ );
+ t.equal(
+ heatmapLayer.config.colorScale,
+ 'quantize',
+ 'should keep quantize legend scale after type change'
+ );
+ t.deepEqual(
+ heatmapLayer.config.colorDomain,
+ [0, 1],
+ 'should keep 0-1 density domain after type change'
+ );
+ t.ok(
+ heatmapLayer.getLegendVisualChannels().color,
+ 'legend should still expose the density color ramp'
+ );
+
+ t.end();
+});
+
+test('#HeatmapLayer -> getLegendVisualChannels includes weight field', t => {
+ const heatmapLayer = new HeatmapLayer({
+ dataId: 'taro',
+ isVisible: true,
+ label: 'heatmap'
+ });
+
+ t.deepEqual(
+ Object.keys(heatmapLayer.getLegendVisualChannels()),
+ ['color'],
+ 'legend should only show the color ramp by default'
+ );
+
+ heatmapLayer.updateLayerConfig({
+ weightField: {name: 'trip_distance', type: 'real'}
+ });
+
+ t.deepEqual(
+ Object.keys(heatmapLayer.getLegendVisualChannels()),
+ ['color', 'weight'],
+ 'legend should include weight when a weight field is selected'
+ );
+ t.equal(
+ heatmapLayer.getVisualChannelDescription('weight').measure,
+ 'trip_distance',
+ 'weight legend should use the selected field name'
+ );
+
+ t.end();
+});
+
test('#Heatmaplayer -> formatLayerData -> w/ GpuFilter', t => {
const filteredIndex = [0, 2, 4];
diff --git a/test/browser/layer-tests/scenegraph-layer-specs.js b/test/browser/layer-tests/scenegraph-layer-specs.js
index 1a463e48a..c3215040c 100644
--- a/test/browser/layer-tests/scenegraph-layer-specs.js
+++ b/test/browser/layer-tests/scenegraph-layer-specs.js
@@ -37,6 +37,11 @@ test('#ScenegraphLayer -> constructor', t => {
t.ok(layer.isAggregated === false, 'ScenegraphLayer is not aggregated');
t.ok(layer.config.label === 'test 3d layer', 'label should be correct');
t.ok(Object.keys(layer.columnPairs).length, 'should have columnPairs');
+ t.deepEqual(
+ layer.getLegendVisualChannels(),
+ {},
+ 'should expose no legend channels (mesh has no fill color)'
+ );
}
}
]
diff --git a/test/browser/layer-tests/wms-layer-specs.js b/test/browser/layer-tests/wms-layer-specs.js
index d2710f8cb..4f5742e89 100644
--- a/test/browser/layer-tests/wms-layer-specs.js
+++ b/test/browser/layer-tests/wms-layer-specs.js
@@ -129,6 +129,85 @@ test('#WMSLayer -> constructor', t => {
t.end();
});
+test('#WMSLayer -> legend visual channels', t => {
+ const layer = createWMSLayer();
+
+ t.deepEqual(
+ layer.getLegendVisualChannels(),
+ {},
+ 'should expose no legend channels (WMS has no fill color)'
+ );
+
+ t.end();
+});
+
+test('#WMSLayer -> getLegendImageUrl', t => {
+ const layer = createWMSLayer({
+ visConfig: {
+ wmsLayer: {
+ ...MOCK_WMS_LAYER_CONFIG,
+ legendUrl: 'https://example.com/legend.png'
+ }
+ }
+ });
+
+ t.equal(
+ layer.getLegendImageUrl(),
+ 'https://example.com/legend.png',
+ 'should use LegendURL stored on the selected WMS layer'
+ );
+
+ const layerWithoutLegend = createWMSLayer();
+ t.equal(
+ layerWithoutLegend.getLegendImageUrl(),
+ null,
+ 'should return null before dataset meta has a service URL'
+ );
+
+ layerWithoutLegend.updateLayerMeta(MOCK_WMS_DATASET);
+ const constructed = layerWithoutLegend.getLegendImageUrl();
+ t.ok(constructed, 'should construct GetLegendGraphic from dataset URL');
+ t.ok(
+ constructed.includes('GetLegendGraphic'),
+ 'constructed legend URL should request GetLegendGraphic'
+ );
+ t.ok(constructed.includes('test_layer'), 'constructed legend URL should include layer name');
+
+ const restoredLayer = createWMSLayer({
+ visConfig: {
+ wmsLayer: {
+ ...MOCK_WMS_LAYER_CONFIG,
+ legendUrl: 'https://stale.example/old-legend.png'
+ }
+ }
+ });
+ restoredLayer.updateLayerMeta({
+ type: 'wms-tile',
+ metadata: {
+ tilesetDataUrl: 'http://example.com/wms',
+ version: '1.3.0',
+ layers: [
+ {
+ ...MOCK_WMS_LAYER_CONFIG,
+ legendUrl: 'https://example.com/refreshed-legend.png'
+ }
+ ]
+ }
+ });
+ t.equal(
+ restoredLayer.getLegendImageUrl(),
+ 'https://example.com/refreshed-legend.png',
+ 'should use advertised LegendURL from refreshed dataset metadata'
+ );
+ t.equal(
+ restoredLayer.config.visConfig.wmsLayer.legendUrl,
+ 'https://example.com/refreshed-legend.png',
+ 'should reconcile selected wmsLayer with refreshed metadata'
+ );
+
+ t.end();
+});
+
test('WMSLayer -> basic layer functionality', t => {
const layer = createWMSLayer();
diff --git a/test/node/utils/index.js b/test/node/utils/index.js
index 9f12619b6..93afc3f60 100644
--- a/test/node/utils/index.js
+++ b/test/node/utils/index.js
@@ -30,6 +30,7 @@ import './timeline-zoom-test';
import './plot-test';
import './composer-helpers-test';
import './dom-to-image';
+import './wms-utils-test';
import './effect-utils-test';
import './duckdb-utils-test';
import './annotation-utils-test';
diff --git a/test/node/utils/wms-utils-test.js b/test/node/utils/wms-utils-test.js
new file mode 100644
index 000000000..b3ec35f7f
--- /dev/null
+++ b/test/node/utils/wms-utils-test.js
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {
+ buildWmsGetCapabilitiesUrl,
+ buildWmsGetLegendGraphicUrl,
+ collectWmsLegendUrlsFromRawJson,
+ wmsCapabilitiesToDatasetMetadata
+} from '../../../src/table/src/tileset/wms-utils';
+
+test('WMS utils -> buildWmsGetLegendGraphicUrl', t => {
+ const url = buildWmsGetLegendGraphicUrl('https://example.com/wms', 'OSM-WMS', {
+ version: '1.3.0'
+ });
+ const parsed = new URL(url);
+
+ t.equal(parsed.origin + parsed.pathname, 'https://example.com/wms');
+ t.equal(parsed.searchParams.get('SERVICE'), 'WMS');
+ t.equal(parsed.searchParams.get('REQUEST'), 'GetLegendGraphic');
+ t.equal(parsed.searchParams.get('LAYER'), 'OSM-WMS');
+ t.equal(parsed.searchParams.get('FORMAT'), 'image/png');
+ t.equal(parsed.searchParams.get('VERSION'), '1.3.0');
+ t.equal(parsed.searchParams.get('TRANSPARENT'), 'TRUE');
+
+ t.end();
+});
+
+test('WMS utils -> buildWmsRequestUrl replaces existing WMS params', t => {
+ const url = buildWmsGetLegendGraphicUrl(
+ 'https://example.com/wms?service=WMS&request=GetCapabilities&map=/data/map.map',
+ 'roads'
+ );
+ const parsed = new URL(url);
+
+ t.equal(parsed.searchParams.get('REQUEST'), 'GetLegendGraphic');
+ t.equal(parsed.searchParams.get('map'), '/data/map.map', 'keeps vendor query params');
+ t.equal(parsed.searchParams.get('LAYER'), 'roads');
+
+ t.end();
+});
+
+test('WMS utils -> buildWmsGetCapabilitiesUrl', t => {
+ const url = buildWmsGetCapabilitiesUrl(
+ 'https://example.com/wms?service=WMS&request=GetMap&layers=x'
+ );
+ const parsed = new URL(url);
+ t.equal(parsed.searchParams.get('REQUEST'), 'GetCapabilities');
+ t.equal(parsed.searchParams.get('SERVICE'), 'WMS');
+ t.notOk(parsed.searchParams.get('layers'));
+ t.end();
+});
+
+test('WMS utils -> collectWmsLegendUrlsFromRawJson unwraps WMS_Capabilities', t => {
+ const rawJson = {
+ WMS_Capabilities: {
+ Capability: {
+ Layer: {
+ Name: 'OSM-WMS',
+ Style: {
+ LegendURL: {
+ OnlineResource: {
+ 'xlink:href': 'https://example.com/legend.png'
+ }
+ }
+ }
+ }
+ }
+ }
+ };
+
+ t.deepEqual(collectWmsLegendUrlsFromRawJson(rawJson), {
+ 'OSM-WMS': 'https://example.com/legend.png'
+ });
+
+ t.end();
+});
+
+test('WMS utils -> collectWmsLegendUrlsFromRawJson', t => {
+ const rawJson = {
+ Capability: {
+ Layer: {
+ Title: 'root',
+ Layer: [
+ {
+ Name: 'OSM-WMS',
+ Title: 'OpenStreetMap',
+ Style: {
+ Name: 'default',
+ LegendURL: {
+ OnlineResource: {
+ 'xlink:href':
+ 'https://example.com/wms?request=GetLegendGraphic&layer=OSM-WMS&format=image/png'
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ };
+
+ t.deepEqual(collectWmsLegendUrlsFromRawJson(rawJson), {
+ 'OSM-WMS': 'https://example.com/wms?request=GetLegendGraphic&layer=OSM-WMS&format=image/png'
+ });
+
+ t.end();
+});
+
+test('WMS utils -> wmsCapabilitiesToDatasetMetadata prefers LegendURL', t => {
+ const capabilities = {
+ version: '1.3.0',
+ name: 'WMS',
+ keywords: [],
+ requests: {},
+ layers: [
+ {
+ title: 'root',
+ keywords: [],
+ layers: [
+ {
+ name: 'OSM-WMS',
+ title: 'OpenStreetMap',
+ keywords: [],
+ geographicBoundingBox: [
+ [-180, -90],
+ [180, 90]
+ ],
+ queryable: true
+ }
+ ]
+ }
+ ],
+ json: {
+ Capability: {
+ Layer: {
+ Layer: {
+ Name: 'OSM-WMS',
+ Style: {
+ LegendURL: {
+ OnlineResource: {
+ 'xlink:href': 'https://example.com/legend.png'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ };
+
+ const metadata = wmsCapabilitiesToDatasetMetadata(capabilities, 'https://example.com/wms');
+
+ t.equal(metadata.layers.length, 1);
+ t.equal(metadata.layers[0].name, 'OSM-WMS');
+ t.equal(metadata.layers[0].legendUrl, 'https://example.com/legend.png');
+ t.deepEqual(metadata.layers[0].boundingBox, [-180, -90, 180, 90]);
+
+ t.end();
+});
+
+test('WMS utils -> wmsCapabilitiesToDatasetMetadata resolves relative LegendURL', t => {
+ const capabilities = {
+ version: '1.3.0',
+ layers: [
+ {
+ name: 'OSM-WMS',
+ title: 'OpenStreetMap'
+ }
+ ],
+ json: {
+ Capability: {
+ Layer: {
+ Name: 'OSM-WMS',
+ Style: {
+ LegendURL: {
+ OnlineResource: {
+ 'xlink:href': '/legends/osm.png'
+ }
+ }
+ }
+ }
+ }
+ }
+ };
+
+ const metadata = wmsCapabilitiesToDatasetMetadata(capabilities, 'https://example.com/wms');
+ t.equal(metadata.layers[0].legendUrl, 'https://example.com/legends/osm.png');
+
+ t.end();
+});
+
+test('WMS utils -> wmsCapabilitiesToDatasetMetadata constructs GetLegendGraphic', t => {
+ const capabilities = {
+ version: '1.1.1',
+ name: 'WMS',
+ keywords: [],
+ requests: {},
+ layers: [
+ {
+ name: 'radar',
+ title: 'Radar',
+ keywords: [],
+ queryable: false
+ }
+ ]
+ };
+
+ const metadata = wmsCapabilitiesToDatasetMetadata(capabilities, 'https://example.com/wms');
+ const legendUrl = new URL(metadata.layers[0].legendUrl);
+
+ t.equal(legendUrl.searchParams.get('REQUEST'), 'GetLegendGraphic');
+ t.equal(legendUrl.searchParams.get('LAYER'), 'radar');
+ t.equal(legendUrl.searchParams.get('VERSION'), '1.1.1');
+
+ t.end();
+});