Merge pull request #12793 from tschaub/set-layers

Add a method to set the map layers
This commit is contained in:
Tim Schaub
2021-09-22 03:17:37 -05:00
committed by GitHub
2 changed files with 54 additions and 0 deletions

View File

@@ -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<import("./layer/Base.js").default>|Collection<import("./layer/Base.js").default>} 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<import("./layer/Base.js").default>} Layers.

View File

@@ -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({});