OpenLayers – How to Get Layer Names in Map v6.14.1

javascriptlayersopenlayers

I'm trying to get name of layers added to OpenLayers v6.14.1, I found some methods but they were very old for instance: "map.layers" and one other method I found was :

let addLayers = map.getLayers();
let length =  addLayers.getLength();
for(let i=0;i<length;i++){
   console.log('layers added already name = ', map.getLayers().item(i).get('name'))
}

but when I used above method I got "undefined" message.

I'm going to know how I can get name of layers added to Openlayers map v6.14.1?

my layers are WMS

Best Answer

Layers in OL do not have names by default, but you can give layer a name by setting some custom layer property, like for example using custom option name: 'My layer name'. Then your code above will work.

Example of such a code would be:

var vector = new ol.layer.Vector({
  source: source,
  style: style,
  name: 'My layer name'
});