Tuesday, 8 May 2018

javascript - How to get layer type in OpenLayers 3?



I would like to iterate through all of the added layers in an ol.Map instance and only select the vector layers. So far I could get the individual layers with the a property of the resulting object of map.getLayers(). As you can see on the image below, a is an array and contains an object related to the corresponding layer.


map.getLayers()


The layers in the array are described with a letter (T for tile, V for vector). My question is, how to extract that information for my script to process?


I have read a related post with an answer using a .CLASS_NAME property, but the OpenLayers 3 ol.layer object doesn't have such attribute.


Any other approach to get the layer type or proven fact, that one can't get this property after the layer objects are constructed is considered as a correct answer.



Answer



If anyone gets stuck with identifying a layer's type in OpenLayers 3, there is a more sophisticated JavaScript method to achieve this. As layer objects are created with layer constructors, the native instanceof JavaScript function can be used to check for layer type.


As the identification of a layer type usually gets into an if or switch clause, one could easily check for the presence of the constructor's prototype object in the layer, instead of storing the type as a property on construction.


var groupLyr = new ol.layer.Group();
groupLyr instanceof ol.layer.Group;

//true
groupLyr instanceof ol.layer.Vector;
//false

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...