From a63735a6498a020a1a755525edfa4d594c9205b7 Mon Sep 17 00:00:00 2001 From: Tim Schaub Date: Tue, 21 Sep 2021 13:34:35 +0000 Subject: [PATCH] Add a method to set the map layers --- src/ol/PluggableMap.js | 17 +++++++++++++++ test/browser/spec/ol/Map.test.js | 37 ++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/ol/PluggableMap.js b/src/ol/PluggableMap.js index 3572686a66..3bdf0d6593 100644 --- a/src/ol/PluggableMap.js +++ b/src/ol/PluggableMap.js @@ -847,6 +847,23 @@ class PluggableMap extends BaseObject { return /** @type {LayerGroup} */ (this.get(MapProperty.LAYERGROUP)); } + /** + * Clear any existing layers and add layers to the map. + * @param {Array|Collection} layers The layers to be added to the map. + * @api + */ + setLayers(layers) { + const group = this.getLayerGroup(); + if (layers instanceof Collection) { + group.setLayers(layers); + return; + } + + const collection = group.getLayers(); + collection.clear(); + collection.extend(layers); + } + /** * Get the collection of layers associated with this map. * @return {!Collection} Layers. diff --git a/test/browser/spec/ol/Map.test.js b/test/browser/spec/ol/Map.test.js index c73d27a6cf..d96422eb79 100644 --- a/test/browser/spec/ol/Map.test.js +++ b/test/browser/spec/ol/Map.test.js @@ -1,3 +1,4 @@ +import Collection from '../../../../src/ol/Collection.js'; import Control from '../../../../src/ol/control/Control.js'; import DoubleClickZoom from '../../../../src/ol/interaction/DoubleClickZoom.js'; import DragPan from '../../../../src/ol/interaction/DragPan.js'; @@ -179,6 +180,42 @@ describe('ol/Map', function () { }); }); + describe('#setLayers()', function () { + it('adds an array of layers to the map', function () { + const map = new Map({}); + + const layer0 = new TileLayer(); + const layer1 = new TileLayer(); + map.setLayers([layer0, layer1]); + + const collection = map.getLayers(); + expect(collection.getLength()).to.be(2); + expect(collection.item(0)).to.be(layer0); + expect(collection.item(1)).to.be(layer1); + }); + + it('clears any existing layers', function () { + const map = new Map({layers: [new TileLayer()]}); + + map.setLayers([new TileLayer(), new TileLayer()]); + + expect(map.getLayers().getLength()).to.be(2); + }); + + it('also works with collections', function () { + const map = new Map({}); + + const layer0 = new TileLayer(); + const layer1 = new TileLayer(); + map.setLayers(new Collection([layer0, layer1])); + + const collection = map.getLayers(); + expect(collection.getLength()).to.be(2); + expect(collection.item(0)).to.be(layer0); + expect(collection.item(1)).to.be(layer1); + }); + }); + describe('#addInteraction()', function () { it('adds an interaction to the map', function () { const map = new Map({});