Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  64] [ 4]  / answers: 1 / hits: 22050  / 9 Years ago, wed, july 8, 2015, 12:00:00

I can't find a way to go from a feature in a selection event to a layer that it may be a part of without traversing all the features of all my map layers, or storing an artificial layer ID within every feature at creation. Is this just not possible yet?



ol.js 3.7.0
ol.interaction.Selection -> click -> callback( event ){ event.selected[0] }



In another part of my app, I would like to go from the feature to the layer to determine the style being used on the feature, specifically whether or not it's visible.



ol.Feature.getStyle() || ol.Feature -> (layer?) -> getStyle()


More From » maps

 Answers
7

You could 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 prototypied 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'));
}
});

[#65884] Monday, July 6, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;