Openlayers 3:如何使用ol.interaction.Select以编程方式选择一个特性

Openlayers 3: how to select a feature programmatically using ol.interaction.Select?

本文关键字:选择 一个 方式 编程 何使用 ol Select interaction Openlayers      更新时间:2023-09-26

我正在使用OpenLayers v3.6(这很重要,因为我发现的大多数解决方案都可能适用于OpenLayers 2)。

我有一个表,当我选择该表中的一行时,我想在OpenLayers地图上突出显示/选择相应的功能。所有的特征都是在同一个向量层(ol.layer.Vector)中的简单多边形(ol.geo . polygon )。

我像这样设置选择交互:

// there is a lot of other code here
...
addSelectListener: function() {
    this.SelectInteraction = new ol.interaction.Select({
        condition: ol.events.condition.singleClick,
        layers: function (layer) {
            // defines layer from which features are selectable
            return layer.get('id') == 'polygons_layer';
        },
        style: this.Style.Selected
    });
    // Map = ol.Map
    Map.addInteraction(this.SelectInteraction);
    this.SelectInteraction.on('select', this.selectPolygon, this);
}
...
selectPolygon: function(event) {
    var selectSrc = this.getSelectInfo(event);
    // some code that relies on selectSrc data
}
...
getSelectInfo: function (event) {
    var selectSrc = {
        deselected: null,
        selected: null,
        type: null                
    };
    if (event.selected.length == 0 && event.deselected.length == 1) {
        // click outside of polygon with previously selected
        selectSrc.type = 'deselect';
        selectSrc.deselected = {
            feature: event.deselected[0],
            id: event.deselected[0].getId()
        };
    } else if (event.deselected.length == 0 && event.selected.length == 1) {
        // click on polygon without previously selected
        selectSrc.type = 'select';
        selectSrc.selected = {
            feature: event.selected[0],
            id: event.selected[0].getId()
        }
    } else if (event.deselected.length == 0 && event.selected.length == 1) {
        // click on polygon with previously selected
        selectSrc.type = 'switch';
        selectSrc.deselected = {
            feature: event.deselected[0],
            id: event.deselected[0].getId()
        };
        selectSrc.selected = {
            feature: event.selected[0],
            id: event.selected[0].getId()
        }
    } else {
        selectSrc.type = 'out';
    }
    return selectSrc;
}

当我想通过点击地图上的多边形来选择它时,这个功能很好。但是我想要实现的是相同的,不是通过点击地图,而是点击地图外的一些元素(在我的例子中是表行,但它可以是任何东西)。

我想使用选择交互,因为它发出的事件,因为它的样式适用于所选的功能。但是,如果碰巧我可以在选择交互中操作选中的功能而不具有相同的事件,那就可以了。

我知道这个问题&回答- Openlayers 3:选择一个功能编程-但问题是,我不能要求在评论澄清(例如,究竟是什么mySelectControl),因为我没有任何声誉:)

方法是在链接的问题中。因此,将ol.Feature推入选定的集合:

var select = new ol.interaction.Select({
    //some options
});
map.addInteraction(select);
var selected_collection = select.getFeatures();
selected_collection.push(featurePoint);

如果您想触发select事件:

select.dispatchEvent('select');
// OR
select.dispatchEvent({
  type: 'select',
  selected: [featurePoly],
  deselected: []
});

看到演示!