How to get a layer from a function in Openlayers 3?

I can’t find a way to move from a function in the selection event to a layer, which can be a part without going through all the functions of all layers of my map or saving the identifier of the artificial layer in each function to create. Is it not possible yet?

ol.js 3.7.0 ol.interaction.Selection β†’ click β†’ callback (event) {event.selected [0]}

In another part of my application, I would like to switch from a function to a layer to determine the style used in this function, in particular, regardless of whether it is visible.

ol.Feature.getStyle () || ol.Feature β†’ (layer?) β†’ getStyle ()

+9
javascript maps openlayers-3
source share
3 answers

You can try with the filter function:

var select = new ol.interaction.Select({ condition: ..., filter: function(feature, layer){ console.info(feature); console.info(layer.get('name')); } }); 

UPDATE

I came up with this prototype method, it does the job:

http://jsfiddle.net/jonataswalker/r242y7ke/

 /** * This is a workaround. * Returns the associated layer. * @param {ol.Map} map. * @return {ol.layer.Vector} Layer. */ ol.Feature.prototype.getLayer = function(map) { var this_ = this, layer_, layersToLookFor = []; /** * Populates array layersToLookFor with only * layers that have features */ var check = function(layer){ var source = layer.getSource(); if(source instanceof ol.source.Vector){ var features = source.getFeatures(); if(features.length > 0){ layersToLookFor.push({ layer: layer, features: features }); } } }; //loop through map layers map.getLayers().forEach(function(layer){ if (layer instanceof ol.layer.Group) { layer.getLayers().forEach(check); } else { check(layer); } }); layersToLookFor.forEach(function(obj){ var found = obj.features.some(function(feature){ return this_ === feature; }); if(found){ //this is the layer we want layer_ = obj.layer; } }); return layer_; }; select.on('select', function(evt){ var feature = evt.selected[0]; if(feature){ var layer = feature.getLayer(map); console.info(layer.getStyle()); console.info(layer.get('name')); } }); 
+10
source share

In Openlayers 4, map.forEachFeatureAtPixel can be used to go to the parent layer of each object.

See the code snippet here: fooobar.com/questions/12107020 / ...

0
source share

In OL 5.3.0, the Select interaction object has a getLayer () function to get the associated layer with the last selected object. Example:

 let selectClick = new Select({}); map.addInteraction(selectClick); selectClick.on('select', function(e) { let featureSelected = e.selected[0]; let layer = selectClick.getLayer(featureSelected); console.log(layer); // here you have the selected layer }); 
0
source share

All Articles