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

时间:2015-07-08 15:52:51

标签: javascript maps openlayers-3

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()

3 个答案:

答案 0 :(得分:10)

您可以尝试使用过滤功能:

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

<强>更新

我想出了这个原型方法,它完成了这项工作:

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

答案 1 :(得分:0)

在Openlayers 4中 - map.forEachFeatureAtPixel可用于获取每个要素的父层。

请参阅此处的代码段:https://stackoverflow.com/a/50415743/2288488

答案 2 :(得分:0)

在OL 5.3.0中,“选择”交互对象具有getLayer()函数,以获取最后选择的要素的关联层。示例:

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
});
相关问题