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

标签 javascript maps openlayers-3

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

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

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

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

最佳答案

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

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

更新

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

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

关于javascript - 如何从 Openlayers 3 中的功能中获取图层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31297721/

相关文章:

javascript - Jqgrid 自定义 edittype custom_element 事件未触发

javascript - 将 onclick 更改图像附加到没有 id 标签的 varing img 数量

android - 尝试从 Google Cloud Messaging 消息更改 Google Maps v2 Api 上的标记时出现非法状态异常

javascript - 如何使用表单输入中的值填充表单的操作参数?

javascript - 使用 p2 旋转约束连接 2 个移相器 Sprite ,无需施加力

openlayers-3 - 如果文本标签适合其几何图形,则仅将 ol.style.Text 打印到多边形

javascript - openlayer 3.5 从点获取特征ID

openlayers-3 - OpenLayers 3 显示/隐藏图层

java - 在 Play 商店发布后 map 无法加载

javascript - 使用数组 javascript 中多个对象的值构建 map