diff --git a/doc/errors/index.md b/doc/errors/index.md index a762cfa599..e45f47bd3b 100644 --- a/doc/errors/index.md +++ b/doc/errors/index.md @@ -245,3 +245,7 @@ Layer opacity must be a number. `forEachFeatureAtCoordinate` cannot be used on a WebGL layer if the hit detection logic has not been enabled. This is done by providing adequate shaders using the `hitVertexShader` and `hitFragmentShader` properties of `WebGLPointsLayerRenderer`. + +### 67 + +A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both. \ No newline at end of file diff --git a/src/ol/layer/Layer.js b/src/ol/layer/Layer.js index bef87a803e..4d3d846845 100644 --- a/src/ol/layer/Layer.js +++ b/src/ol/layer/Layer.js @@ -9,6 +9,7 @@ import LayerProperty from './Property.js'; import {assign} from '../obj.js'; import RenderEventType from '../render/EventType.js'; import SourceState from '../source/State.js'; +import {assert} from '../asserts.js'; /** * @typedef {function(import("../PluggableMap.js").FrameState):HTMLElement} RenderFunction @@ -243,7 +244,13 @@ class Layer extends BaseLayer { if (map) { this.mapPrecomposeKey_ = listen(map, RenderEventType.PRECOMPOSE, function(evt) { const renderEvent = /** @type {import("../render/Event.js").default} */ (evt); - renderEvent.frameState.layerStatesArray.push(this.getLayerState(false)); + const layerStatesArray = renderEvent.frameState.layerStatesArray; + const layerState = this.getLayerState(false); + // A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both. + assert(!layerStatesArray.some(function(arrayLayerState) { + return arrayLayerState.layer === layerState.layer; + }), 67); + layerStatesArray.push(layerState); }, this); this.mapRenderKey_ = listen(this, EventType.CHANGE, map.render, map); this.changed(); diff --git a/test/spec/ol/layer/layer.test.js b/test/spec/ol/layer/layer.test.js index eb090511ac..f7c3aeb13e 100644 --- a/test/spec/ol/layer/layer.test.js +++ b/test/spec/ol/layer/layer.test.js @@ -631,8 +631,7 @@ describe('ol.layer.Layer', function() { map: map }); frameState = { - layerStatesArray: [], - layerStates: {} + layerStatesArray: [] }; }); @@ -651,6 +650,7 @@ describe('ol.layer.Layer', function() { layer.setZIndex(index); map.dispatchEvent(new RenderEvent('precompose', null, frameState, null)); const layerState = frameState.layerStatesArray[0]; + frameState.layerStatesArray.length = 0; expect(layerState.zIndex).to.be(index); }); });