在 select 上获取功能 ID

Getting a feature id on select

我无法从我的地图中获取我 select 地图项的 ID。这是我如何添加功能的示例:

var mylayer = map.getLayer('mylayerid');
var layersrc = mylayer.getSource();

var feature = new ol.Feature(new ol.geom.Point([0, 0]));
feature.setId(54);

layersrc.addFeature(feature);

这是我select使用功能的设置:

var selectSingleClick = new ol.interaction.Select();
    selectSingleClick.on('select', function(e) {
        // tried many things with e but can't get id of selected feature
    });
    map.addInteraction(selectSingleClick);

有没有合适的方法来获取特征id?谢谢!

我找到了收集id的方法,虽然有点绕。我跟着pointermove事件不断采集鼠标的位置。然后,当单击地图时,会捕获鼠标在那一瞬间的位置,我们现在可以循环遍历该像素位置的每个要素。

map.on('singleclick', function(evt) {
    var pixel = map.getPixelFromCoordinate(evt.coordinate);
    map.forEachFeatureAtPixel(pixel, function(feature) {
        console.log(feature.getId()); // id of selected feature
    });
});

如果您在该位置拥有多个地图项,您将获得多项地图项。希望这对遇到此问题的其他人有所帮助。