如何从 Openlayers 3 中的功能获取图层?

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

如果不遍历我所有地图图层的所有要素,或者在每个地图图层中存储一个人工图层 ID,我找不到从选择事件中的要素到它可能所属的图层的方法创建时的功能。这还不可能吗?

ol.js 3.7.0 ol.interaction.Selection -> 点击 -> 回调(事件){ event.selected[0] }

在我的应用程序的另一部分,我想从特征转到图层以确定特征上使用的样式,特别是它是否可见。

ol.Feature.getStyle() || ol.Feature -> (图层?) -> getStyle()

你可以试试过滤功能:

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

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

在此处查看代码片段:

在OL 5.3.0中,Select交互对象有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
});